blob: ad101f862c865719cb0b4fc20fcb8290a1a47610 [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;
Romain Guyc5d55862011-01-21 19:01:46 -0800713 // We used to use the following condition to choose 32 bits drawing caches:
714 // PixelFormat.hasAlpha(lp.format) || lp.format == PixelFormat.RGBX_8888
715 // However, windows are now always 32 bits by default, so choose 32 bits
716 attachInfo.mUse32BitDrawingCache = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800717 attachInfo.mHasWindowFocus = false;
718 attachInfo.mWindowVisibility = viewVisibility;
719 attachInfo.mRecomputeGlobalAttributes = false;
720 attachInfo.mKeepScreenOn = false;
721 viewVisibilityChanged = false;
Dianne Hackborn694f79b2010-03-17 19:44:59 -0700722 mLastConfiguration.setTo(host.getResources().getConfiguration());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800723 host.dispatchAttachedToWindow(attachInfo, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800724 //Log.i(TAG, "Screen on initialized: " + attachInfo.mKeepScreenOn);
svetoslavganov75986cf2009-05-14 22:28:01 -0700725
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800726 } else {
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700727 desiredWindowWidth = frame.width();
728 desiredWindowHeight = frame.height();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800729 if (desiredWindowWidth != mWidth || desiredWindowHeight != mHeight) {
Jeff Brownc5ed5912010-07-14 18:48:53 -0700730 if (DEBUG_ORIENTATION) Log.v(TAG,
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700731 "View " + host + " resized to: " + frame);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800732 fullRedrawNeeded = true;
733 mLayoutRequested = true;
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800734 windowSizeMayChange = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800735 }
736 }
737
738 if (viewVisibilityChanged) {
739 attachInfo.mWindowVisibility = viewVisibility;
740 host.dispatchWindowVisibilityChanged(viewVisibility);
741 if (viewVisibility != View.VISIBLE || mNewSurfaceNeeded) {
Romain Guyb051e892010-09-28 19:09:36 -0700742 if (mAttachInfo.mHardwareRenderer != null) {
743 mAttachInfo.mHardwareRenderer.destroy(false);
Romain Guy4caa4ed2010-08-25 14:46:24 -0700744 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800745 }
746 if (viewVisibility == View.GONE) {
747 // After making a window gone, we will count it as being
748 // shown for the first time the next time it gets focus.
749 mHasHadWindowFocus = false;
750 }
751 }
752
753 boolean insetsChanged = false;
Romain Guy8506ab42009-06-11 17:35:47 -0700754
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800755 if (mLayoutRequested) {
Romain Guy15df6702009-08-17 20:17:30 -0700756 // Execute enqueued actions on every layout in case a view that was detached
757 // enqueued an action after being detached
758 getRunQueue().executeActions(attachInfo.mHandler);
759
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800760 final Resources res = mView.getContext().getResources();
761
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800762 if (mFirst) {
763 host.fitSystemWindows(mAttachInfo.mContentInsets);
764 // make sure touch mode code executes by setting cached value
765 // to opposite of the added touch mode.
766 mAttachInfo.mInTouchMode = !mAddedTouchMode;
Romain Guy2d4cff62010-04-09 15:39:00 -0700767 ensureTouchModeLocally(mAddedTouchMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800768 } else {
769 if (!mAttachInfo.mContentInsets.equals(mPendingContentInsets)) {
Dianne Hackborn0f761d62010-11-30 22:06:10 -0800770 if (mWidth > 0 && mHeight > 0 &&
771 mSurface != null && mSurface.isValid() &&
772 mAttachInfo.mHardwareRenderer != null &&
773 mAttachInfo.mHardwareRenderer.isEnabled() &&
774 lp != null && !PixelFormat.formatHasAlpha(lp.format)) {
775
776 disposeResizeBitmap();
777
778 boolean completed = false;
779 try {
780 mResizeBitmap = Bitmap.createBitmap(mWidth, mHeight,
781 Bitmap.Config.ARGB_8888);
782 mResizeBitmap.setHasAlpha(false);
783 Canvas canvas = new Canvas(mResizeBitmap);
784 int yoff;
785 final boolean scrolling = mScroller != null
786 && mScroller.computeScrollOffset();
787 if (scrolling) {
788 yoff = mScroller.getCurrY();
789 mScroller.abortAnimation();
790 } else {
791 yoff = mScrollY;
792 }
793 canvas.translate(0, -yoff);
794 if (mTranslator != null) {
795 mTranslator.translateCanvas(canvas);
796 }
797 canvas.setScreenDensity(mAttachInfo.mScalingRequired
798 ? DisplayMetrics.DENSITY_DEVICE : 0);
799 mView.draw(canvas);
800 mResizeBitmapStartTime = SystemClock.uptimeMillis();
801 mResizeBitmapDuration = mView.getResources().getInteger(
802 com.android.internal.R.integer.config_mediumAnimTime);
803 completed = true;
804 } catch (OutOfMemoryError e) {
805 Log.w(TAG, "Not enough memory for content change anim buffer", e);
806 } finally {
807 if (!completed) {
808 mResizeBitmap = null;
809 }
810 }
811 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800812 mAttachInfo.mContentInsets.set(mPendingContentInsets);
813 host.fitSystemWindows(mAttachInfo.mContentInsets);
814 insetsChanged = true;
815 if (DEBUG_LAYOUT) Log.v(TAG, "Content insets changing to: "
816 + mAttachInfo.mContentInsets);
817 }
818 if (!mAttachInfo.mVisibleInsets.equals(mPendingVisibleInsets)) {
819 mAttachInfo.mVisibleInsets.set(mPendingVisibleInsets);
820 if (DEBUG_LAYOUT) Log.v(TAG, "Visible insets changing to: "
821 + mAttachInfo.mVisibleInsets);
822 }
823 if (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT
824 || lp.height == ViewGroup.LayoutParams.WRAP_CONTENT) {
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800825 windowSizeMayChange = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800826
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800827 DisplayMetrics packageMetrics = res.getDisplayMetrics();
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700828 desiredWindowWidth = packageMetrics.widthPixels;
829 desiredWindowHeight = packageMetrics.heightPixels;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800830 }
831 }
832
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800833 // Ask host how big it wants to be
Jeff Brownc5ed5912010-07-14 18:48:53 -0700834 if (DEBUG_ORIENTATION || DEBUG_LAYOUT) Log.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800835 "Measuring " + host + " in display " + desiredWindowWidth
836 + "x" + desiredWindowHeight + "...");
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800837
838 boolean goodMeasure = false;
839 if (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT
840 || lp.height == ViewGroup.LayoutParams.WRAP_CONTENT) {
841 // On large screens, we don't want to allow dialogs to just
842 // stretch to fill the entire width of the screen to display
843 // one line of text. First try doing the layout at a smaller
844 // size to see if it will fit.
845 final DisplayMetrics packageMetrics = res.getDisplayMetrics();
846 res.getValue(com.android.internal.R.dimen.config_prefDialogWidth, mTmpValue, true);
847 int baseSize = 0;
848 if (mTmpValue.type == TypedValue.TYPE_DIMENSION) {
849 baseSize = (int)mTmpValue.getDimension(packageMetrics);
850 }
851 if (DEBUG_DIALOG) Log.v(TAG, "Window " + mView + ": baseSize=" + baseSize);
Dianne Hackborn7d3a5bc2010-11-29 22:52:12 -0800852 if (baseSize != 0 && desiredWindowWidth > baseSize) {
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800853 childWidthMeasureSpec = getRootMeasureSpec(baseSize, lp.width);
854 childHeightMeasureSpec = getRootMeasureSpec(desiredWindowHeight, lp.height);
855 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
856 if (DEBUG_DIALOG) Log.v(TAG, "Window " + mView + ": measured ("
Dianne Hackborn189ee182010-12-02 21:48:53 -0800857 + host.getMeasuredWidth() + "," + host.getMeasuredHeight() + ")");
858 if ((host.getMeasuredWidthAndState()&View.MEASURED_STATE_TOO_SMALL) == 0) {
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800859 goodMeasure = true;
860 } else {
861 // Didn't fit in that size... try expanding a bit.
862 baseSize = (baseSize+desiredWindowWidth)/2;
863 if (DEBUG_DIALOG) Log.v(TAG, "Window " + mView + ": next baseSize="
864 + baseSize);
Dianne Hackborn189ee182010-12-02 21:48:53 -0800865 childWidthMeasureSpec = getRootMeasureSpec(baseSize, lp.width);
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800866 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
867 if (DEBUG_DIALOG) Log.v(TAG, "Window " + mView + ": measured ("
Dianne Hackborn189ee182010-12-02 21:48:53 -0800868 + host.getMeasuredWidth() + "," + host.getMeasuredHeight() + ")");
869 if ((host.getMeasuredWidthAndState()&View.MEASURED_STATE_TOO_SMALL) == 0) {
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800870 if (DEBUG_DIALOG) Log.v(TAG, "Good!");
871 goodMeasure = true;
872 }
873 }
874 }
875 }
876
877 if (!goodMeasure) {
878 childWidthMeasureSpec = getRootMeasureSpec(desiredWindowWidth, lp.width);
879 childHeightMeasureSpec = getRootMeasureSpec(desiredWindowHeight, lp.height);
880 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
Adam Powellaa0b92c2010-12-13 22:38:53 -0800881 if (mWidth != host.getMeasuredWidth() || mHeight != host.getMeasuredHeight()) {
882 windowSizeMayChange = true;
883 }
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800884 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800885
886 if (DBG) {
887 System.out.println("======================================");
888 System.out.println("performTraversals -- after measure");
889 host.debug();
890 }
891 }
892
893 if (attachInfo.mRecomputeGlobalAttributes) {
894 //Log.i(TAG, "Computing screen on!");
895 attachInfo.mRecomputeGlobalAttributes = false;
896 boolean oldVal = attachInfo.mKeepScreenOn;
897 attachInfo.mKeepScreenOn = false;
898 host.dispatchCollectViewAttributes(0);
899 if (attachInfo.mKeepScreenOn != oldVal) {
900 params = lp;
901 //Log.i(TAG, "Keep screen on changed: " + attachInfo.mKeepScreenOn);
902 }
903 }
904
905 if (mFirst || attachInfo.mViewVisibilityChanged) {
906 attachInfo.mViewVisibilityChanged = false;
907 int resizeMode = mSoftInputMode &
908 WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST;
909 // If we are in auto resize mode, then we need to determine
910 // what mode to use now.
911 if (resizeMode == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED) {
912 final int N = attachInfo.mScrollContainers.size();
913 for (int i=0; i<N; i++) {
914 if (attachInfo.mScrollContainers.get(i).isShown()) {
915 resizeMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE;
916 }
917 }
918 if (resizeMode == 0) {
919 resizeMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN;
920 }
921 if ((lp.softInputMode &
922 WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) != resizeMode) {
923 lp.softInputMode = (lp.softInputMode &
924 ~WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) |
925 resizeMode;
926 params = lp;
927 }
928 }
929 }
Romain Guy8506ab42009-06-11 17:35:47 -0700930
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800931 if (params != null && (host.mPrivateFlags & View.REQUEST_TRANSPARENT_REGIONS) != 0) {
932 if (!PixelFormat.formatHasAlpha(params.format)) {
933 params.format = PixelFormat.TRANSLUCENT;
934 }
935 }
936
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800937 boolean windowShouldResize = mLayoutRequested && windowSizeMayChange
Dianne Hackborn189ee182010-12-02 21:48:53 -0800938 && ((mWidth != host.getMeasuredWidth() || mHeight != host.getMeasuredHeight())
Romain Guy2e4f4262010-04-06 11:07:52 -0700939 || (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT &&
940 frame.width() < desiredWindowWidth && frame.width() != mWidth)
941 || (lp.height == ViewGroup.LayoutParams.WRAP_CONTENT &&
942 frame.height() < desiredWindowHeight && frame.height() != mHeight));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800943
944 final boolean computesInternalInsets =
945 attachInfo.mTreeObserver.hasComputeInternalInsetsListeners();
Romain Guy812ccbe2010-06-01 14:07:24 -0700946
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800947 boolean insetsPending = false;
948 int relayoutResult = 0;
Romain Guy812ccbe2010-06-01 14:07:24 -0700949
950 if (mFirst || windowShouldResize || insetsChanged ||
951 viewVisibilityChanged || params != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800952
953 if (viewVisibility == View.VISIBLE) {
954 // If this window is giving internal insets to the window
955 // manager, and it is being added or changing its visibility,
956 // then we want to first give the window manager "fake"
957 // insets to cause it to effectively ignore the content of
958 // the window during layout. This avoids it briefly causing
959 // other windows to resize/move based on the raw frame of the
960 // window, waiting until we can finish laying out this window
961 // and get back to the window manager with the ultimately
962 // computed insets.
Romain Guy812ccbe2010-06-01 14:07:24 -0700963 insetsPending = computesInternalInsets && (mFirst || viewVisibilityChanged);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800964 }
965
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700966 if (mSurfaceHolder != null) {
967 mSurfaceHolder.mSurfaceLock.lock();
968 mDrawingAllowed = true;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700969 }
Romain Guy812ccbe2010-06-01 14:07:24 -0700970
Romain Guyc361da82010-10-25 15:29:10 -0700971 boolean hwInitialized = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800972 boolean contentInsetsChanged = false;
Romain Guy13922e02009-05-12 17:56:14 -0700973 boolean visibleInsetsChanged;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700974 boolean hadSurface = mSurface.isValid();
Romain Guy812ccbe2010-06-01 14:07:24 -0700975
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800976 try {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800977 int fl = 0;
978 if (params != null) {
979 fl = params.flags;
980 if (attachInfo.mKeepScreenOn) {
981 params.flags |= WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
982 }
983 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700984 if (DEBUG_LAYOUT) {
Dianne Hackborn189ee182010-12-02 21:48:53 -0800985 Log.i(TAG, "host=w:" + host.getMeasuredWidth() + ", h:" +
986 host.getMeasuredHeight() + ", params=" + params);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700987 }
Romain Guy2a83f002011-01-18 18:28:21 -0800988
989 final int surfaceGenerationId = mSurface.getGenerationId();
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700990 relayoutResult = relayoutWindow(params, viewVisibility, insetsPending);
991
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800992 if (params != null) {
993 params.flags = fl;
994 }
995
996 if (DEBUG_LAYOUT) Log.v(TAG, "relayout: frame=" + frame.toShortString()
997 + " content=" + mPendingContentInsets.toShortString()
998 + " visible=" + mPendingVisibleInsets.toShortString()
999 + " surface=" + mSurface);
Romain Guy8506ab42009-06-11 17:35:47 -07001000
Dianne Hackborn694f79b2010-03-17 19:44:59 -07001001 if (mPendingConfiguration.seq != 0) {
1002 if (DEBUG_CONFIGURATION) Log.v(TAG, "Visible with new config: "
1003 + mPendingConfiguration);
1004 updateConfiguration(mPendingConfiguration, !mFirst);
1005 mPendingConfiguration.seq = 0;
1006 }
1007
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001008 contentInsetsChanged = !mPendingContentInsets.equals(
1009 mAttachInfo.mContentInsets);
1010 visibleInsetsChanged = !mPendingVisibleInsets.equals(
1011 mAttachInfo.mVisibleInsets);
1012 if (contentInsetsChanged) {
1013 mAttachInfo.mContentInsets.set(mPendingContentInsets);
1014 host.fitSystemWindows(mAttachInfo.mContentInsets);
1015 if (DEBUG_LAYOUT) Log.v(TAG, "Content insets changing to: "
1016 + mAttachInfo.mContentInsets);
1017 }
1018 if (visibleInsetsChanged) {
1019 mAttachInfo.mVisibleInsets.set(mPendingVisibleInsets);
1020 if (DEBUG_LAYOUT) Log.v(TAG, "Visible insets changing to: "
1021 + mAttachInfo.mVisibleInsets);
1022 }
1023
1024 if (!hadSurface) {
1025 if (mSurface.isValid()) {
1026 // If we are creating a new surface, then we need to
1027 // completely redraw it. Also, when we get to the
1028 // point of drawing it we will hold off and schedule
1029 // a new traversal instead. This is so we can tell the
1030 // window manager about all of the windows being displayed
1031 // before actually drawing them, so it can display then
1032 // all at once.
1033 newSurface = true;
1034 fullRedrawNeeded = true;
Jack Palevich61a6e682009-10-09 17:37:50 -07001035 mPreviousTransparentRegion.setEmpty();
Romain Guy8506ab42009-06-11 17:35:47 -07001036
Romain Guyb051e892010-09-28 19:09:36 -07001037 if (mAttachInfo.mHardwareRenderer != null) {
Romain Guyc361da82010-10-25 15:29:10 -07001038 hwInitialized = mAttachInfo.mHardwareRenderer.initialize(mHolder);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001039 }
1040 }
1041 } else if (!mSurface.isValid()) {
1042 // If the surface has been removed, then reset the scroll
1043 // positions.
1044 mLastScrolledFocus = null;
1045 mScrollY = mCurScrollY = 0;
1046 if (mScroller != null) {
1047 mScroller.abortAnimation();
1048 }
Dianne Hackborn0f761d62010-11-30 22:06:10 -08001049 disposeResizeBitmap();
Romain Guy2a83f002011-01-18 18:28:21 -08001050 } else if (surfaceGenerationId != mSurface.getGenerationId() &&
1051 mSurfaceHolder == null && mAttachInfo.mHardwareRenderer != null) {
1052 mAttachInfo.mHardwareRenderer.updateSurface(mHolder);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001053 }
1054 } catch (RemoteException e) {
1055 }
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001056
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001057 if (DEBUG_ORIENTATION) Log.v(
Jeff Brownc5ed5912010-07-14 18:48:53 -07001058 TAG, "Relayout returned: frame=" + frame + ", surface=" + mSurface);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001059
1060 attachInfo.mWindowLeft = frame.left;
1061 attachInfo.mWindowTop = frame.top;
1062
1063 // !!FIXME!! This next section handles the case where we did not get the
1064 // window size we asked for. We should avoid this by getting a maximum size from
1065 // the window session beforehand.
1066 mWidth = frame.width();
1067 mHeight = frame.height();
1068
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001069 if (mSurfaceHolder != null) {
1070 // The app owns the surface; tell it about what is going on.
1071 if (mSurface.isValid()) {
1072 // XXX .copyFrom() doesn't work!
1073 //mSurfaceHolder.mSurface.copyFrom(mSurface);
1074 mSurfaceHolder.mSurface = mSurface;
1075 }
1076 mSurfaceHolder.mSurfaceLock.unlock();
1077 if (mSurface.isValid()) {
1078 if (!hadSurface) {
1079 mSurfaceHolder.ungetCallbacks();
1080
1081 mIsCreating = true;
1082 mSurfaceHolderCallback.surfaceCreated(mSurfaceHolder);
1083 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
1084 if (callbacks != null) {
1085 for (SurfaceHolder.Callback c : callbacks) {
1086 c.surfaceCreated(mSurfaceHolder);
1087 }
1088 }
1089 surfaceChanged = true;
1090 }
1091 if (surfaceChanged) {
1092 mSurfaceHolderCallback.surfaceChanged(mSurfaceHolder,
1093 lp.format, mWidth, mHeight);
1094 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
1095 if (callbacks != null) {
1096 for (SurfaceHolder.Callback c : callbacks) {
1097 c.surfaceChanged(mSurfaceHolder, lp.format,
1098 mWidth, mHeight);
1099 }
1100 }
1101 }
1102 mIsCreating = false;
1103 } else if (hadSurface) {
1104 mSurfaceHolder.ungetCallbacks();
1105 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
1106 mSurfaceHolderCallback.surfaceDestroyed(mSurfaceHolder);
1107 if (callbacks != null) {
1108 for (SurfaceHolder.Callback c : callbacks) {
1109 c.surfaceDestroyed(mSurfaceHolder);
1110 }
1111 }
1112 mSurfaceHolder.mSurfaceLock.lock();
1113 // Make surface invalid.
1114 //mSurfaceHolder.mSurface.copyFrom(mSurface);
1115 mSurfaceHolder.mSurface = new Surface();
1116 mSurfaceHolder.mSurfaceLock.unlock();
1117 }
1118 }
Romain Guy53389bd2010-09-07 17:16:32 -07001119
Romain Guy6b5108b2011-01-04 16:11:10 -08001120 if (hwInitialized || ((windowShouldResize || params != null) &&
Romain Guydbf78bd2010-12-07 17:04:03 -08001121 mAttachInfo.mHardwareRenderer != null &&
1122 mAttachInfo.mHardwareRenderer.isEnabled())) {
Romain Guyb051e892010-09-28 19:09:36 -07001123 mAttachInfo.mHardwareRenderer.setup(mWidth, mHeight);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001124 }
1125
1126 boolean focusChangedDueToTouchMode = ensureTouchModeLocally(
Romain Guy2d4cff62010-04-09 15:39:00 -07001127 (relayoutResult&WindowManagerImpl.RELAYOUT_IN_TOUCH_MODE) != 0);
Dianne Hackborn189ee182010-12-02 21:48:53 -08001128 if (focusChangedDueToTouchMode || mWidth != host.getMeasuredWidth()
1129 || mHeight != host.getMeasuredHeight() || contentInsetsChanged) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001130 childWidthMeasureSpec = getRootMeasureSpec(mWidth, lp.width);
1131 childHeightMeasureSpec = getRootMeasureSpec(mHeight, lp.height);
1132
1133 if (DEBUG_LAYOUT) Log.v(TAG, "Ooops, something changed! mWidth="
Dianne Hackborn189ee182010-12-02 21:48:53 -08001134 + mWidth + " measuredWidth=" + host.getMeasuredWidth()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001135 + " mHeight=" + mHeight
Dianne Hackborn189ee182010-12-02 21:48:53 -08001136 + " measuredHeight" + host.getMeasuredHeight()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001137 + " coveredInsetsChanged=" + contentInsetsChanged);
Romain Guy8506ab42009-06-11 17:35:47 -07001138
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001139 // Ask host how big it wants to be
1140 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
1141
1142 // Implementation of weights from WindowManager.LayoutParams
1143 // We just grow the dimensions as needed and re-measure if
1144 // needs be
Dianne Hackborn189ee182010-12-02 21:48:53 -08001145 int width = host.getMeasuredWidth();
1146 int height = host.getMeasuredHeight();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001147 boolean measureAgain = false;
1148
1149 if (lp.horizontalWeight > 0.0f) {
1150 width += (int) ((mWidth - width) * lp.horizontalWeight);
1151 childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(width,
1152 MeasureSpec.EXACTLY);
1153 measureAgain = true;
1154 }
1155 if (lp.verticalWeight > 0.0f) {
1156 height += (int) ((mHeight - height) * lp.verticalWeight);
1157 childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(height,
1158 MeasureSpec.EXACTLY);
1159 measureAgain = true;
1160 }
1161
1162 if (measureAgain) {
1163 if (DEBUG_LAYOUT) Log.v(TAG,
1164 "And hey let's measure once more: width=" + width
1165 + " height=" + height);
1166 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
1167 }
1168
1169 mLayoutRequested = true;
1170 }
1171 }
1172
1173 final boolean didLayout = mLayoutRequested;
1174 boolean triggerGlobalLayoutListener = didLayout
1175 || attachInfo.mRecomputeGlobalAttributes;
1176 if (didLayout) {
1177 mLayoutRequested = false;
1178 mScrollMayChange = true;
1179 if (DEBUG_ORIENTATION || DEBUG_LAYOUT) Log.v(
Jeff Brownc5ed5912010-07-14 18:48:53 -07001180 TAG, "Laying out " + host + " to (" +
Dianne Hackborn189ee182010-12-02 21:48:53 -08001181 host.getMeasuredWidth() + ", " + host.getMeasuredHeight() + ")");
Romain Guy13922e02009-05-12 17:56:14 -07001182 long startTime = 0L;
Romain Guy5429e1d2010-09-07 12:38:00 -07001183 if (ViewDebug.DEBUG_PROFILE_LAYOUT) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001184 startTime = SystemClock.elapsedRealtime();
1185 }
Dianne Hackborn189ee182010-12-02 21:48:53 -08001186 host.layout(0, 0, host.getMeasuredWidth(), host.getMeasuredHeight());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001187
Romain Guy13922e02009-05-12 17:56:14 -07001188 if (Config.DEBUG && ViewDebug.consistencyCheckEnabled) {
1189 if (!host.dispatchConsistencyCheck(ViewDebug.CONSISTENCY_LAYOUT)) {
1190 throw new IllegalStateException("The view hierarchy is an inconsistent state,"
1191 + "please refer to the logs with the tag "
1192 + ViewDebug.CONSISTENCY_LOG_TAG + " for more infomation.");
1193 }
1194 }
1195
Romain Guy5429e1d2010-09-07 12:38:00 -07001196 if (ViewDebug.DEBUG_PROFILE_LAYOUT) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001197 EventLog.writeEvent(60001, SystemClock.elapsedRealtime() - startTime);
1198 }
1199
1200 // By this point all views have been sized and positionned
1201 // We can compute the transparent area
1202
1203 if ((host.mPrivateFlags & View.REQUEST_TRANSPARENT_REGIONS) != 0) {
1204 // start out transparent
1205 // TODO: AVOID THAT CALL BY CACHING THE RESULT?
1206 host.getLocationInWindow(mTmpLocation);
1207 mTransparentRegion.set(mTmpLocation[0], mTmpLocation[1],
1208 mTmpLocation[0] + host.mRight - host.mLeft,
1209 mTmpLocation[1] + host.mBottom - host.mTop);
1210
1211 host.gatherTransparentRegion(mTransparentRegion);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001212 if (mTranslator != null) {
1213 mTranslator.translateRegionInWindowToScreen(mTransparentRegion);
1214 }
1215
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001216 if (!mTransparentRegion.equals(mPreviousTransparentRegion)) {
1217 mPreviousTransparentRegion.set(mTransparentRegion);
1218 // reconfigure window manager
1219 try {
1220 sWindowSession.setTransparentRegion(mWindow, mTransparentRegion);
1221 } catch (RemoteException e) {
1222 }
1223 }
1224 }
1225
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001226 if (DBG) {
1227 System.out.println("======================================");
1228 System.out.println("performTraversals -- after setFrame");
1229 host.debug();
1230 }
1231 }
1232
1233 if (triggerGlobalLayoutListener) {
1234 attachInfo.mRecomputeGlobalAttributes = false;
1235 attachInfo.mTreeObserver.dispatchOnGlobalLayout();
1236 }
1237
1238 if (computesInternalInsets) {
Jeff Brownfbf09772011-01-16 14:06:57 -08001239 // Clear the original insets.
1240 final ViewTreeObserver.InternalInsetsInfo insets = attachInfo.mGivenInternalInsets;
1241 insets.reset();
1242
1243 // Compute new insets in place.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001244 attachInfo.mTreeObserver.dispatchOnComputeInternalInsets(insets);
Jeff Brownfbf09772011-01-16 14:06:57 -08001245
1246 // Tell the window manager.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001247 if (insetsPending || !mLastGivenInsets.equals(insets)) {
1248 mLastGivenInsets.set(insets);
Jeff Brownfbf09772011-01-16 14:06:57 -08001249
1250 // Translate insets to screen coordinates if needed.
1251 final Rect contentInsets;
1252 final Rect visibleInsets;
1253 final Region touchableRegion;
1254 if (mTranslator != null) {
1255 contentInsets = mTranslator.getTranslatedContentInsets(insets.contentInsets);
1256 visibleInsets = mTranslator.getTranslatedVisibleInsets(insets.visibleInsets);
1257 touchableRegion = mTranslator.getTranslatedTouchableArea(insets.touchableRegion);
1258 } else {
1259 contentInsets = insets.contentInsets;
1260 visibleInsets = insets.visibleInsets;
1261 touchableRegion = insets.touchableRegion;
1262 }
1263
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001264 try {
1265 sWindowSession.setInsets(mWindow, insets.mTouchableInsets,
Jeff Brownfbf09772011-01-16 14:06:57 -08001266 contentInsets, visibleInsets, touchableRegion);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001267 } catch (RemoteException e) {
1268 }
1269 }
1270 }
Romain Guy8506ab42009-06-11 17:35:47 -07001271
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001272 if (mFirst) {
1273 // handle first focus request
1274 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: mView.hasFocus()="
1275 + mView.hasFocus());
1276 if (mView != null) {
1277 if (!mView.hasFocus()) {
1278 mView.requestFocus(View.FOCUS_FORWARD);
1279 mFocusedView = mRealFocusedView = mView.findFocus();
1280 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: requested focused view="
1281 + mFocusedView);
1282 } else {
1283 mRealFocusedView = mView.findFocus();
1284 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: existing focused view="
1285 + mRealFocusedView);
1286 }
1287 }
1288 }
1289
1290 mFirst = false;
1291 mWillDrawSoon = false;
1292 mNewSurfaceNeeded = false;
1293 mViewVisibility = viewVisibility;
1294
1295 if (mAttachInfo.mHasWindowFocus) {
1296 final boolean imTarget = WindowManager.LayoutParams
1297 .mayUseInputMethod(mWindowAttributes.flags);
1298 if (imTarget != mLastWasImTarget) {
1299 mLastWasImTarget = imTarget;
1300 InputMethodManager imm = InputMethodManager.peekInstance();
1301 if (imm != null && imTarget) {
1302 imm.startGettingWindowFocus(mView);
1303 imm.onWindowFocus(mView, mView.findFocus(),
1304 mWindowAttributes.softInputMode,
1305 !mHasHadWindowFocus, mWindowAttributes.flags);
1306 }
1307 }
1308 }
Romain Guy8506ab42009-06-11 17:35:47 -07001309
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001310 boolean cancelDraw = attachInfo.mTreeObserver.dispatchOnPreDraw();
1311
1312 if (!cancelDraw && !newSurface) {
1313 mFullRedrawNeeded = false;
1314 draw(fullRedrawNeeded);
1315
1316 if ((relayoutResult&WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0
1317 || mReportNextDraw) {
1318 if (LOCAL_LOGV) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001319 Log.v(TAG, "FINISHED DRAWING: " + mWindowAttributes.getTitle());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001320 }
1321 mReportNextDraw = false;
Dianne Hackbornd76b67c2010-07-13 17:48:30 -07001322 if (mSurfaceHolder != null && mSurface.isValid()) {
1323 mSurfaceHolderCallback.surfaceRedrawNeeded(mSurfaceHolder);
1324 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
1325 if (callbacks != null) {
1326 for (SurfaceHolder.Callback c : callbacks) {
1327 if (c instanceof SurfaceHolder.Callback2) {
1328 ((SurfaceHolder.Callback2)c).surfaceRedrawNeeded(
1329 mSurfaceHolder);
1330 }
1331 }
1332 }
1333 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001334 try {
1335 sWindowSession.finishDrawing(mWindow);
1336 } catch (RemoteException e) {
1337 }
1338 }
1339 } else {
1340 // We were supposed to report when we are done drawing. Since we canceled the
1341 // draw, remember it here.
1342 if ((relayoutResult&WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0) {
1343 mReportNextDraw = true;
1344 }
1345 if (fullRedrawNeeded) {
1346 mFullRedrawNeeded = true;
1347 }
1348 // Try again
1349 scheduleTraversals();
1350 }
1351 }
1352
1353 public void requestTransparentRegion(View child) {
1354 // the test below should not fail unless someone is messing with us
1355 checkThread();
1356 if (mView == child) {
1357 mView.mPrivateFlags |= View.REQUEST_TRANSPARENT_REGIONS;
1358 // Need to make sure we re-evaluate the window attributes next
1359 // time around, to ensure the window has the correct format.
1360 mWindowAttributesChanged = true;
Mathias Agopian1bd80ad2010-11-04 17:13:39 -07001361 requestLayout();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001362 }
1363 }
1364
1365 /**
1366 * Figures out the measure spec for the root view in a window based on it's
1367 * layout params.
1368 *
1369 * @param windowSize
1370 * The available width or height of the window
1371 *
1372 * @param rootDimension
1373 * The layout params for one dimension (width or height) of the
1374 * window.
1375 *
1376 * @return The measure spec to use to measure the root view.
1377 */
1378 private int getRootMeasureSpec(int windowSize, int rootDimension) {
1379 int measureSpec;
1380 switch (rootDimension) {
1381
Romain Guy980a9382010-01-08 15:06:28 -08001382 case ViewGroup.LayoutParams.MATCH_PARENT:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001383 // Window can't resize. Force root view to be windowSize.
1384 measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.EXACTLY);
1385 break;
1386 case ViewGroup.LayoutParams.WRAP_CONTENT:
1387 // Window can resize. Set max size for root view.
1388 measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.AT_MOST);
1389 break;
1390 default:
1391 // Window wants to be an exact size. Force root view to be that size.
1392 measureSpec = MeasureSpec.makeMeasureSpec(rootDimension, MeasureSpec.EXACTLY);
1393 break;
1394 }
1395 return measureSpec;
1396 }
1397
Dianne Hackborn0f761d62010-11-30 22:06:10 -08001398 int mHardwareYOffset;
1399 int mResizeAlpha;
1400 final Paint mResizePaint = new Paint();
1401
1402 public void onHardwarePreDraw(Canvas canvas) {
1403 canvas.translate(0, -mHardwareYOffset);
1404 }
1405
1406 public void onHardwarePostDraw(Canvas canvas) {
1407 if (mResizeBitmap != null) {
1408 canvas.translate(0, mHardwareYOffset);
1409 mResizePaint.setAlpha(mResizeAlpha);
1410 canvas.drawBitmap(mResizeBitmap, 0, 0, mResizePaint);
1411 }
1412 }
1413
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001414 private void draw(boolean fullRedrawNeeded) {
1415 Surface surface = mSurface;
1416 if (surface == null || !surface.isValid()) {
1417 return;
1418 }
1419
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001420 if (!sFirstDrawComplete) {
1421 synchronized (sFirstDrawHandlers) {
1422 sFirstDrawComplete = true;
Romain Guy812ccbe2010-06-01 14:07:24 -07001423 final int count = sFirstDrawHandlers.size();
1424 for (int i = 0; i< count; i++) {
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001425 post(sFirstDrawHandlers.get(i));
1426 }
1427 }
1428 }
1429
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001430 scrollToRectOrFocus(null, false);
1431
1432 if (mAttachInfo.mViewScrollChanged) {
1433 mAttachInfo.mViewScrollChanged = false;
1434 mAttachInfo.mTreeObserver.dispatchOnScrollChanged();
1435 }
Romain Guy8506ab42009-06-11 17:35:47 -07001436
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001437 int yoff;
Dianne Hackborn0f761d62010-11-30 22:06:10 -08001438 boolean animating = mScroller != null && mScroller.computeScrollOffset();
1439 if (animating) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001440 yoff = mScroller.getCurrY();
1441 } else {
1442 yoff = mScrollY;
1443 }
1444 if (mCurScrollY != yoff) {
1445 mCurScrollY = yoff;
1446 fullRedrawNeeded = true;
1447 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001448 float appScale = mAttachInfo.mApplicationScale;
1449 boolean scalingRequired = mAttachInfo.mScalingRequired;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001450
Dianne Hackborn0f761d62010-11-30 22:06:10 -08001451 int resizeAlpha = 0;
1452 if (mResizeBitmap != null) {
1453 long deltaTime = SystemClock.uptimeMillis() - mResizeBitmapStartTime;
1454 if (deltaTime < mResizeBitmapDuration) {
1455 float amt = deltaTime/(float)mResizeBitmapDuration;
1456 amt = mResizeInterpolator.getInterpolation(amt);
1457 animating = true;
1458 resizeAlpha = 255 - (int)(amt*255);
1459 } else {
1460 disposeResizeBitmap();
1461 }
1462 }
1463
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001464 Rect dirty = mDirty;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001465 if (mSurfaceHolder != null) {
1466 // The app owns the surface, we won't draw.
1467 dirty.setEmpty();
Dianne Hackborn0f761d62010-11-30 22:06:10 -08001468 if (animating) {
1469 if (mScroller != null) {
1470 mScroller.abortAnimation();
1471 }
1472 disposeResizeBitmap();
1473 }
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001474 return;
1475 }
Romain Guy58ef7fb2010-09-13 12:52:37 -07001476
1477 if (fullRedrawNeeded) {
1478 mAttachInfo.mIgnoreDirtyState = true;
1479 dirty.union(0, 0, (int) (mWidth * appScale + 0.5f), (int) (mHeight * appScale + 0.5f));
1480 }
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001481
Romain Guyb051e892010-09-28 19:09:36 -07001482 if (mAttachInfo.mHardwareRenderer != null && mAttachInfo.mHardwareRenderer.isEnabled()) {
Romain Guyfd507262010-10-10 15:42:49 -07001483 if (!dirty.isEmpty() || mIsAnimating) {
Romain Guy101e2ae2010-10-11 12:41:21 -07001484 mIsAnimating = false;
Romain Guyfd507262010-10-10 15:42:49 -07001485 dirty.setEmpty();
Dianne Hackborn0f761d62010-11-30 22:06:10 -08001486 mHardwareYOffset = yoff;
1487 mResizeAlpha = resizeAlpha;
1488 mAttachInfo.mHardwareRenderer.draw(mView, mAttachInfo, this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001489 }
Romain Guy812ccbe2010-06-01 14:07:24 -07001490
Dianne Hackborn0f761d62010-11-30 22:06:10 -08001491 if (animating) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001492 mFullRedrawNeeded = true;
1493 scheduleTraversals();
1494 }
Romain Guy812ccbe2010-06-01 14:07:24 -07001495
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001496 return;
1497 }
1498
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001499 if (DEBUG_ORIENTATION || DEBUG_DRAW) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001500 Log.v(TAG, "Draw " + mView + "/"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001501 + mWindowAttributes.getTitle()
1502 + ": dirty={" + dirty.left + "," + dirty.top
1503 + "," + dirty.right + "," + dirty.bottom + "} surface="
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001504 + surface + " surface.isValid()=" + surface.isValid() + ", appScale:" +
1505 appScale + ", width=" + mWidth + ", height=" + mHeight);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001506 }
1507
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001508 if (!dirty.isEmpty() || mIsAnimating) {
1509 Canvas canvas;
1510 try {
1511 int left = dirty.left;
1512 int top = dirty.top;
1513 int right = dirty.right;
1514 int bottom = dirty.bottom;
1515 canvas = surface.lockCanvas(dirty);
Romain Guy5bcdff42009-05-14 21:27:18 -07001516
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001517 if (left != dirty.left || top != dirty.top || right != dirty.right ||
1518 bottom != dirty.bottom) {
1519 mAttachInfo.mIgnoreDirtyState = true;
1520 }
1521
1522 // TODO: Do this in native
1523 canvas.setDensity(mDensity);
1524 } catch (Surface.OutOfResourcesException e) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001525 Log.e(TAG, "OutOfResourcesException locking surface", e);
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001526 // TODO: we should ask the window manager to do something!
1527 // for now we just do nothing
1528 return;
1529 } catch (IllegalArgumentException e) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001530 Log.e(TAG, "IllegalArgumentException locking surface", e);
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001531 // TODO: we should ask the window manager to do something!
1532 // for now we just do nothing
1533 return;
Romain Guy5bcdff42009-05-14 21:27:18 -07001534 }
1535
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001536 try {
1537 if (!dirty.isEmpty() || mIsAnimating) {
1538 long startTime = 0L;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001539
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001540 if (DEBUG_ORIENTATION || DEBUG_DRAW) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001541 Log.v(TAG, "Surface " + surface + " drawing to bitmap w="
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001542 + canvas.getWidth() + ", h=" + canvas.getHeight());
1543 //canvas.drawARGB(255, 255, 0, 0);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001544 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001545
Romain Guy5429e1d2010-09-07 12:38:00 -07001546 if (ViewDebug.DEBUG_PROFILE_DRAWING) {
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001547 startTime = SystemClock.elapsedRealtime();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001548 }
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001549
1550 // If this bitmap's format includes an alpha channel, we
1551 // need to clear it before drawing so that the child will
1552 // properly re-composite its drawing on a transparent
1553 // background. This automatically respects the clip/dirty region
1554 // or
1555 // If we are applying an offset, we need to clear the area
1556 // where the offset doesn't appear to avoid having garbage
1557 // left in the blank areas.
1558 if (!canvas.isOpaque() || yoff != 0) {
1559 canvas.drawColor(0, PorterDuff.Mode.CLEAR);
1560 }
1561
1562 dirty.setEmpty();
1563 mIsAnimating = false;
1564 mAttachInfo.mDrawingTime = SystemClock.uptimeMillis();
1565 mView.mPrivateFlags |= View.DRAWN;
1566
1567 if (DEBUG_DRAW) {
1568 Context cxt = mView.getContext();
1569 Log.i(TAG, "Drawing: package:" + cxt.getPackageName() +
1570 ", metrics=" + cxt.getResources().getDisplayMetrics() +
1571 ", compatibilityInfo=" + cxt.getResources().getCompatibilityInfo());
1572 }
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001573 try {
1574 canvas.translate(0, -yoff);
1575 if (mTranslator != null) {
1576 mTranslator.translateCanvas(canvas);
1577 }
1578 canvas.setScreenDensity(scalingRequired
1579 ? DisplayMetrics.DENSITY_DEVICE : 0);
1580 mView.draw(canvas);
1581 } finally {
1582 mAttachInfo.mIgnoreDirtyState = false;
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001583 }
1584
1585 if (Config.DEBUG && ViewDebug.consistencyCheckEnabled) {
1586 mView.dispatchConsistencyCheck(ViewDebug.CONSISTENCY_DRAWING);
1587 }
1588
Romain Guy5429e1d2010-09-07 12:38:00 -07001589 if (SHOW_FPS || ViewDebug.DEBUG_SHOW_FPS) {
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001590 int now = (int)SystemClock.elapsedRealtime();
1591 if (sDrawTime != 0) {
1592 nativeShowFPS(canvas, now - sDrawTime);
1593 }
1594 sDrawTime = now;
1595 }
1596
Romain Guy5429e1d2010-09-07 12:38:00 -07001597 if (ViewDebug.DEBUG_PROFILE_DRAWING) {
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001598 EventLog.writeEvent(60000, SystemClock.elapsedRealtime() - startTime);
1599 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001600 }
1601
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001602 } finally {
1603 surface.unlockCanvasAndPost(canvas);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001604 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001605 }
1606
1607 if (LOCAL_LOGV) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001608 Log.v(TAG, "Surface " + surface + " unlockCanvasAndPost");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001609 }
Romain Guy8506ab42009-06-11 17:35:47 -07001610
Dianne Hackborn0f761d62010-11-30 22:06:10 -08001611 if (animating) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001612 mFullRedrawNeeded = true;
1613 scheduleTraversals();
1614 }
1615 }
1616
1617 boolean scrollToRectOrFocus(Rect rectangle, boolean immediate) {
1618 final View.AttachInfo attachInfo = mAttachInfo;
1619 final Rect ci = attachInfo.mContentInsets;
1620 final Rect vi = attachInfo.mVisibleInsets;
1621 int scrollY = 0;
1622 boolean handled = false;
Romain Guy8506ab42009-06-11 17:35:47 -07001623
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001624 if (vi.left > ci.left || vi.top > ci.top
1625 || vi.right > ci.right || vi.bottom > ci.bottom) {
1626 // We'll assume that we aren't going to change the scroll
1627 // offset, since we want to avoid that unless it is actually
1628 // going to make the focus visible... otherwise we scroll
1629 // all over the place.
1630 scrollY = mScrollY;
1631 // We can be called for two different situations: during a draw,
1632 // to update the scroll position if the focus has changed (in which
1633 // case 'rectangle' is null), or in response to a
1634 // requestChildRectangleOnScreen() call (in which case 'rectangle'
1635 // is non-null and we just want to scroll to whatever that
1636 // rectangle is).
1637 View focus = mRealFocusedView;
Romain Guye8b16522009-07-14 13:06:42 -07001638
1639 // When in touch mode, focus points to the previously focused view,
1640 // which may have been removed from the view hierarchy. The following
Joe Onoratob71193b2009-11-24 18:34:42 -05001641 // line checks whether the view is still in our hierarchy.
1642 if (focus == null || focus.mAttachInfo != mAttachInfo) {
Romain Guye8b16522009-07-14 13:06:42 -07001643 mRealFocusedView = null;
1644 return false;
1645 }
1646
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001647 if (focus != mLastScrolledFocus) {
1648 // If the focus has changed, then ignore any requests to scroll
1649 // to a rectangle; first we want to make sure the entire focus
1650 // view is visible.
1651 rectangle = null;
1652 }
1653 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Eval scroll: focus=" + focus
1654 + " rectangle=" + rectangle + " ci=" + ci
1655 + " vi=" + vi);
1656 if (focus == mLastScrolledFocus && !mScrollMayChange
1657 && rectangle == null) {
1658 // Optimization: if the focus hasn't changed since last
1659 // time, and no layout has happened, then just leave things
1660 // as they are.
1661 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Keeping scroll y="
1662 + mScrollY + " vi=" + vi.toShortString());
1663 } else if (focus != null) {
1664 // We need to determine if the currently focused view is
1665 // within the visible part of the window and, if not, apply
1666 // a pan so it can be seen.
1667 mLastScrolledFocus = focus;
1668 mScrollMayChange = false;
1669 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Need to scroll?");
1670 // Try to find the rectangle from the focus view.
1671 if (focus.getGlobalVisibleRect(mVisRect, null)) {
1672 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Root w="
1673 + mView.getWidth() + " h=" + mView.getHeight()
1674 + " ci=" + ci.toShortString()
1675 + " vi=" + vi.toShortString());
1676 if (rectangle == null) {
1677 focus.getFocusedRect(mTempRect);
1678 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Focus " + focus
1679 + ": focusRect=" + mTempRect.toShortString());
Dianne Hackborn1c6a8942010-03-23 16:34:20 -07001680 if (mView instanceof ViewGroup) {
1681 ((ViewGroup) mView).offsetDescendantRectToMyCoords(
1682 focus, mTempRect);
1683 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001684 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1685 "Focus in window: focusRect="
1686 + mTempRect.toShortString()
1687 + " visRect=" + mVisRect.toShortString());
1688 } else {
1689 mTempRect.set(rectangle);
1690 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1691 "Request scroll to rect: "
1692 + mTempRect.toShortString()
1693 + " visRect=" + mVisRect.toShortString());
1694 }
1695 if (mTempRect.intersect(mVisRect)) {
1696 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1697 "Focus window visible rect: "
1698 + mTempRect.toShortString());
1699 if (mTempRect.height() >
1700 (mView.getHeight()-vi.top-vi.bottom)) {
1701 // If the focus simply is not going to fit, then
1702 // best is probably just to leave things as-is.
1703 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1704 "Too tall; leaving scrollY=" + scrollY);
1705 } else if ((mTempRect.top-scrollY) < vi.top) {
1706 scrollY -= vi.top - (mTempRect.top-scrollY);
1707 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1708 "Top covered; scrollY=" + scrollY);
1709 } else if ((mTempRect.bottom-scrollY)
1710 > (mView.getHeight()-vi.bottom)) {
1711 scrollY += (mTempRect.bottom-scrollY)
1712 - (mView.getHeight()-vi.bottom);
1713 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1714 "Bottom covered; scrollY=" + scrollY);
1715 }
1716 handled = true;
1717 }
1718 }
1719 }
1720 }
Romain Guy8506ab42009-06-11 17:35:47 -07001721
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001722 if (scrollY != mScrollY) {
1723 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Pan scroll changed: old="
1724 + mScrollY + " , new=" + scrollY);
Dianne Hackborn0f761d62010-11-30 22:06:10 -08001725 if (!immediate && mResizeBitmap == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001726 if (mScroller == null) {
1727 mScroller = new Scroller(mView.getContext());
1728 }
1729 mScroller.startScroll(0, mScrollY, 0, scrollY-mScrollY);
1730 } else if (mScroller != null) {
1731 mScroller.abortAnimation();
1732 }
1733 mScrollY = scrollY;
1734 }
Romain Guy8506ab42009-06-11 17:35:47 -07001735
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001736 return handled;
1737 }
Romain Guy8506ab42009-06-11 17:35:47 -07001738
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001739 public void requestChildFocus(View child, View focused) {
1740 checkThread();
1741 if (mFocusedView != focused) {
1742 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(mFocusedView, focused);
1743 scheduleTraversals();
1744 }
1745 mFocusedView = mRealFocusedView = focused;
1746 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Request child focus: focus now "
1747 + mFocusedView);
1748 }
1749
1750 public void clearChildFocus(View child) {
1751 checkThread();
1752
1753 View oldFocus = mFocusedView;
1754
1755 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Clearing child focus");
1756 mFocusedView = mRealFocusedView = null;
1757 if (mView != null && !mView.hasFocus()) {
1758 // If a view gets the focus, the listener will be invoked from requestChildFocus()
1759 if (!mView.requestFocus(View.FOCUS_FORWARD)) {
1760 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
1761 }
1762 } else if (oldFocus != null) {
1763 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
1764 }
1765 }
1766
1767
1768 public void focusableViewAvailable(View v) {
1769 checkThread();
1770
1771 if (mView != null && !mView.hasFocus()) {
1772 v.requestFocus();
1773 } else {
1774 // the one case where will transfer focus away from the current one
1775 // is if the current view is a view group that prefers to give focus
1776 // to its children first AND the view is a descendant of it.
1777 mFocusedView = mView.findFocus();
1778 boolean descendantsHaveDibsOnFocus =
1779 (mFocusedView instanceof ViewGroup) &&
1780 (((ViewGroup) mFocusedView).getDescendantFocusability() ==
1781 ViewGroup.FOCUS_AFTER_DESCENDANTS);
1782 if (descendantsHaveDibsOnFocus && isViewDescendantOf(v, mFocusedView)) {
1783 // If a view gets the focus, the listener will be invoked from requestChildFocus()
1784 v.requestFocus();
1785 }
1786 }
1787 }
1788
1789 public void recomputeViewAttributes(View child) {
1790 checkThread();
1791 if (mView == child) {
1792 mAttachInfo.mRecomputeGlobalAttributes = true;
1793 if (!mWillDrawSoon) {
1794 scheduleTraversals();
1795 }
1796 }
1797 }
1798
1799 void dispatchDetachedFromWindow() {
Romain Guy90fc03b2011-01-16 13:07:15 -08001800 if (mView != null && mView.mAttachInfo != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001801 mView.dispatchDetachedFromWindow();
1802 }
1803
1804 mView = null;
1805 mAttachInfo.mRootView = null;
Mathias Agopian5583dc62009-07-09 16:28:11 -07001806 mAttachInfo.mSurface = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001807
Romain Guy29d89972010-09-22 16:10:57 -07001808 destroyHardwareRenderer();
Romain Guy4caa4ed2010-08-25 14:46:24 -07001809
Dianne Hackborn0586a1b2009-09-06 21:08:27 -07001810 mSurface.release();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001811
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001812 if (mInputChannel != null) {
1813 if (mInputQueueCallback != null) {
1814 mInputQueueCallback.onInputQueueDestroyed(mInputQueue);
1815 mInputQueueCallback = null;
1816 } else {
1817 InputQueue.unregisterInputChannel(mInputChannel);
Jeff Brown46b9ac02010-04-22 18:58:52 -07001818 }
1819 }
1820
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001821 try {
1822 sWindowSession.remove(mWindow);
1823 } catch (RemoteException e) {
1824 }
Jeff Brown349703e2010-06-22 01:27:15 -07001825
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001826 // Dispose the input channel after removing the window so the Window Manager
1827 // doesn't interpret the input channel being closed as an abnormal termination.
1828 if (mInputChannel != null) {
1829 mInputChannel.dispose();
1830 mInputChannel = null;
Jeff Brown349703e2010-06-22 01:27:15 -07001831 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001832 }
Romain Guy8506ab42009-06-11 17:35:47 -07001833
Dianne Hackborn694f79b2010-03-17 19:44:59 -07001834 void updateConfiguration(Configuration config, boolean force) {
1835 if (DEBUG_CONFIGURATION) Log.v(TAG,
1836 "Applying new config to window "
1837 + mWindowAttributes.getTitle()
1838 + ": " + config);
1839 synchronized (sConfigCallbacks) {
1840 for (int i=sConfigCallbacks.size()-1; i>=0; i--) {
1841 sConfigCallbacks.get(i).onConfigurationChanged(config);
1842 }
1843 }
1844 if (mView != null) {
1845 // At this point the resources have been updated to
1846 // have the most recent config, whatever that is. Use
1847 // the on in them which may be newer.
1848 if (mView != null) {
1849 config = mView.getResources().getConfiguration();
1850 }
1851 if (force || mLastConfiguration.diff(config) != 0) {
1852 mLastConfiguration.setTo(config);
1853 mView.dispatchConfigurationChanged(config);
1854 }
1855 }
1856 }
1857
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001858 /**
1859 * Return true if child is an ancestor of parent, (or equal to the parent).
1860 */
1861 private static boolean isViewDescendantOf(View child, View parent) {
1862 if (child == parent) {
1863 return true;
1864 }
1865
1866 final ViewParent theParent = child.getParent();
1867 return (theParent instanceof ViewGroup) && isViewDescendantOf((View) theParent, parent);
1868 }
1869
Romain Guycdb86672010-03-18 18:54:50 -07001870 private static void forceLayout(View view) {
1871 view.forceLayout();
1872 if (view instanceof ViewGroup) {
1873 ViewGroup group = (ViewGroup) view;
1874 final int count = group.getChildCount();
1875 for (int i = 0; i < count; i++) {
1876 forceLayout(group.getChildAt(i));
1877 }
1878 }
1879 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001880
1881 public final static int DO_TRAVERSAL = 1000;
1882 public final static int DIE = 1001;
1883 public final static int RESIZED = 1002;
1884 public final static int RESIZED_REPORT = 1003;
1885 public final static int WINDOW_FOCUS_CHANGED = 1004;
1886 public final static int DISPATCH_KEY = 1005;
1887 public final static int DISPATCH_POINTER = 1006;
1888 public final static int DISPATCH_TRACKBALL = 1007;
1889 public final static int DISPATCH_APP_VISIBILITY = 1008;
1890 public final static int DISPATCH_GET_NEW_SURFACE = 1009;
1891 public final static int FINISHED_EVENT = 1010;
1892 public final static int DISPATCH_KEY_FROM_IME = 1011;
1893 public final static int FINISH_INPUT_CONNECTION = 1012;
1894 public final static int CHECK_FOCUS = 1013;
Dianne Hackbornffa42482009-09-23 22:20:11 -07001895 public final static int CLOSE_SYSTEM_DIALOGS = 1014;
Christopher Tatea53146c2010-09-07 11:57:52 -07001896 public final static int DISPATCH_DRAG_EVENT = 1015;
Chris Tate91e9bb32010-10-12 12:58:43 -07001897 public final static int DISPATCH_DRAG_LOCATION_EVENT = 1016;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001898
1899 @Override
1900 public void handleMessage(Message msg) {
1901 switch (msg.what) {
1902 case View.AttachInfo.INVALIDATE_MSG:
1903 ((View) msg.obj).invalidate();
1904 break;
1905 case View.AttachInfo.INVALIDATE_RECT_MSG:
1906 final View.AttachInfo.InvalidateInfo info = (View.AttachInfo.InvalidateInfo) msg.obj;
1907 info.target.invalidate(info.left, info.top, info.right, info.bottom);
1908 info.release();
1909 break;
1910 case DO_TRAVERSAL:
1911 if (mProfile) {
1912 Debug.startMethodTracing("ViewRoot");
1913 }
1914
1915 performTraversals();
1916
1917 if (mProfile) {
1918 Debug.stopMethodTracing();
1919 mProfile = false;
1920 }
1921 break;
1922 case FINISHED_EVENT:
1923 handleFinishedEvent(msg.arg1, msg.arg2 != 0);
1924 break;
1925 case DISPATCH_KEY:
Jeff Brown92ff1dd2010-08-11 16:16:06 -07001926 deliverKeyEvent((KeyEvent)msg.obj, msg.arg1 != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001927 break;
Jeff Brown3915bb82010-11-05 15:02:16 -07001928 case DISPATCH_POINTER:
1929 deliverPointerEvent((MotionEvent) msg.obj, msg.arg1 != 0);
1930 break;
1931 case DISPATCH_TRACKBALL:
1932 deliverTrackballEvent((MotionEvent) msg.obj, msg.arg1 != 0);
1933 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001934 case DISPATCH_APP_VISIBILITY:
1935 handleAppVisibility(msg.arg1 != 0);
1936 break;
1937 case DISPATCH_GET_NEW_SURFACE:
1938 handleGetNewSurface();
1939 break;
1940 case RESIZED:
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001941 ResizedInfo ri = (ResizedInfo)msg.obj;
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001942
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001943 if (mWinFrame.width() == msg.arg1 && mWinFrame.height() == msg.arg2
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001944 && mPendingContentInsets.equals(ri.coveredInsets)
Dianne Hackbornd49258f2010-03-26 00:44:29 -07001945 && mPendingVisibleInsets.equals(ri.visibleInsets)
1946 && ((ResizedInfo)msg.obj).newConfig == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001947 break;
1948 }
1949 // fall through...
1950 case RESIZED_REPORT:
1951 if (mAdded) {
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001952 Configuration config = ((ResizedInfo)msg.obj).newConfig;
1953 if (config != null) {
Dianne Hackborn694f79b2010-03-17 19:44:59 -07001954 updateConfiguration(config, false);
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001955 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001956 mWinFrame.left = 0;
1957 mWinFrame.right = msg.arg1;
1958 mWinFrame.top = 0;
1959 mWinFrame.bottom = msg.arg2;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001960 mPendingContentInsets.set(((ResizedInfo)msg.obj).coveredInsets);
1961 mPendingVisibleInsets.set(((ResizedInfo)msg.obj).visibleInsets);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001962 if (msg.what == RESIZED_REPORT) {
1963 mReportNextDraw = true;
1964 }
Romain Guycdb86672010-03-18 18:54:50 -07001965
1966 if (mView != null) {
1967 forceLayout(mView);
1968 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001969 requestLayout();
1970 }
1971 break;
1972 case WINDOW_FOCUS_CHANGED: {
1973 if (mAdded) {
1974 boolean hasWindowFocus = msg.arg1 != 0;
1975 mAttachInfo.mHasWindowFocus = hasWindowFocus;
1976 if (hasWindowFocus) {
1977 boolean inTouchMode = msg.arg2 != 0;
Romain Guy2d4cff62010-04-09 15:39:00 -07001978 ensureTouchModeLocally(inTouchMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001979
Romain Guyc361da82010-10-25 15:29:10 -07001980 if (mAttachInfo.mHardwareRenderer != null &&
1981 mSurface != null && mSurface.isValid()) {
Romain Guyb051e892010-09-28 19:09:36 -07001982 mAttachInfo.mHardwareRenderer.initializeIfNeeded(mWidth, mHeight,
1983 mAttachInfo, mHolder);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001984 }
1985 }
Romain Guy8506ab42009-06-11 17:35:47 -07001986
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001987 mLastWasImTarget = WindowManager.LayoutParams
1988 .mayUseInputMethod(mWindowAttributes.flags);
Romain Guy8506ab42009-06-11 17:35:47 -07001989
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001990 InputMethodManager imm = InputMethodManager.peekInstance();
1991 if (mView != null) {
1992 if (hasWindowFocus && imm != null && mLastWasImTarget) {
1993 imm.startGettingWindowFocus(mView);
1994 }
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07001995 mAttachInfo.mKeyDispatchState.reset();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001996 mView.dispatchWindowFocusChanged(hasWindowFocus);
1997 }
svetoslavganov75986cf2009-05-14 22:28:01 -07001998
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001999 // Note: must be done after the focus change callbacks,
2000 // so all of the view state is set up correctly.
2001 if (hasWindowFocus) {
2002 if (imm != null && mLastWasImTarget) {
2003 imm.onWindowFocus(mView, mView.findFocus(),
2004 mWindowAttributes.softInputMode,
2005 !mHasHadWindowFocus, mWindowAttributes.flags);
2006 }
2007 // Clear the forward bit. We can just do this directly, since
2008 // the window manager doesn't care about it.
2009 mWindowAttributes.softInputMode &=
2010 ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
2011 ((WindowManager.LayoutParams)mView.getLayoutParams())
2012 .softInputMode &=
2013 ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
2014 mHasHadWindowFocus = true;
2015 }
svetoslavganov75986cf2009-05-14 22:28:01 -07002016
2017 if (hasWindowFocus && mView != null) {
2018 sendAccessibilityEvents();
2019 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002020 }
2021 } break;
2022 case DIE:
Dianne Hackborn94d69142009-09-28 22:14:42 -07002023 doDie();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002024 break;
The Android Open Source Project10592532009-03-18 17:39:46 -07002025 case DISPATCH_KEY_FROM_IME: {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002026 if (LOCAL_LOGV) Log.v(
Jeff Brownc5ed5912010-07-14 18:48:53 -07002027 TAG, "Dispatching key "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002028 + msg.obj + " from IME to " + mView);
The Android Open Source Project10592532009-03-18 17:39:46 -07002029 KeyEvent event = (KeyEvent)msg.obj;
2030 if ((event.getFlags()&KeyEvent.FLAG_FROM_SYSTEM) != 0) {
2031 // The IME is trying to say this event is from the
2032 // system! Bad bad bad!
Romain Guy812ccbe2010-06-01 14:07:24 -07002033 event = KeyEvent.changeFlags(event, event.getFlags() & ~KeyEvent.FLAG_FROM_SYSTEM);
The Android Open Source Project10592532009-03-18 17:39:46 -07002034 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002035 deliverKeyEventPostIme((KeyEvent)msg.obj, false);
The Android Open Source Project10592532009-03-18 17:39:46 -07002036 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002037 case FINISH_INPUT_CONNECTION: {
2038 InputMethodManager imm = InputMethodManager.peekInstance();
2039 if (imm != null) {
2040 imm.reportFinishInputConnection((InputConnection)msg.obj);
2041 }
2042 } break;
2043 case CHECK_FOCUS: {
2044 InputMethodManager imm = InputMethodManager.peekInstance();
2045 if (imm != null) {
2046 imm.checkFocus();
2047 }
2048 } break;
Dianne Hackbornffa42482009-09-23 22:20:11 -07002049 case CLOSE_SYSTEM_DIALOGS: {
2050 if (mView != null) {
2051 mView.onCloseSystemDialogs((String)msg.obj);
2052 }
2053 } break;
Chris Tate91e9bb32010-10-12 12:58:43 -07002054 case DISPATCH_DRAG_EVENT:
2055 case DISPATCH_DRAG_LOCATION_EVENT: {
Christopher Tate7fb8b562011-01-20 13:46:41 -08002056 DragEvent event = (DragEvent)msg.obj;
2057 event.mLocalState = mLocalDragState; // only present when this app called startDrag()
2058 handleDragEvent(event);
Christopher Tatea53146c2010-09-07 11:57:52 -07002059 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002060 }
2061 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002062
Jeff Brown3915bb82010-11-05 15:02:16 -07002063 private void startInputEvent(InputQueue.FinishedCallback finishedCallback) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07002064 if (mFinishedCallback != null) {
2065 Slog.w(TAG, "Received a new input event from the input queue but there is "
2066 + "already an unfinished input event in progress.");
2067 }
2068
2069 mFinishedCallback = finishedCallback;
2070 }
2071
Jeff Brown3915bb82010-11-05 15:02:16 -07002072 private void finishInputEvent(boolean handled) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07002073 if (LOCAL_LOGV) Log.v(TAG, "Telling window manager input event is finished");
Jeff Brown92ff1dd2010-08-11 16:16:06 -07002074
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002075 if (mFinishedCallback != null) {
Jeff Brown3915bb82010-11-05 15:02:16 -07002076 mFinishedCallback.finished(handled);
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002077 mFinishedCallback = null;
Jeff Brown92ff1dd2010-08-11 16:16:06 -07002078 } else {
Jeff Brown93ed4e32010-09-23 13:51:48 -07002079 Slog.w(TAG, "Attempted to tell the input queue that the current input event "
2080 + "is finished but there is no input event actually in progress.");
Jeff Brown46b9ac02010-04-22 18:58:52 -07002081 }
2082 }
2083
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002084 /**
2085 * Something in the current window tells us we need to change the touch mode. For
2086 * example, we are not in touch mode, and the user touches the screen.
2087 *
2088 * If the touch mode has changed, tell the window manager, and handle it locally.
2089 *
2090 * @param inTouchMode Whether we want to be in touch mode.
2091 * @return True if the touch mode changed and focus changed was changed as a result
2092 */
2093 boolean ensureTouchMode(boolean inTouchMode) {
2094 if (DBG) Log.d("touchmode", "ensureTouchMode(" + inTouchMode + "), current "
2095 + "touch mode is " + mAttachInfo.mInTouchMode);
2096 if (mAttachInfo.mInTouchMode == inTouchMode) return false;
2097
2098 // tell the window manager
2099 try {
2100 sWindowSession.setInTouchMode(inTouchMode);
2101 } catch (RemoteException e) {
2102 throw new RuntimeException(e);
2103 }
2104
2105 // handle the change
Romain Guy2d4cff62010-04-09 15:39:00 -07002106 return ensureTouchModeLocally(inTouchMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002107 }
2108
2109 /**
2110 * Ensure that the touch mode for this window is set, and if it is changing,
2111 * take the appropriate action.
2112 * @param inTouchMode Whether we want to be in touch mode.
2113 * @return True if the touch mode changed and focus changed was changed as a result
2114 */
Romain Guy2d4cff62010-04-09 15:39:00 -07002115 private boolean ensureTouchModeLocally(boolean inTouchMode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002116 if (DBG) Log.d("touchmode", "ensureTouchModeLocally(" + inTouchMode + "), current "
2117 + "touch mode is " + mAttachInfo.mInTouchMode);
2118
2119 if (mAttachInfo.mInTouchMode == inTouchMode) return false;
2120
2121 mAttachInfo.mInTouchMode = inTouchMode;
2122 mAttachInfo.mTreeObserver.dispatchOnTouchModeChanged(inTouchMode);
2123
Romain Guy2d4cff62010-04-09 15:39:00 -07002124 return (inTouchMode) ? enterTouchMode() : leaveTouchMode();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002125 }
2126
2127 private boolean enterTouchMode() {
2128 if (mView != null) {
2129 if (mView.hasFocus()) {
2130 // note: not relying on mFocusedView here because this could
2131 // be when the window is first being added, and mFocused isn't
2132 // set yet.
2133 final View focused = mView.findFocus();
2134 if (focused != null && !focused.isFocusableInTouchMode()) {
2135
2136 final ViewGroup ancestorToTakeFocus =
2137 findAncestorToTakeFocusInTouchMode(focused);
2138 if (ancestorToTakeFocus != null) {
2139 // there is an ancestor that wants focus after its descendants that
2140 // is focusable in touch mode.. give it focus
2141 return ancestorToTakeFocus.requestFocus();
2142 } else {
2143 // nothing appropriate to have focus in touch mode, clear it out
2144 mView.unFocus();
2145 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(focused, null);
2146 mFocusedView = null;
2147 return true;
2148 }
2149 }
2150 }
2151 }
2152 return false;
2153 }
2154
2155
2156 /**
2157 * Find an ancestor of focused that wants focus after its descendants and is
2158 * focusable in touch mode.
2159 * @param focused The currently focused view.
2160 * @return An appropriate view, or null if no such view exists.
2161 */
2162 private ViewGroup findAncestorToTakeFocusInTouchMode(View focused) {
2163 ViewParent parent = focused.getParent();
2164 while (parent instanceof ViewGroup) {
2165 final ViewGroup vgParent = (ViewGroup) parent;
2166 if (vgParent.getDescendantFocusability() == ViewGroup.FOCUS_AFTER_DESCENDANTS
2167 && vgParent.isFocusableInTouchMode()) {
2168 return vgParent;
2169 }
2170 if (vgParent.isRootNamespace()) {
2171 return null;
2172 } else {
2173 parent = vgParent.getParent();
2174 }
2175 }
2176 return null;
2177 }
2178
2179 private boolean leaveTouchMode() {
2180 if (mView != null) {
2181 if (mView.hasFocus()) {
2182 // i learned the hard way to not trust mFocusedView :)
2183 mFocusedView = mView.findFocus();
2184 if (!(mFocusedView instanceof ViewGroup)) {
2185 // some view has focus, let it keep it
2186 return false;
2187 } else if (((ViewGroup)mFocusedView).getDescendantFocusability() !=
2188 ViewGroup.FOCUS_AFTER_DESCENDANTS) {
2189 // some view group has focus, and doesn't prefer its children
2190 // over itself for focus, so let them keep it.
2191 return false;
2192 }
2193 }
2194
2195 // find the best view to give focus to in this brave new non-touch-mode
2196 // world
2197 final View focused = focusSearch(null, View.FOCUS_DOWN);
2198 if (focused != null) {
2199 return focused.requestFocus(View.FOCUS_DOWN);
2200 }
2201 }
2202 return false;
2203 }
2204
Jeff Brown3915bb82010-11-05 15:02:16 -07002205 private void deliverPointerEvent(MotionEvent event, boolean sendDone) {
2206 // If there is no view, then the event will not be handled.
2207 if (mView == null || !mAdded) {
2208 finishPointerEvent(event, sendDone, false);
2209 return;
2210 }
2211
2212 // Translate the pointer event for compatibility, if needed.
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002213 if (mTranslator != null) {
2214 mTranslator.translateEventInScreenToAppWindow(event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002215 }
2216
Jeff Brown3915bb82010-11-05 15:02:16 -07002217 // Enter touch mode on the down.
2218 boolean isDown = event.getAction() == MotionEvent.ACTION_DOWN;
2219 if (isDown) {
2220 ensureTouchMode(true);
2221 }
2222 if(Config.LOGV) {
2223 captureMotionLog("captureDispatchPointer", event);
2224 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002225
Jeff Brown3915bb82010-11-05 15:02:16 -07002226 // Offset the scroll position.
2227 if (mCurScrollY != 0) {
2228 event.offsetLocation(0, mCurScrollY);
2229 }
2230 if (MEASURE_LATENCY) {
2231 lt.sample("A Dispatching TouchEvents", System.nanoTime() - event.getEventTimeNano());
2232 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002233
Jeff Brown3915bb82010-11-05 15:02:16 -07002234 // Remember the touch position for possible drag-initiation.
2235 mLastTouchPoint.x = event.getRawX();
2236 mLastTouchPoint.y = event.getRawY();
2237
2238 // Dispatch touch to view hierarchy.
2239 boolean handled = mView.dispatchTouchEvent(event);
2240 if (MEASURE_LATENCY) {
2241 lt.sample("B Dispatched TouchEvents ", System.nanoTime() - event.getEventTimeNano());
2242 }
2243 if (handled) {
2244 finishPointerEvent(event, sendDone, true);
2245 return;
2246 }
2247
2248 // Apply edge slop and try again, if appropriate.
2249 final int edgeFlags = event.getEdgeFlags();
2250 if (edgeFlags != 0 && mView instanceof ViewGroup) {
2251 final int edgeSlop = mViewConfiguration.getScaledEdgeSlop();
2252 int direction = View.FOCUS_UP;
2253 int x = (int)event.getX();
2254 int y = (int)event.getY();
2255 final int[] deltas = new int[2];
2256
2257 if ((edgeFlags & MotionEvent.EDGE_TOP) != 0) {
2258 direction = View.FOCUS_DOWN;
2259 if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
2260 deltas[0] = edgeSlop;
2261 x += edgeSlop;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002262 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
Jeff Brown3915bb82010-11-05 15:02:16 -07002263 deltas[0] = -edgeSlop;
2264 x -= edgeSlop;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002265 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002266 } else if ((edgeFlags & MotionEvent.EDGE_BOTTOM) != 0) {
2267 direction = View.FOCUS_UP;
2268 if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
2269 deltas[0] = edgeSlop;
2270 x += edgeSlop;
2271 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
2272 deltas[0] = -edgeSlop;
2273 x -= edgeSlop;
2274 }
2275 } else if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
2276 direction = View.FOCUS_RIGHT;
2277 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
2278 direction = View.FOCUS_LEFT;
2279 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002280
Jeff Brown3915bb82010-11-05 15:02:16 -07002281 View nearest = FocusFinder.getInstance().findNearestTouchable(
2282 ((ViewGroup) mView), x, y, direction, deltas);
2283 if (nearest != null) {
2284 event.offsetLocation(deltas[0], deltas[1]);
2285 event.setEdgeFlags(0);
2286 if (mView.dispatchTouchEvent(event)) {
2287 finishPointerEvent(event, sendDone, true);
2288 return;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002289 }
2290 }
2291 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002292
2293 // Pointer event was unhandled.
2294 finishPointerEvent(event, sendDone, false);
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002295 }
2296
Jeff Brown3915bb82010-11-05 15:02:16 -07002297 private void finishPointerEvent(MotionEvent event, boolean sendDone, boolean handled) {
2298 event.recycle();
2299 if (sendDone) {
2300 finishInputEvent(handled);
2301 }
2302 if (LOCAL_LOGV || WATCH_POINTER) Log.i(TAG, "Done dispatching!");
2303 }
2304
2305 private void deliverTrackballEvent(MotionEvent event, boolean sendDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002306 if (DEBUG_TRACKBALL) Log.v(TAG, "Motion event:" + event);
2307
Jeff Brown3915bb82010-11-05 15:02:16 -07002308 // If there is no view, then the event will not be handled.
2309 if (mView == null || !mAdded) {
2310 finishTrackballEvent(event, sendDone, false);
2311 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002312 }
2313
Jeff Brown3915bb82010-11-05 15:02:16 -07002314 // Deliver the trackball event to the view.
2315 if (mView.dispatchTrackballEvent(event)) {
2316 // If we reach this, we delivered a trackball event to mView and
2317 // mView consumed it. Because we will not translate the trackball
2318 // event into a key event, touch mode will not exit, so we exit
2319 // touch mode here.
2320 ensureTouchMode(false);
2321
2322 finishTrackballEvent(event, sendDone, true);
2323 mLastTrackballTime = Integer.MIN_VALUE;
2324 return;
2325 }
2326
2327 // Translate the trackball event into DPAD keys and try to deliver those.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002328 final TrackballAxis x = mTrackballAxisX;
2329 final TrackballAxis y = mTrackballAxisY;
2330
2331 long curTime = SystemClock.uptimeMillis();
Jeff Brown3915bb82010-11-05 15:02:16 -07002332 if ((mLastTrackballTime + MAX_TRACKBALL_DELAY) < curTime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002333 // It has been too long since the last movement,
2334 // so restart at the beginning.
2335 x.reset(0);
2336 y.reset(0);
2337 mLastTrackballTime = curTime;
2338 }
2339
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002340 final int action = event.getAction();
Jeff Brown49ed71d2010-12-06 17:13:33 -08002341 final int metaState = event.getMetaState();
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002342 switch (action) {
2343 case MotionEvent.ACTION_DOWN:
2344 x.reset(2);
2345 y.reset(2);
2346 deliverKeyEvent(new KeyEvent(curTime, curTime,
Jeff Brown49ed71d2010-12-06 17:13:33 -08002347 KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_CENTER, 0, metaState,
2348 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
2349 InputDevice.SOURCE_KEYBOARD), false);
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002350 break;
2351 case MotionEvent.ACTION_UP:
2352 x.reset(2);
2353 y.reset(2);
2354 deliverKeyEvent(new KeyEvent(curTime, curTime,
Jeff Brown49ed71d2010-12-06 17:13:33 -08002355 KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_CENTER, 0, metaState,
2356 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
2357 InputDevice.SOURCE_KEYBOARD), false);
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002358 break;
2359 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002360
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002361 if (DEBUG_TRACKBALL) Log.v(TAG, "TB X=" + x.position + " step="
2362 + x.step + " dir=" + x.dir + " acc=" + x.acceleration
2363 + " move=" + event.getX()
2364 + " / Y=" + y.position + " step="
2365 + y.step + " dir=" + y.dir + " acc=" + y.acceleration
2366 + " move=" + event.getY());
2367 final float xOff = x.collect(event.getX(), event.getEventTime(), "X");
2368 final float yOff = y.collect(event.getY(), event.getEventTime(), "Y");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002369
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002370 // Generate DPAD events based on the trackball movement.
2371 // We pick the axis that has moved the most as the direction of
2372 // the DPAD. When we generate DPAD events for one axis, then the
2373 // other axis is reset -- we don't want to perform DPAD jumps due
2374 // to slight movements in the trackball when making major movements
2375 // along the other axis.
2376 int keycode = 0;
2377 int movement = 0;
2378 float accel = 1;
2379 if (xOff > yOff) {
2380 movement = x.generate((2/event.getXPrecision()));
2381 if (movement != 0) {
2382 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_RIGHT
2383 : KeyEvent.KEYCODE_DPAD_LEFT;
2384 accel = x.acceleration;
2385 y.reset(2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002386 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002387 } else if (yOff > 0) {
2388 movement = y.generate((2/event.getYPrecision()));
2389 if (movement != 0) {
2390 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_DOWN
2391 : KeyEvent.KEYCODE_DPAD_UP;
2392 accel = y.acceleration;
2393 x.reset(2);
2394 }
2395 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002396
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002397 if (keycode != 0) {
2398 if (movement < 0) movement = -movement;
2399 int accelMovement = (int)(movement * accel);
2400 if (DEBUG_TRACKBALL) Log.v(TAG, "Move: movement=" + movement
2401 + " accelMovement=" + accelMovement
2402 + " accel=" + accel);
2403 if (accelMovement > movement) {
2404 if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: "
2405 + keycode);
2406 movement--;
Jeff Brown49ed71d2010-12-06 17:13:33 -08002407 int repeatCount = accelMovement - movement;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002408 deliverKeyEvent(new KeyEvent(curTime, curTime,
Jeff Brown49ed71d2010-12-06 17:13:33 -08002409 KeyEvent.ACTION_MULTIPLE, keycode, repeatCount, metaState,
2410 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
2411 InputDevice.SOURCE_KEYBOARD), false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002412 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002413 while (movement > 0) {
2414 if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: "
2415 + keycode);
2416 movement--;
2417 curTime = SystemClock.uptimeMillis();
2418 deliverKeyEvent(new KeyEvent(curTime, curTime,
Jeff Brown49ed71d2010-12-06 17:13:33 -08002419 KeyEvent.ACTION_DOWN, keycode, 0, metaState,
2420 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
2421 InputDevice.SOURCE_KEYBOARD), false);
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002422 deliverKeyEvent(new KeyEvent(curTime, curTime,
Jeff Brown49ed71d2010-12-06 17:13:33 -08002423 KeyEvent.ACTION_UP, keycode, 0, metaState,
2424 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
2425 InputDevice.SOURCE_KEYBOARD), false);
2426 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002427 mLastTrackballTime = curTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002428 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002429
2430 // Unfortunately we can't tell whether the application consumed the keys, so
2431 // we always consider the trackball event handled.
2432 finishTrackballEvent(event, sendDone, true);
2433 }
2434
2435 private void finishTrackballEvent(MotionEvent event, boolean sendDone, boolean handled) {
2436 event.recycle();
2437 if (sendDone) {
2438 finishInputEvent(handled);
2439 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002440 }
2441
2442 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08002443 * Returns true if the key is used for keyboard navigation.
2444 * @param keyEvent The key event.
2445 * @return True if the key is used for keyboard navigation.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002446 */
Jeff Brown4e6319b2010-12-13 10:36:51 -08002447 private static boolean isNavigationKey(KeyEvent keyEvent) {
2448 switch (keyEvent.getKeyCode()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002449 case KeyEvent.KEYCODE_DPAD_LEFT:
2450 case KeyEvent.KEYCODE_DPAD_RIGHT:
2451 case KeyEvent.KEYCODE_DPAD_UP:
2452 case KeyEvent.KEYCODE_DPAD_DOWN:
Jeff Brown4e6319b2010-12-13 10:36:51 -08002453 case KeyEvent.KEYCODE_DPAD_CENTER:
2454 case KeyEvent.KEYCODE_PAGE_UP:
2455 case KeyEvent.KEYCODE_PAGE_DOWN:
2456 case KeyEvent.KEYCODE_MOVE_HOME:
2457 case KeyEvent.KEYCODE_MOVE_END:
2458 case KeyEvent.KEYCODE_TAB:
2459 case KeyEvent.KEYCODE_SPACE:
2460 case KeyEvent.KEYCODE_ENTER:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002461 return true;
2462 }
2463 return false;
2464 }
2465
2466 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08002467 * Returns true if the key is used for typing.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002468 * @param keyEvent The key event.
Jeff Brown4e6319b2010-12-13 10:36:51 -08002469 * @return True if the key is used for typing.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002470 */
Jeff Brown4e6319b2010-12-13 10:36:51 -08002471 private static boolean isTypingKey(KeyEvent keyEvent) {
2472 return keyEvent.getUnicodeChar() > 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002473 }
2474
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002475 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08002476 * 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 -08002477 * @param event The key event.
2478 * @return Whether this key event should be consumed (meaning the act of
2479 * leaving touch mode alone is considered the event).
2480 */
2481 private boolean checkForLeavingTouchModeAndConsume(KeyEvent event) {
Jeff Brown4e6319b2010-12-13 10:36:51 -08002482 // Only relevant in touch mode.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002483 if (!mAttachInfo.mInTouchMode) {
2484 return false;
2485 }
2486
Jeff Brown4e6319b2010-12-13 10:36:51 -08002487 // Only consider leaving touch mode on DOWN or MULTIPLE actions, never on UP.
2488 final int action = event.getAction();
2489 if (action != KeyEvent.ACTION_DOWN && action != KeyEvent.ACTION_MULTIPLE) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002490 return false;
2491 }
2492
Jeff Brown4e6319b2010-12-13 10:36:51 -08002493 // Don't leave touch mode if the IME told us not to.
2494 if ((event.getFlags() & KeyEvent.FLAG_KEEP_TOUCH_MODE) != 0) {
2495 return false;
2496 }
2497
2498 // If the key can be used for keyboard navigation then leave touch mode
2499 // and select a focused view if needed (in ensureTouchMode).
2500 // When a new focused view is selected, we consume the navigation key because
2501 // navigation doesn't make much sense unless a view already has focus so
2502 // the key's purpose is to set focus.
2503 if (isNavigationKey(event)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002504 return ensureTouchMode(false);
2505 }
Jeff Brown4e6319b2010-12-13 10:36:51 -08002506
2507 // If the key can be used for typing then leave touch mode
2508 // and select a focused view if needed (in ensureTouchMode).
2509 // Always allow the view to process the typing key.
2510 if (isTypingKey(event)) {
2511 ensureTouchMode(false);
2512 return false;
2513 }
2514
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002515 return false;
2516 }
2517
2518 /**
Romain Guy8506ab42009-06-11 17:35:47 -07002519 * log motion events
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002520 */
2521 private static void captureMotionLog(String subTag, MotionEvent ev) {
Romain Guy8506ab42009-06-11 17:35:47 -07002522 //check dynamic switch
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002523 if (ev == null ||
2524 SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_EVENT, 0) == 0) {
2525 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002526 }
Romain Guy8506ab42009-06-11 17:35:47 -07002527
2528 StringBuilder sb = new StringBuilder(subTag + ": ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002529 sb.append(ev.getDownTime()).append(',');
2530 sb.append(ev.getEventTime()).append(',');
2531 sb.append(ev.getAction()).append(',');
Romain Guy8506ab42009-06-11 17:35:47 -07002532 sb.append(ev.getX()).append(',');
2533 sb.append(ev.getY()).append(',');
2534 sb.append(ev.getPressure()).append(',');
2535 sb.append(ev.getSize()).append(',');
2536 sb.append(ev.getMetaState()).append(',');
2537 sb.append(ev.getXPrecision()).append(',');
2538 sb.append(ev.getYPrecision()).append(',');
2539 sb.append(ev.getDeviceId()).append(',');
2540 sb.append(ev.getEdgeFlags());
2541 Log.d(TAG, sb.toString());
2542 }
2543 /**
2544 * log motion events
2545 */
2546 private static void captureKeyLog(String subTag, KeyEvent ev) {
2547 //check dynamic switch
2548 if (ev == null ||
2549 SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_EVENT, 0) == 0) {
2550 return;
2551 }
2552 StringBuilder sb = new StringBuilder(subTag + ": ");
2553 sb.append(ev.getDownTime()).append(',');
2554 sb.append(ev.getEventTime()).append(',');
2555 sb.append(ev.getAction()).append(',');
2556 sb.append(ev.getKeyCode()).append(',');
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002557 sb.append(ev.getRepeatCount()).append(',');
2558 sb.append(ev.getMetaState()).append(',');
2559 sb.append(ev.getDeviceId()).append(',');
2560 sb.append(ev.getScanCode());
Romain Guy8506ab42009-06-11 17:35:47 -07002561 Log.d(TAG, sb.toString());
2562 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002563
2564 int enqueuePendingEvent(Object event, boolean sendDone) {
2565 int seq = mPendingEventSeq+1;
2566 if (seq < 0) seq = 0;
2567 mPendingEventSeq = seq;
2568 mPendingEvents.put(seq, event);
2569 return sendDone ? seq : -seq;
2570 }
2571
2572 Object retrievePendingEvent(int seq) {
2573 if (seq < 0) seq = -seq;
2574 Object event = mPendingEvents.get(seq);
2575 if (event != null) {
2576 mPendingEvents.remove(seq);
2577 }
2578 return event;
2579 }
Romain Guy8506ab42009-06-11 17:35:47 -07002580
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002581 private void deliverKeyEvent(KeyEvent event, boolean sendDone) {
Jeff Brown3915bb82010-11-05 15:02:16 -07002582 // If there is no view, then the event will not be handled.
2583 if (mView == null || !mAdded) {
2584 finishKeyEvent(event, sendDone, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002585 return;
2586 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002587
2588 if (LOCAL_LOGV) Log.v(TAG, "Dispatching key " + event + " to " + mView);
2589
2590 // Perform predispatching before the IME.
2591 if (mView.dispatchKeyEventPreIme(event)) {
2592 finishKeyEvent(event, sendDone, true);
2593 return;
2594 }
2595
2596 // Dispatch to the IME before propagating down the view hierarchy.
2597 // The IME will eventually call back into handleFinishedEvent.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002598 if (mLastWasImTarget) {
2599 InputMethodManager imm = InputMethodManager.peekInstance();
Jeff Brown3915bb82010-11-05 15:02:16 -07002600 if (imm != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002601 int seq = enqueuePendingEvent(event, sendDone);
2602 if (DEBUG_IMF) Log.v(TAG, "Sending key event to IME: seq="
2603 + seq + " event=" + event);
Jeff Brown3915bb82010-11-05 15:02:16 -07002604 imm.dispatchKeyEvent(mView.getContext(), seq, event, mInputMethodCallback);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002605 return;
2606 }
2607 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002608
2609 // Not dispatching to IME, continue with post IME actions.
2610 deliverKeyEventPostIme(event, sendDone);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002611 }
2612
Jeff Brown3915bb82010-11-05 15:02:16 -07002613 private void handleFinishedEvent(int seq, boolean handled) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002614 final KeyEvent event = (KeyEvent)retrievePendingEvent(seq);
2615 if (DEBUG_IMF) Log.v(TAG, "IME finished event: seq=" + seq
2616 + " handled=" + handled + " event=" + event);
2617 if (event != null) {
2618 final boolean sendDone = seq >= 0;
Jeff Brown3915bb82010-11-05 15:02:16 -07002619 if (handled) {
2620 finishKeyEvent(event, sendDone, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002621 } else {
Jeff Brown3915bb82010-11-05 15:02:16 -07002622 deliverKeyEventPostIme(event, sendDone);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002623 }
2624 }
2625 }
Romain Guy8506ab42009-06-11 17:35:47 -07002626
Jeff Brown3915bb82010-11-05 15:02:16 -07002627 private void deliverKeyEventPostIme(KeyEvent event, boolean sendDone) {
2628 // If the view went away, then the event will not be handled.
2629 if (mView == null || !mAdded) {
2630 finishKeyEvent(event, sendDone, false);
2631 return;
2632 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002633
Jeff Brown3915bb82010-11-05 15:02:16 -07002634 // If the key's purpose is to exit touch mode then we consume it and consider it handled.
2635 if (checkForLeavingTouchModeAndConsume(event)) {
2636 finishKeyEvent(event, sendDone, true);
2637 return;
2638 }
Romain Guy8506ab42009-06-11 17:35:47 -07002639
Jeff Brown3915bb82010-11-05 15:02:16 -07002640 if (Config.LOGV) {
2641 captureKeyLog("captureDispatchKeyEvent", event);
2642 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002643
Jeff Brown90655042010-12-02 13:50:46 -08002644 // Make sure the fallback event policy sees all keys that will be delivered to the
2645 // view hierarchy.
2646 mFallbackEventHandler.preDispatchKeyEvent(event);
2647
Jeff Brown3915bb82010-11-05 15:02:16 -07002648 // Deliver the key to the view hierarchy.
2649 if (mView.dispatchKeyEvent(event)) {
2650 finishKeyEvent(event, sendDone, true);
2651 return;
2652 }
Joe Onorato86f67862010-11-05 18:57:34 -07002653
Jeff Brownc1df9072010-12-21 16:38:50 -08002654 // If the Control modifier is held, try to interpret the key as a shortcut.
2655 if (event.getAction() == KeyEvent.ACTION_UP
2656 && event.isCtrlPressed()
2657 && !KeyEvent.isModifierKey(event.getKeyCode())) {
2658 if (mView.dispatchKeyShortcutEvent(event)) {
2659 finishKeyEvent(event, sendDone, true);
2660 return;
2661 }
2662 }
2663
Jeff Brown3915bb82010-11-05 15:02:16 -07002664 // Apply the fallback event policy.
2665 if (mFallbackEventHandler.dispatchKeyEvent(event)) {
2666 finishKeyEvent(event, sendDone, true);
2667 return;
2668 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002669
Jeff Brown3915bb82010-11-05 15:02:16 -07002670 // Handle automatic focus changes.
2671 if (event.getAction() == KeyEvent.ACTION_DOWN) {
2672 int direction = 0;
2673 switch (event.getKeyCode()) {
2674 case KeyEvent.KEYCODE_DPAD_LEFT:
Jeff Brown4e6319b2010-12-13 10:36:51 -08002675 if (event.hasNoModifiers()) {
2676 direction = View.FOCUS_LEFT;
2677 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002678 break;
2679 case KeyEvent.KEYCODE_DPAD_RIGHT:
Jeff Brown4e6319b2010-12-13 10:36:51 -08002680 if (event.hasNoModifiers()) {
2681 direction = View.FOCUS_RIGHT;
2682 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002683 break;
2684 case KeyEvent.KEYCODE_DPAD_UP:
Jeff Brown4e6319b2010-12-13 10:36:51 -08002685 if (event.hasNoModifiers()) {
2686 direction = View.FOCUS_UP;
2687 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002688 break;
2689 case KeyEvent.KEYCODE_DPAD_DOWN:
Jeff Brown4e6319b2010-12-13 10:36:51 -08002690 if (event.hasNoModifiers()) {
2691 direction = View.FOCUS_DOWN;
2692 }
2693 break;
2694 case KeyEvent.KEYCODE_TAB:
2695 if (event.hasNoModifiers()) {
2696 direction = View.FOCUS_FORWARD;
2697 } else if (event.hasModifiers(KeyEvent.META_SHIFT_ON)) {
2698 direction = View.FOCUS_BACKWARD;
2699 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002700 break;
2701 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002702
Jeff Brown3915bb82010-11-05 15:02:16 -07002703 if (direction != 0) {
2704 View focused = mView != null ? mView.findFocus() : null;
2705 if (focused != null) {
2706 View v = focused.focusSearch(direction);
2707 if (v != null && v != focused) {
2708 // do the math the get the interesting rect
2709 // of previous focused into the coord system of
2710 // newly focused view
2711 focused.getFocusedRect(mTempRect);
2712 if (mView instanceof ViewGroup) {
2713 ((ViewGroup) mView).offsetDescendantRectToMyCoords(
2714 focused, mTempRect);
2715 ((ViewGroup) mView).offsetRectIntoDescendantCoords(
2716 v, mTempRect);
2717 }
2718 if (v.requestFocus(direction, mTempRect)) {
2719 playSoundEffect(
2720 SoundEffectConstants.getContantForFocusDirection(direction));
2721 finishKeyEvent(event, sendDone, true);
2722 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002723 }
2724 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002725
2726 // Give the focused view a last chance to handle the dpad key.
2727 if (mView.dispatchUnhandledMove(focused, direction)) {
2728 finishKeyEvent(event, sendDone, true);
2729 return;
2730 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002731 }
2732 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002733 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002734
Jeff Brown3915bb82010-11-05 15:02:16 -07002735 // Key was unhandled.
2736 finishKeyEvent(event, sendDone, false);
2737 }
2738
2739 private void finishKeyEvent(KeyEvent event, boolean sendDone, boolean handled) {
2740 if (sendDone) {
2741 finishInputEvent(handled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002742 }
2743 }
2744
Christopher Tatea53146c2010-09-07 11:57:52 -07002745 /* drag/drop */
Christopher Tate407b4e92010-11-30 17:14:08 -08002746 void setLocalDragState(Object obj) {
2747 mLocalDragState = obj;
2748 }
2749
Christopher Tatea53146c2010-09-07 11:57:52 -07002750 private void handleDragEvent(DragEvent event) {
2751 // From the root, only drag start/end/location are dispatched. entered/exited
2752 // are determined and dispatched by the viewgroup hierarchy, who then report
2753 // that back here for ultimate reporting back to the framework.
2754 if (mView != null && mAdded) {
2755 final int what = event.mAction;
2756
2757 if (what == DragEvent.ACTION_DRAG_EXITED) {
2758 // A direct EXITED event means that the window manager knows we've just crossed
2759 // a window boundary, so the current drag target within this one must have
2760 // just been exited. Send it the usual notifications and then we're done
2761 // for now.
Chris Tate9d1ab882010-11-02 15:55:39 -07002762 mView.dispatchDragEvent(event);
Christopher Tatea53146c2010-09-07 11:57:52 -07002763 } else {
2764 // Cache the drag description when the operation starts, then fill it in
2765 // on subsequent calls as a convenience
2766 if (what == DragEvent.ACTION_DRAG_STARTED) {
Chris Tate9d1ab882010-11-02 15:55:39 -07002767 mCurrentDragView = null; // Start the current-recipient tracking
Christopher Tatea53146c2010-09-07 11:57:52 -07002768 mDragDescription = event.mClipDescription;
2769 } else {
2770 event.mClipDescription = mDragDescription;
2771 }
2772
2773 // For events with a [screen] location, translate into window coordinates
2774 if ((what == DragEvent.ACTION_DRAG_LOCATION) || (what == DragEvent.ACTION_DROP)) {
2775 mDragPoint.set(event.mX, event.mY);
2776 if (mTranslator != null) {
2777 mTranslator.translatePointInScreenToAppWindow(mDragPoint);
2778 }
2779
2780 if (mCurScrollY != 0) {
2781 mDragPoint.offset(0, mCurScrollY);
2782 }
2783
2784 event.mX = mDragPoint.x;
2785 event.mY = mDragPoint.y;
2786 }
2787
2788 // Remember who the current drag target is pre-dispatch
2789 final View prevDragView = mCurrentDragView;
2790
2791 // Now dispatch the drag/drop event
Chris Tated4533f12010-10-19 15:15:08 -07002792 boolean result = mView.dispatchDragEvent(event);
Christopher Tatea53146c2010-09-07 11:57:52 -07002793
2794 // If we changed apparent drag target, tell the OS about it
2795 if (prevDragView != mCurrentDragView) {
2796 try {
2797 if (prevDragView != null) {
2798 sWindowSession.dragRecipientExited(mWindow);
2799 }
2800 if (mCurrentDragView != null) {
2801 sWindowSession.dragRecipientEntered(mWindow);
2802 }
2803 } catch (RemoteException e) {
2804 Slog.e(TAG, "Unable to note drag target change");
2805 }
Christopher Tatea53146c2010-09-07 11:57:52 -07002806 }
Chris Tated4533f12010-10-19 15:15:08 -07002807
Christopher Tate407b4e92010-11-30 17:14:08 -08002808 // Report the drop result when we're done
Chris Tated4533f12010-10-19 15:15:08 -07002809 if (what == DragEvent.ACTION_DROP) {
Christopher Tate1fc014f2011-01-19 12:56:26 -08002810 mDragDescription = null;
Chris Tated4533f12010-10-19 15:15:08 -07002811 try {
2812 Log.i(TAG, "Reporting drop result: " + result);
2813 sWindowSession.reportDropResult(mWindow, result);
2814 } catch (RemoteException e) {
2815 Log.e(TAG, "Unable to report drop result");
2816 }
2817 }
Christopher Tate407b4e92010-11-30 17:14:08 -08002818
2819 // When the drag operation ends, release any local state object
2820 // that may have been in use
2821 if (what == DragEvent.ACTION_DRAG_ENDED) {
2822 setLocalDragState(null);
2823 }
Christopher Tatea53146c2010-09-07 11:57:52 -07002824 }
2825 }
2826 event.recycle();
2827 }
2828
Christopher Tate2c095f32010-10-04 14:13:40 -07002829 public void getLastTouchPoint(Point outLocation) {
2830 outLocation.x = (int) mLastTouchPoint.x;
2831 outLocation.y = (int) mLastTouchPoint.y;
2832 }
2833
Chris Tate9d1ab882010-11-02 15:55:39 -07002834 public void setDragFocus(View newDragTarget) {
Christopher Tatea53146c2010-09-07 11:57:52 -07002835 if (mCurrentDragView != newDragTarget) {
Chris Tate048691c2010-10-12 17:39:18 -07002836 mCurrentDragView = newDragTarget;
Christopher Tatea53146c2010-09-07 11:57:52 -07002837 }
Christopher Tatea53146c2010-09-07 11:57:52 -07002838 }
2839
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002840 private AudioManager getAudioManager() {
2841 if (mView == null) {
2842 throw new IllegalStateException("getAudioManager called when there is no mView");
2843 }
2844 if (mAudioManager == null) {
2845 mAudioManager = (AudioManager) mView.getContext().getSystemService(Context.AUDIO_SERVICE);
2846 }
2847 return mAudioManager;
2848 }
2849
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002850 private int relayoutWindow(WindowManager.LayoutParams params, int viewVisibility,
2851 boolean insetsPending) throws RemoteException {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002852
2853 float appScale = mAttachInfo.mApplicationScale;
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002854 boolean restore = false;
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002855 if (params != null && mTranslator != null) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07002856 restore = true;
2857 params.backup();
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002858 mTranslator.translateWindowLayout(params);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002859 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002860 if (params != null) {
2861 if (DBG) Log.d(TAG, "WindowLayout in layoutWindow:" + params);
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002862 }
Dianne Hackborn694f79b2010-03-17 19:44:59 -07002863 mPendingConfiguration.seq = 0;
Dianne Hackbornf123e492010-09-24 11:16:23 -07002864 //Log.d(TAG, ">>>>>> CALLING relayout");
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002865 int relayoutResult = sWindowSession.relayout(
2866 mWindow, params,
Dianne Hackborn189ee182010-12-02 21:48:53 -08002867 (int) (mView.getMeasuredWidth() * appScale + 0.5f),
2868 (int) (mView.getMeasuredHeight() * appScale + 0.5f),
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002869 viewVisibility, insetsPending, mWinFrame,
Dianne Hackborn694f79b2010-03-17 19:44:59 -07002870 mPendingContentInsets, mPendingVisibleInsets,
2871 mPendingConfiguration, mSurface);
Dianne Hackbornf123e492010-09-24 11:16:23 -07002872 //Log.d(TAG, "<<<<<< BACK FROM relayout");
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002873 if (restore) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07002874 params.restore();
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002875 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002876
2877 if (mTranslator != null) {
2878 mTranslator.translateRectInScreenToAppWinFrame(mWinFrame);
2879 mTranslator.translateRectInScreenToAppWindow(mPendingContentInsets);
2880 mTranslator.translateRectInScreenToAppWindow(mPendingVisibleInsets);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002881 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002882 return relayoutResult;
2883 }
Romain Guy8506ab42009-06-11 17:35:47 -07002884
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002885 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002886 * {@inheritDoc}
2887 */
2888 public void playSoundEffect(int effectId) {
2889 checkThread();
2890
Jean-Michel Trivi13b18fd2010-05-05 09:18:15 -07002891 try {
2892 final AudioManager audioManager = getAudioManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002893
Jean-Michel Trivi13b18fd2010-05-05 09:18:15 -07002894 switch (effectId) {
2895 case SoundEffectConstants.CLICK:
2896 audioManager.playSoundEffect(AudioManager.FX_KEY_CLICK);
2897 return;
2898 case SoundEffectConstants.NAVIGATION_DOWN:
2899 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_DOWN);
2900 return;
2901 case SoundEffectConstants.NAVIGATION_LEFT:
2902 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_LEFT);
2903 return;
2904 case SoundEffectConstants.NAVIGATION_RIGHT:
2905 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_RIGHT);
2906 return;
2907 case SoundEffectConstants.NAVIGATION_UP:
2908 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_UP);
2909 return;
2910 default:
2911 throw new IllegalArgumentException("unknown effect id " + effectId +
2912 " not defined in " + SoundEffectConstants.class.getCanonicalName());
2913 }
2914 } catch (IllegalStateException e) {
2915 // Exception thrown by getAudioManager() when mView is null
2916 Log.e(TAG, "FATAL EXCEPTION when attempting to play sound effect: " + e);
2917 e.printStackTrace();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002918 }
2919 }
2920
2921 /**
2922 * {@inheritDoc}
2923 */
2924 public boolean performHapticFeedback(int effectId, boolean always) {
2925 try {
2926 return sWindowSession.performHapticFeedback(mWindow, effectId, always);
2927 } catch (RemoteException e) {
2928 return false;
2929 }
2930 }
2931
2932 /**
2933 * {@inheritDoc}
2934 */
2935 public View focusSearch(View focused, int direction) {
2936 checkThread();
2937 if (!(mView instanceof ViewGroup)) {
2938 return null;
2939 }
2940 return FocusFinder.getInstance().findNextFocus((ViewGroup) mView, focused, direction);
2941 }
2942
2943 public void debug() {
2944 mView.debug();
2945 }
2946
2947 public void die(boolean immediate) {
Dianne Hackborn94d69142009-09-28 22:14:42 -07002948 if (immediate) {
2949 doDie();
2950 } else {
2951 sendEmptyMessage(DIE);
2952 }
2953 }
2954
2955 void doDie() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002956 checkThread();
Jeff Brownb75fa302010-07-15 23:47:29 -07002957 if (LOCAL_LOGV) Log.v(TAG, "DIE in " + this + " of " + mSurface);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002958 synchronized (this) {
2959 if (mAdded && !mFirst) {
Romain Guy29d89972010-09-22 16:10:57 -07002960 destroyHardwareRenderer();
2961
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002962 int viewVisibility = mView.getVisibility();
2963 boolean viewVisibilityChanged = mViewVisibility != viewVisibility;
2964 if (mWindowAttributesChanged || viewVisibilityChanged) {
2965 // If layout params have been changed, first give them
2966 // to the window manager to make sure it has the correct
2967 // animation info.
2968 try {
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002969 if ((relayoutWindow(mWindowAttributes, viewVisibility, false)
2970 & WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002971 sWindowSession.finishDrawing(mWindow);
2972 }
2973 } catch (RemoteException e) {
2974 }
2975 }
2976
Dianne Hackborn0586a1b2009-09-06 21:08:27 -07002977 mSurface.release();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002978 }
2979 if (mAdded) {
2980 mAdded = false;
Dianne Hackborn94d69142009-09-28 22:14:42 -07002981 dispatchDetachedFromWindow();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002982 }
2983 }
2984 }
2985
Romain Guy29d89972010-09-22 16:10:57 -07002986 private void destroyHardwareRenderer() {
Romain Guyb051e892010-09-28 19:09:36 -07002987 if (mAttachInfo.mHardwareRenderer != null) {
2988 mAttachInfo.mHardwareRenderer.destroy(true);
2989 mAttachInfo.mHardwareRenderer = null;
Romain Guy29d89972010-09-22 16:10:57 -07002990 mAttachInfo.mHardwareAccelerated = false;
2991 }
2992 }
2993
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002994 public void dispatchFinishedEvent(int seq, boolean handled) {
2995 Message msg = obtainMessage(FINISHED_EVENT);
2996 msg.arg1 = seq;
2997 msg.arg2 = handled ? 1 : 0;
2998 sendMessage(msg);
2999 }
Mitsuru Oshima3d914922009-05-13 22:29:15 -07003000
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003001 public void dispatchResized(int w, int h, Rect coveredInsets,
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003002 Rect visibleInsets, boolean reportDraw, Configuration newConfig) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003003 if (DEBUG_LAYOUT) Log.v(TAG, "Resizing " + this + ": w=" + w
3004 + " h=" + h + " coveredInsets=" + coveredInsets.toShortString()
3005 + " visibleInsets=" + visibleInsets.toShortString()
3006 + " reportDraw=" + reportDraw);
3007 Message msg = obtainMessage(reportDraw ? RESIZED_REPORT :RESIZED);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07003008 if (mTranslator != null) {
3009 mTranslator.translateRectInScreenToAppWindow(coveredInsets);
3010 mTranslator.translateRectInScreenToAppWindow(visibleInsets);
3011 w *= mTranslator.applicationInvertedScale;
3012 h *= mTranslator.applicationInvertedScale;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07003013 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07003014 msg.arg1 = w;
3015 msg.arg2 = h;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003016 ResizedInfo ri = new ResizedInfo();
3017 ri.coveredInsets = new Rect(coveredInsets);
3018 ri.visibleInsets = new Rect(visibleInsets);
3019 ri.newConfig = newConfig;
3020 msg.obj = ri;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003021 sendMessage(msg);
3022 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07003023
Jeff Brown3915bb82010-11-05 15:02:16 -07003024 private InputQueue.FinishedCallback mFinishedCallback;
Jeff Brown46b9ac02010-04-22 18:58:52 -07003025
3026 private final InputHandler mInputHandler = new InputHandler() {
Jeff Brown3915bb82010-11-05 15:02:16 -07003027 public void handleKey(KeyEvent event, InputQueue.FinishedCallback finishedCallback) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07003028 startInputEvent(finishedCallback);
Jeff Brown92ff1dd2010-08-11 16:16:06 -07003029 dispatchKey(event, true);
Jeff Brown46b9ac02010-04-22 18:58:52 -07003030 }
3031
Jeff Brown3915bb82010-11-05 15:02:16 -07003032 public void handleMotion(MotionEvent event, InputQueue.FinishedCallback finishedCallback) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07003033 startInputEvent(finishedCallback);
3034 dispatchMotion(event, true);
Jeff Brown46b9ac02010-04-22 18:58:52 -07003035 }
3036 };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003037
3038 public void dispatchKey(KeyEvent event) {
Jeff Brown92ff1dd2010-08-11 16:16:06 -07003039 dispatchKey(event, false);
3040 }
3041
3042 private void dispatchKey(KeyEvent event, boolean sendDone) {
3043 //noinspection ConstantConditions
3044 if (false && event.getAction() == KeyEvent.ACTION_DOWN) {
3045 if (event.getKeyCode() == KeyEvent.KEYCODE_CAMERA) {
Romain Guy812ccbe2010-06-01 14:07:24 -07003046 if (DBG) Log.d("keydisp", "===================================================");
3047 if (DBG) Log.d("keydisp", "Focused view Hierarchy is:");
3048
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003049 debug();
3050
Romain Guy812ccbe2010-06-01 14:07:24 -07003051 if (DBG) Log.d("keydisp", "===================================================");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003052 }
3053 }
3054
3055 Message msg = obtainMessage(DISPATCH_KEY);
3056 msg.obj = event;
Jeff Brown92ff1dd2010-08-11 16:16:06 -07003057 msg.arg1 = sendDone ? 1 : 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003058
3059 if (LOCAL_LOGV) Log.v(
Jeff Brownc5ed5912010-07-14 18:48:53 -07003060 TAG, "sending key " + event + " to " + mView);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003061
3062 sendMessageAtTime(msg, event.getEventTime());
3063 }
Jeff Brownc5ed5912010-07-14 18:48:53 -07003064
3065 public void dispatchMotion(MotionEvent event) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07003066 dispatchMotion(event, false);
3067 }
3068
3069 private void dispatchMotion(MotionEvent event, boolean sendDone) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07003070 int source = event.getSource();
3071 if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07003072 dispatchPointer(event, sendDone);
Jeff Brownc5ed5912010-07-14 18:48:53 -07003073 } else if ((source & InputDevice.SOURCE_CLASS_TRACKBALL) != 0) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07003074 dispatchTrackball(event, sendDone);
Jeff Brownc5ed5912010-07-14 18:48:53 -07003075 } else {
3076 // TODO
3077 Log.v(TAG, "Dropping unsupported motion event (unimplemented): " + event);
Jeff Brown93ed4e32010-09-23 13:51:48 -07003078 if (sendDone) {
Jeff Brown3915bb82010-11-05 15:02:16 -07003079 finishInputEvent(false);
Jeff Brown93ed4e32010-09-23 13:51:48 -07003080 }
Jeff Brownc5ed5912010-07-14 18:48:53 -07003081 }
3082 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003083
Jeff Brown00fa7bd2010-07-02 15:37:36 -07003084 public void dispatchPointer(MotionEvent event) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07003085 dispatchPointer(event, false);
3086 }
3087
3088 private void dispatchPointer(MotionEvent event, boolean sendDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003089 Message msg = obtainMessage(DISPATCH_POINTER);
3090 msg.obj = event;
Jeff Brown93ed4e32010-09-23 13:51:48 -07003091 msg.arg1 = sendDone ? 1 : 0;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07003092 sendMessageAtTime(msg, event.getEventTime());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003093 }
3094
Jeff Brown00fa7bd2010-07-02 15:37:36 -07003095 public void dispatchTrackball(MotionEvent event) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07003096 dispatchTrackball(event, false);
3097 }
3098
3099 private void dispatchTrackball(MotionEvent event, boolean sendDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003100 Message msg = obtainMessage(DISPATCH_TRACKBALL);
3101 msg.obj = event;
Jeff Brown93ed4e32010-09-23 13:51:48 -07003102 msg.arg1 = sendDone ? 1 : 0;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07003103 sendMessageAtTime(msg, event.getEventTime());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003104 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07003105
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003106 public void dispatchAppVisibility(boolean visible) {
3107 Message msg = obtainMessage(DISPATCH_APP_VISIBILITY);
3108 msg.arg1 = visible ? 1 : 0;
3109 sendMessage(msg);
3110 }
3111
3112 public void dispatchGetNewSurface() {
3113 Message msg = obtainMessage(DISPATCH_GET_NEW_SURFACE);
3114 sendMessage(msg);
3115 }
3116
3117 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
3118 Message msg = Message.obtain();
3119 msg.what = WINDOW_FOCUS_CHANGED;
3120 msg.arg1 = hasFocus ? 1 : 0;
3121 msg.arg2 = inTouchMode ? 1 : 0;
3122 sendMessage(msg);
3123 }
3124
Dianne Hackbornffa42482009-09-23 22:20:11 -07003125 public void dispatchCloseSystemDialogs(String reason) {
3126 Message msg = Message.obtain();
3127 msg.what = CLOSE_SYSTEM_DIALOGS;
3128 msg.obj = reason;
3129 sendMessage(msg);
3130 }
Christopher Tatea53146c2010-09-07 11:57:52 -07003131
3132 public void dispatchDragEvent(DragEvent event) {
Chris Tate91e9bb32010-10-12 12:58:43 -07003133 final int what;
3134 if (event.getAction() == DragEvent.ACTION_DRAG_LOCATION) {
3135 what = DISPATCH_DRAG_LOCATION_EVENT;
3136 removeMessages(what);
3137 } else {
3138 what = DISPATCH_DRAG_EVENT;
3139 }
3140 Message msg = obtainMessage(what, event);
Christopher Tatea53146c2010-09-07 11:57:52 -07003141 sendMessage(msg);
3142 }
3143
svetoslavganov75986cf2009-05-14 22:28:01 -07003144 /**
3145 * The window is getting focus so if there is anything focused/selected
3146 * send an {@link AccessibilityEvent} to announce that.
3147 */
3148 private void sendAccessibilityEvents() {
3149 if (!AccessibilityManager.getInstance(mView.getContext()).isEnabled()) {
3150 return;
3151 }
3152 mView.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
3153 View focusedView = mView.findFocus();
3154 if (focusedView != null && focusedView != mView) {
3155 focusedView.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
3156 }
3157 }
3158
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003159 public boolean showContextMenuForChild(View originalView) {
3160 return false;
3161 }
3162
Adam Powell6e346362010-07-23 10:18:23 -07003163 public ActionMode startActionModeForChild(View originalView, ActionMode.Callback callback) {
3164 return null;
3165 }
3166
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003167 public void createContextMenu(ContextMenu menu) {
3168 }
3169
3170 public void childDrawableStateChanged(View child) {
3171 }
3172
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003173 void checkThread() {
3174 if (mThread != Thread.currentThread()) {
3175 throw new CalledFromWrongThreadException(
3176 "Only the original thread that created a view hierarchy can touch its views.");
3177 }
3178 }
3179
3180 public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
3181 // ViewRoot never intercepts touch event, so this can be a no-op
3182 }
3183
3184 public boolean requestChildRectangleOnScreen(View child, Rect rectangle,
3185 boolean immediate) {
3186 return scrollToRectOrFocus(rectangle, immediate);
3187 }
Romain Guy8506ab42009-06-11 17:35:47 -07003188
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07003189 class TakenSurfaceHolder extends BaseSurfaceHolder {
3190 @Override
3191 public boolean onAllowLockCanvas() {
3192 return mDrawingAllowed;
3193 }
3194
3195 @Override
3196 public void onRelayoutContainer() {
3197 // Not currently interesting -- from changing between fixed and layout size.
3198 }
3199
3200 public void setFormat(int format) {
3201 ((RootViewSurfaceTaker)mView).setSurfaceFormat(format);
3202 }
3203
3204 public void setType(int type) {
3205 ((RootViewSurfaceTaker)mView).setSurfaceType(type);
3206 }
3207
3208 @Override
3209 public void onUpdateSurface() {
3210 // We take care of format and type changes on our own.
3211 throw new IllegalStateException("Shouldn't be here");
3212 }
3213
3214 public boolean isCreating() {
3215 return mIsCreating;
3216 }
3217
3218 @Override
3219 public void setFixedSize(int width, int height) {
3220 throw new UnsupportedOperationException(
3221 "Currently only support sizing from layout");
3222 }
3223
3224 public void setKeepScreenOn(boolean screenOn) {
3225 ((RootViewSurfaceTaker)mView).setSurfaceKeepScreenOn(screenOn);
3226 }
3227 }
3228
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003229 static class InputMethodCallback extends IInputMethodCallback.Stub {
3230 private WeakReference<ViewRoot> mViewRoot;
3231
3232 public InputMethodCallback(ViewRoot viewRoot) {
3233 mViewRoot = new WeakReference<ViewRoot>(viewRoot);
3234 }
Romain Guy8506ab42009-06-11 17:35:47 -07003235
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003236 public void finishedEvent(int seq, boolean handled) {
3237 final ViewRoot viewRoot = mViewRoot.get();
3238 if (viewRoot != null) {
3239 viewRoot.dispatchFinishedEvent(seq, handled);
3240 }
3241 }
3242
3243 public void sessionCreated(IInputMethodSession session) throws RemoteException {
3244 // Stub -- not for use in the client.
3245 }
3246 }
Romain Guy8506ab42009-06-11 17:35:47 -07003247
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003248 static class W extends IWindow.Stub {
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07003249 private final WeakReference<ViewRoot> mViewRoot;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003250
Romain Guyfb8b7632010-08-23 21:05:08 -07003251 W(ViewRoot viewRoot) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003252 mViewRoot = new WeakReference<ViewRoot>(viewRoot);
3253 }
3254
Romain Guyfb8b7632010-08-23 21:05:08 -07003255 public void resized(int w, int h, Rect coveredInsets, Rect visibleInsets,
3256 boolean reportDraw, Configuration newConfig) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003257 final ViewRoot viewRoot = mViewRoot.get();
3258 if (viewRoot != null) {
Romain Guyfb8b7632010-08-23 21:05:08 -07003259 viewRoot.dispatchResized(w, h, coveredInsets, visibleInsets, reportDraw, newConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003260 }
3261 }
3262
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003263 public void dispatchAppVisibility(boolean visible) {
3264 final ViewRoot viewRoot = mViewRoot.get();
3265 if (viewRoot != null) {
3266 viewRoot.dispatchAppVisibility(visible);
3267 }
3268 }
3269
3270 public void dispatchGetNewSurface() {
3271 final ViewRoot viewRoot = mViewRoot.get();
3272 if (viewRoot != null) {
3273 viewRoot.dispatchGetNewSurface();
3274 }
3275 }
3276
3277 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
3278 final ViewRoot viewRoot = mViewRoot.get();
3279 if (viewRoot != null) {
3280 viewRoot.windowFocusChanged(hasFocus, inTouchMode);
3281 }
3282 }
3283
3284 private static int checkCallingPermission(String permission) {
3285 if (!Process.supportsProcesses()) {
3286 return PackageManager.PERMISSION_GRANTED;
3287 }
3288
3289 try {
3290 return ActivityManagerNative.getDefault().checkPermission(
3291 permission, Binder.getCallingPid(), Binder.getCallingUid());
3292 } catch (RemoteException e) {
3293 return PackageManager.PERMISSION_DENIED;
3294 }
3295 }
3296
3297 public void executeCommand(String command, String parameters, ParcelFileDescriptor out) {
3298 final ViewRoot viewRoot = mViewRoot.get();
3299 if (viewRoot != null) {
3300 final View view = viewRoot.mView;
3301 if (view != null) {
3302 if (checkCallingPermission(Manifest.permission.DUMP) !=
3303 PackageManager.PERMISSION_GRANTED) {
3304 throw new SecurityException("Insufficient permissions to invoke"
3305 + " executeCommand() from pid=" + Binder.getCallingPid()
3306 + ", uid=" + Binder.getCallingUid());
3307 }
3308
3309 OutputStream clientStream = null;
3310 try {
3311 clientStream = new ParcelFileDescriptor.AutoCloseOutputStream(out);
3312 ViewDebug.dispatchCommand(view, command, parameters, clientStream);
3313 } catch (IOException e) {
3314 e.printStackTrace();
3315 } finally {
3316 if (clientStream != null) {
3317 try {
3318 clientStream.close();
3319 } catch (IOException e) {
3320 e.printStackTrace();
3321 }
3322 }
3323 }
3324 }
3325 }
3326 }
Dianne Hackborn72c82ab2009-08-11 21:13:54 -07003327
Dianne Hackbornffa42482009-09-23 22:20:11 -07003328 public void closeSystemDialogs(String reason) {
3329 final ViewRoot viewRoot = mViewRoot.get();
3330 if (viewRoot != null) {
3331 viewRoot.dispatchCloseSystemDialogs(reason);
3332 }
3333 }
3334
Marco Nelissenbf6956b2009-11-09 15:21:13 -08003335 public void dispatchWallpaperOffsets(float x, float y, float xStep, float yStep,
3336 boolean sync) {
Dianne Hackborn19382ac2009-09-11 21:13:37 -07003337 if (sync) {
3338 try {
3339 sWindowSession.wallpaperOffsetsComplete(asBinder());
3340 } catch (RemoteException e) {
3341 }
3342 }
Dianne Hackborn72c82ab2009-08-11 21:13:54 -07003343 }
Dianne Hackborn75804932009-10-20 20:15:20 -07003344
3345 public void dispatchWallpaperCommand(String action, int x, int y,
3346 int z, Bundle extras, boolean sync) {
3347 if (sync) {
3348 try {
3349 sWindowSession.wallpaperCommandComplete(asBinder(), null);
3350 } catch (RemoteException e) {
3351 }
3352 }
3353 }
Christopher Tatea53146c2010-09-07 11:57:52 -07003354
3355 /* Drag/drop */
3356 public void dispatchDragEvent(DragEvent event) {
3357 final ViewRoot viewRoot = mViewRoot.get();
3358 if (viewRoot != null) {
3359 viewRoot.dispatchDragEvent(event);
3360 }
3361 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003362 }
3363
3364 /**
3365 * Maintains state information for a single trackball axis, generating
3366 * discrete (DPAD) movements based on raw trackball motion.
3367 */
3368 static final class TrackballAxis {
3369 /**
3370 * The maximum amount of acceleration we will apply.
3371 */
3372 static final float MAX_ACCELERATION = 20;
Romain Guy8506ab42009-06-11 17:35:47 -07003373
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003374 /**
3375 * The maximum amount of time (in milliseconds) between events in order
3376 * for us to consider the user to be doing fast trackball movements,
3377 * and thus apply an acceleration.
3378 */
3379 static final long FAST_MOVE_TIME = 150;
Romain Guy8506ab42009-06-11 17:35:47 -07003380
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003381 /**
3382 * Scaling factor to the time (in milliseconds) between events to how
3383 * much to multiple/divide the current acceleration. When movement
3384 * is < FAST_MOVE_TIME this multiplies the acceleration; when >
3385 * FAST_MOVE_TIME it divides it.
3386 */
3387 static final float ACCEL_MOVE_SCALING_FACTOR = (1.0f/40);
Romain Guy8506ab42009-06-11 17:35:47 -07003388
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003389 float position;
3390 float absPosition;
3391 float acceleration = 1;
3392 long lastMoveTime = 0;
3393 int step;
3394 int dir;
3395 int nonAccelMovement;
3396
3397 void reset(int _step) {
3398 position = 0;
3399 acceleration = 1;
3400 lastMoveTime = 0;
3401 step = _step;
3402 dir = 0;
3403 }
3404
3405 /**
3406 * Add trackball movement into the state. If the direction of movement
3407 * has been reversed, the state is reset before adding the
3408 * movement (so that you don't have to compensate for any previously
3409 * collected movement before see the result of the movement in the
3410 * new direction).
3411 *
3412 * @return Returns the absolute value of the amount of movement
3413 * collected so far.
3414 */
3415 float collect(float off, long time, String axis) {
3416 long normTime;
3417 if (off > 0) {
3418 normTime = (long)(off * FAST_MOVE_TIME);
3419 if (dir < 0) {
3420 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to positive!");
3421 position = 0;
3422 step = 0;
3423 acceleration = 1;
3424 lastMoveTime = 0;
3425 }
3426 dir = 1;
3427 } else if (off < 0) {
3428 normTime = (long)((-off) * FAST_MOVE_TIME);
3429 if (dir > 0) {
3430 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to negative!");
3431 position = 0;
3432 step = 0;
3433 acceleration = 1;
3434 lastMoveTime = 0;
3435 }
3436 dir = -1;
3437 } else {
3438 normTime = 0;
3439 }
Romain Guy8506ab42009-06-11 17:35:47 -07003440
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003441 // The number of milliseconds between each movement that is
3442 // considered "normal" and will not result in any acceleration
3443 // or deceleration, scaled by the offset we have here.
3444 if (normTime > 0) {
3445 long delta = time - lastMoveTime;
3446 lastMoveTime = time;
3447 float acc = acceleration;
3448 if (delta < normTime) {
3449 // The user is scrolling rapidly, so increase acceleration.
3450 float scale = (normTime-delta) * ACCEL_MOVE_SCALING_FACTOR;
3451 if (scale > 1) acc *= scale;
3452 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " accelerate: off="
3453 + off + " normTime=" + normTime + " delta=" + delta
3454 + " scale=" + scale + " acc=" + acc);
3455 acceleration = acc < MAX_ACCELERATION ? acc : MAX_ACCELERATION;
3456 } else {
3457 // The user is scrolling slowly, so decrease acceleration.
3458 float scale = (delta-normTime) * ACCEL_MOVE_SCALING_FACTOR;
3459 if (scale > 1) acc /= scale;
3460 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " deccelerate: off="
3461 + off + " normTime=" + normTime + " delta=" + delta
3462 + " scale=" + scale + " acc=" + acc);
3463 acceleration = acc > 1 ? acc : 1;
3464 }
3465 }
3466 position += off;
3467 return (absPosition = Math.abs(position));
3468 }
3469
3470 /**
3471 * Generate the number of discrete movement events appropriate for
3472 * the currently collected trackball movement.
3473 *
3474 * @param precision The minimum movement required to generate the
3475 * first discrete movement.
3476 *
3477 * @return Returns the number of discrete movements, either positive
3478 * or negative, or 0 if there is not enough trackball movement yet
3479 * for a discrete movement.
3480 */
3481 int generate(float precision) {
3482 int movement = 0;
3483 nonAccelMovement = 0;
3484 do {
3485 final int dir = position >= 0 ? 1 : -1;
3486 switch (step) {
3487 // If we are going to execute the first step, then we want
3488 // to do this as soon as possible instead of waiting for
3489 // a full movement, in order to make things look responsive.
3490 case 0:
3491 if (absPosition < precision) {
3492 return movement;
3493 }
3494 movement += dir;
3495 nonAccelMovement += dir;
3496 step = 1;
3497 break;
3498 // If we have generated the first movement, then we need
3499 // to wait for the second complete trackball motion before
3500 // generating the second discrete movement.
3501 case 1:
3502 if (absPosition < 2) {
3503 return movement;
3504 }
3505 movement += dir;
3506 nonAccelMovement += dir;
3507 position += dir > 0 ? -2 : 2;
3508 absPosition = Math.abs(position);
3509 step = 2;
3510 break;
3511 // After the first two, we generate discrete movements
3512 // consistently with the trackball, applying an acceleration
3513 // if the trackball is moving quickly. This is a simple
3514 // acceleration on top of what we already compute based
3515 // on how quickly the wheel is being turned, to apply
3516 // a longer increasing acceleration to continuous movement
3517 // in one direction.
3518 default:
3519 if (absPosition < 1) {
3520 return movement;
3521 }
3522 movement += dir;
3523 position += dir >= 0 ? -1 : 1;
3524 absPosition = Math.abs(position);
3525 float acc = acceleration;
3526 acc *= 1.1f;
3527 acceleration = acc < MAX_ACCELERATION ? acc : acceleration;
3528 break;
3529 }
3530 } while (true);
3531 }
3532 }
3533
3534 public static final class CalledFromWrongThreadException extends AndroidRuntimeException {
3535 public CalledFromWrongThreadException(String msg) {
3536 super(msg);
3537 }
3538 }
3539
3540 private SurfaceHolder mHolder = new SurfaceHolder() {
3541 // we only need a SurfaceHolder for opengl. it would be nice
3542 // to implement everything else though, especially the callback
3543 // support (opengl doesn't make use of it right now, but eventually
3544 // will).
3545 public Surface getSurface() {
3546 return mSurface;
3547 }
3548
3549 public boolean isCreating() {
3550 return false;
3551 }
3552
3553 public void addCallback(Callback callback) {
3554 }
3555
3556 public void removeCallback(Callback callback) {
3557 }
3558
3559 public void setFixedSize(int width, int height) {
3560 }
3561
3562 public void setSizeFromLayout() {
3563 }
3564
3565 public void setFormat(int format) {
3566 }
3567
3568 public void setType(int type) {
3569 }
3570
3571 public void setKeepScreenOn(boolean screenOn) {
3572 }
3573
3574 public Canvas lockCanvas() {
3575 return null;
3576 }
3577
3578 public Canvas lockCanvas(Rect dirty) {
3579 return null;
3580 }
3581
3582 public void unlockCanvasAndPost(Canvas canvas) {
3583 }
3584 public Rect getSurfaceFrame() {
3585 return null;
3586 }
3587 };
3588
3589 static RunQueue getRunQueue() {
3590 RunQueue rq = sRunQueues.get();
3591 if (rq != null) {
3592 return rq;
3593 }
3594 rq = new RunQueue();
3595 sRunQueues.set(rq);
3596 return rq;
3597 }
Romain Guy8506ab42009-06-11 17:35:47 -07003598
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003599 /**
3600 * @hide
3601 */
3602 static final class RunQueue {
3603 private final ArrayList<HandlerAction> mActions = new ArrayList<HandlerAction>();
3604
3605 void post(Runnable action) {
3606 postDelayed(action, 0);
3607 }
3608
3609 void postDelayed(Runnable action, long delayMillis) {
3610 HandlerAction handlerAction = new HandlerAction();
3611 handlerAction.action = action;
3612 handlerAction.delay = delayMillis;
3613
3614 synchronized (mActions) {
3615 mActions.add(handlerAction);
3616 }
3617 }
3618
3619 void removeCallbacks(Runnable action) {
3620 final HandlerAction handlerAction = new HandlerAction();
3621 handlerAction.action = action;
3622
3623 synchronized (mActions) {
3624 final ArrayList<HandlerAction> actions = mActions;
3625
3626 while (actions.remove(handlerAction)) {
3627 // Keep going
3628 }
3629 }
3630 }
3631
3632 void executeActions(Handler handler) {
3633 synchronized (mActions) {
3634 final ArrayList<HandlerAction> actions = mActions;
3635 final int count = actions.size();
3636
3637 for (int i = 0; i < count; i++) {
3638 final HandlerAction handlerAction = actions.get(i);
3639 handler.postDelayed(handlerAction.action, handlerAction.delay);
3640 }
3641
Romain Guy15df6702009-08-17 20:17:30 -07003642 actions.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003643 }
3644 }
3645
3646 private static class HandlerAction {
3647 Runnable action;
3648 long delay;
3649
3650 @Override
3651 public boolean equals(Object o) {
3652 if (this == o) return true;
3653 if (o == null || getClass() != o.getClass()) return false;
3654
3655 HandlerAction that = (HandlerAction) o;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003656 return !(action != null ? !action.equals(that.action) : that.action != null);
3657
3658 }
3659
3660 @Override
3661 public int hashCode() {
3662 int result = action != null ? action.hashCode() : 0;
3663 result = 31 * result + (int) (delay ^ (delay >>> 32));
3664 return result;
3665 }
3666 }
3667 }
3668
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003669 private static native void nativeShowFPS(Canvas canvas, int durationMillis);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003670}