blob: 8085ea8974e8ebb3992d1a597917d0aeb0e926d6 [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;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -070052import android.util.DisplayMetrics;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080053import android.util.EventLog;
Romain Guy6b7bd242010-10-06 19:49:23 -070054import android.util.Log;
Chet Haase949dbf72010-08-11 18:41:06 -070055import android.util.Slog;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080056import android.util.SparseArray;
Dianne Hackborn711e62a2010-11-29 16:38:22 -080057import android.util.TypedValue;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080058import android.view.View.MeasureSpec;
svetoslavganov75986cf2009-05-14 22:28:01 -070059import android.view.accessibility.AccessibilityEvent;
60import android.view.accessibility.AccessibilityManager;
Dianne Hackborn0f761d62010-11-30 22:06:10 -080061import android.view.animation.AccelerateDecelerateInterpolator;
62import android.view.animation.Interpolator;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080063import android.view.inputmethod.InputConnection;
64import android.view.inputmethod.InputMethodManager;
65import android.widget.Scroller;
Joe Onorato86f67862010-11-05 18:57:34 -070066import com.android.internal.policy.PolicyManager;
Romain Guy6b7bd242010-10-06 19:49:23 -070067import com.android.internal.view.BaseSurfaceHolder;
68import com.android.internal.view.IInputMethodCallback;
69import com.android.internal.view.IInputMethodSession;
70import com.android.internal.view.RootViewSurfaceTaker;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080071
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080072import java.io.IOException;
73import java.io.OutputStream;
Romain Guy6b7bd242010-10-06 19:49:23 -070074import java.lang.ref.WeakReference;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080075import java.util.ArrayList;
76
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080077/**
78 * The top of a view hierarchy, implementing the needed protocol between View
79 * and the WindowManager. This is for the most part an internal implementation
80 * detail of {@link WindowManagerImpl}.
81 *
82 * {@hide}
83 */
Romain Guy812ccbe2010-06-01 14:07:24 -070084@SuppressWarnings({"EmptyCatchBlock", "PointlessBooleanExpression"})
Joe Onoratoc6cc0f82011-04-12 11:53:13 -070085public final class ViewAncestor extends Handler implements ViewParent,
Dianne Hackborn0f761d62010-11-30 22:06:10 -080086 View.AttachInfo.Callbacks, HardwareRenderer.HardwareDrawCallbacks {
Joe Onoratoc6cc0f82011-04-12 11:53:13 -070087 private static final String TAG = "ViewAncestor";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080088 private static final boolean DBG = false;
Mike Reedfd716532009-10-12 14:42:56 -040089 private static final boolean SHOW_FPS = false;
Romain Guy812ccbe2010-06-01 14:07:24 -070090 private static final boolean LOCAL_LOGV = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080091 /** @noinspection PointlessBooleanExpression*/
92 private static final boolean DEBUG_DRAW = false || LOCAL_LOGV;
93 private static final boolean DEBUG_LAYOUT = false || LOCAL_LOGV;
Dianne Hackborn711e62a2010-11-29 16:38:22 -080094 private static final boolean DEBUG_DIALOG = false || LOCAL_LOGV;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080095 private static final boolean DEBUG_INPUT_RESIZE = false || LOCAL_LOGV;
96 private static final boolean DEBUG_ORIENTATION = false || LOCAL_LOGV;
97 private static final boolean DEBUG_TRACKBALL = false || LOCAL_LOGV;
98 private static final boolean DEBUG_IMF = false || LOCAL_LOGV;
Dianne Hackborn694f79b2010-03-17 19:44:59 -070099 private static final boolean DEBUG_CONFIGURATION = false || LOCAL_LOGV;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800100 private static final boolean WATCH_POINTER = false;
101
Michael Chan53071d62009-05-13 17:29:48 -0700102 private static final boolean MEASURE_LATENCY = false;
103 private static LatencyTimer lt;
104
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800105 /**
106 * Maximum time we allow the user to roll the trackball enough to generate
107 * a key event, before resetting the counters.
108 */
109 static final int MAX_TRACKBALL_DELAY = 250;
110
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800111 static IWindowSession sWindowSession;
112
113 static final Object mStaticInit = new Object();
114 static boolean mInitialized = false;
115
116 static final ThreadLocal<RunQueue> sRunQueues = new ThreadLocal<RunQueue>();
117
Dianne Hackborn2a9094d2010-02-03 19:20:09 -0800118 static final ArrayList<Runnable> sFirstDrawHandlers = new ArrayList<Runnable>();
119 static boolean sFirstDrawComplete = false;
120
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800121 static final ArrayList<ComponentCallbacks> sConfigCallbacks
122 = new ArrayList<ComponentCallbacks>();
123
Romain Guy8506ab42009-06-11 17:35:47 -0700124 private static int sDrawTime;
Romain Guy13922e02009-05-12 17:56:14 -0700125
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800126 long mLastTrackballTime = 0;
127 final TrackballAxis mTrackballAxisX = new TrackballAxis();
128 final TrackballAxis mTrackballAxisY = new TrackballAxis();
129
Jeff Browncb1404e2011-01-15 18:14:15 -0800130 int mLastJoystickXDirection;
131 int mLastJoystickYDirection;
132 int mLastJoystickXKeyCode;
133 int mLastJoystickYKeyCode;
134
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800135 final int[] mTmpLocation = new int[2];
Romain Guy8506ab42009-06-11 17:35:47 -0700136
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800137 final TypedValue mTmpValue = new TypedValue();
138
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800139 final InputMethodCallback mInputMethodCallback;
140 final SparseArray<Object> mPendingEvents = new SparseArray<Object>();
141 int mPendingEventSeq = 0;
Romain Guy8506ab42009-06-11 17:35:47 -0700142
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800143 final Thread mThread;
144
145 final WindowLeaked mLocation;
146
147 final WindowManager.LayoutParams mWindowAttributes = new WindowManager.LayoutParams();
148
149 final W mWindow;
150
151 View mView;
152 View mFocusedView;
153 View mRealFocusedView; // this is not set to null in touch mode
154 int mViewVisibility;
155 boolean mAppVisible = true;
156
Dianne Hackbornce418e62011-03-01 14:31:38 -0800157 // Set to true if the owner of this window is in the stopped state,
158 // so the window should no longer be active.
159 boolean mStopped = false;
160
Dianne Hackbornd76b67c2010-07-13 17:48:30 -0700161 SurfaceHolder.Callback2 mSurfaceHolderCallback;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700162 BaseSurfaceHolder mSurfaceHolder;
163 boolean mIsCreating;
164 boolean mDrawingAllowed;
165
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800166 final Region mTransparentRegion;
167 final Region mPreviousTransparentRegion;
168
169 int mWidth;
170 int mHeight;
Romain Guy7d7b5492011-01-24 16:33:45 -0800171 Rect mDirty;
172 final Rect mCurrentDirty = new Rect();
173 final Rect mPreviousDirty = new Rect();
Romain Guybb93d552009-03-24 21:04:15 -0700174 boolean mIsAnimating;
Romain Guy8506ab42009-06-11 17:35:47 -0700175
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700176 CompatibilityInfo.Translator mTranslator;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800177
178 final View.AttachInfo mAttachInfo;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700179 InputChannel mInputChannel;
Dianne Hackborn1e4b9f32010-06-23 14:10:57 -0700180 InputQueue.Callback mInputQueueCallback;
181 InputQueue mInputQueue;
Joe Onorato86f67862010-11-05 18:57:34 -0700182 FallbackEventHandler mFallbackEventHandler;
Dianne Hackborna95e4cb2010-06-18 18:09:33 -0700183
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800184 final Rect mTempRect; // used in the transaction to not thrash the heap.
185 final Rect mVisRect; // used to retrieve visible rect of focused view.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800186
187 boolean mTraversalScheduled;
Jeff Brown4e91a182011-04-07 11:38:09 -0700188 long mLastTraversalFinishedTimeNanos;
189 long mLastDrawDurationNanos;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800190 boolean mWillDrawSoon;
191 boolean mLayoutRequested;
192 boolean mFirst;
193 boolean mReportNextDraw;
194 boolean mFullRedrawNeeded;
195 boolean mNewSurfaceNeeded;
196 boolean mHasHadWindowFocus;
197 boolean mLastWasImTarget;
198
199 boolean mWindowAttributesChanged = false;
200
201 // These can be accessed by any thread, must be protected with a lock.
Mathias Agopian5583dc62009-07-09 16:28:11 -0700202 // Surface can never be reassigned or cleared (use Surface.clear()).
203 private final Surface mSurface = new Surface();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800204
205 boolean mAdded;
206 boolean mAddedTouchMode;
207
208 /*package*/ int mAddNesting;
209
210 // These are accessed by multiple threads.
211 final Rect mWinFrame; // frame given by window manager.
212
213 final Rect mPendingVisibleInsets = new Rect();
214 final Rect mPendingContentInsets = new Rect();
215 final ViewTreeObserver.InternalInsetsInfo mLastGivenInsets
216 = new ViewTreeObserver.InternalInsetsInfo();
217
Dianne Hackborn694f79b2010-03-17 19:44:59 -0700218 final Configuration mLastConfiguration = new Configuration();
219 final Configuration mPendingConfiguration = new Configuration();
220
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800221 class ResizedInfo {
222 Rect coveredInsets;
223 Rect visibleInsets;
224 Configuration newConfig;
225 }
226
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800227 boolean mScrollMayChange;
228 int mSoftInputMode;
229 View mLastScrolledFocus;
230 int mScrollY;
231 int mCurScrollY;
232 Scroller mScroller;
Dianne Hackborn0f761d62010-11-30 22:06:10 -0800233 Bitmap mResizeBitmap;
234 long mResizeBitmapStartTime;
235 int mResizeBitmapDuration;
236 static final Interpolator mResizeInterpolator = new AccelerateDecelerateInterpolator();
Romain Guy8506ab42009-06-11 17:35:47 -0700237
Romain Guy8506ab42009-06-11 17:35:47 -0700238 final ViewConfiguration mViewConfiguration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800239
Christopher Tatea53146c2010-09-07 11:57:52 -0700240 /* Drag/drop */
241 ClipDescription mDragDescription;
242 View mCurrentDragView;
Christopher Tate7fb8b562011-01-20 13:46:41 -0800243 volatile Object mLocalDragState;
Christopher Tatea53146c2010-09-07 11:57:52 -0700244 final PointF mDragPoint = new PointF();
Christopher Tate2c095f32010-10-04 14:13:40 -0700245 final PointF mLastTouchPoint = new PointF();
Christopher Tatea53146c2010-09-07 11:57:52 -0700246
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800247 /**
248 * see {@link #playSoundEffect(int)}
249 */
250 AudioManager mAudioManager;
251
Dianne Hackborn11ea3342009-07-22 21:48:55 -0700252 private final int mDensity;
Adam Powellb08013c2010-09-16 16:28:11 -0700253
Jeff Brown21bc5c92011-02-28 18:27:14 -0800254 /**
255 * Consistency verifier for debugging purposes.
256 */
257 protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier =
258 InputEventConsistencyVerifier.isInstrumentationEnabled() ?
259 new InputEventConsistencyVerifier(this, 0) : null;
260
Dianne Hackborn4c62fc02009-08-08 20:40:27 -0700261 public static IWindowSession getWindowSession(Looper mainLooper) {
262 synchronized (mStaticInit) {
263 if (!mInitialized) {
264 try {
265 InputMethodManager imm = InputMethodManager.getInstance(mainLooper);
Dianne Hackborn44bc17c2011-04-20 18:18:51 -0700266 sWindowSession = Display.getWindowManager().openSession(
267 imm.getClient(), imm.getInputContext());
Dianne Hackborn4c62fc02009-08-08 20:40:27 -0700268 mInitialized = true;
269 } catch (RemoteException e) {
270 }
271 }
272 return sWindowSession;
273 }
274 }
275
Joe Onoratoc6cc0f82011-04-12 11:53:13 -0700276 public ViewAncestor(Context context) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800277 super();
278
Romain Guy812ccbe2010-06-01 14:07:24 -0700279 if (MEASURE_LATENCY) {
280 if (lt == null) {
281 lt = new LatencyTimer(100, 1000);
282 }
Michael Chan53071d62009-05-13 17:29:48 -0700283 }
284
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800285 // Initialize the statics when this class is first instantiated. This is
286 // done here instead of in the static block because Zygote does not
287 // allow the spawning of threads.
Dianne Hackborn4c62fc02009-08-08 20:40:27 -0700288 getWindowSession(context.getMainLooper());
289
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800290 mThread = Thread.currentThread();
291 mLocation = new WindowLeaked(null);
292 mLocation.fillInStackTrace();
293 mWidth = -1;
294 mHeight = -1;
295 mDirty = new Rect();
296 mTempRect = new Rect();
297 mVisRect = new Rect();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800298 mWinFrame = new Rect();
Romain Guyfb8b7632010-08-23 21:05:08 -0700299 mWindow = new W(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800300 mInputMethodCallback = new InputMethodCallback(this);
301 mViewVisibility = View.GONE;
302 mTransparentRegion = new Region();
303 mPreviousTransparentRegion = new Region();
304 mFirst = true; // true for the first time the view is added
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800305 mAdded = false;
306 mAttachInfo = new View.AttachInfo(sWindowSession, mWindow, this, this);
307 mViewConfiguration = ViewConfiguration.get(context);
Dianne Hackborn11ea3342009-07-22 21:48:55 -0700308 mDensity = context.getResources().getDisplayMetrics().densityDpi;
Joe Onorato86f67862010-11-05 18:57:34 -0700309 mFallbackEventHandler = PolicyManager.makeNewFallbackEventHandler(context);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800310 }
311
Dianne Hackborn2a9094d2010-02-03 19:20:09 -0800312 public static void addFirstDrawHandler(Runnable callback) {
313 synchronized (sFirstDrawHandlers) {
314 if (!sFirstDrawComplete) {
315 sFirstDrawHandlers.add(callback);
316 }
317 }
318 }
319
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800320 public static void addConfigCallback(ComponentCallbacks callback) {
321 synchronized (sConfigCallbacks) {
322 sConfigCallbacks.add(callback);
323 }
324 }
325
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800326 // FIXME for perf testing only
327 private boolean mProfile = false;
328
329 /**
330 * Call this to profile the next traversal call.
331 * FIXME for perf testing only. Remove eventually
332 */
333 public void profile() {
334 mProfile = true;
335 }
336
337 /**
338 * Indicates whether we are in touch mode. Calling this method triggers an IPC
339 * call and should be avoided whenever possible.
340 *
341 * @return True, if the device is in touch mode, false otherwise.
342 *
343 * @hide
344 */
345 static boolean isInTouchMode() {
346 if (mInitialized) {
347 try {
348 return sWindowSession.getInTouchMode();
349 } catch (RemoteException e) {
350 }
351 }
352 return false;
353 }
354
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800355 /**
356 * We have one child
357 */
Romain Guye4d01122010-06-16 18:44:05 -0700358 public void setView(View view, WindowManager.LayoutParams attrs, View panelParentView) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800359 synchronized (this) {
360 if (mView == null) {
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700361 mView = view;
Joe Onorato86f67862010-11-05 18:57:34 -0700362 mFallbackEventHandler.setView(view);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700363 mWindowAttributes.copyFrom(attrs);
Mitsuru Oshima1ecf5d22009-07-06 17:20:38 -0700364 attrs = mWindowAttributes;
Romain Guye4d01122010-06-16 18:44:05 -0700365
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700366 if (view instanceof RootViewSurfaceTaker) {
367 mSurfaceHolderCallback =
368 ((RootViewSurfaceTaker)view).willYouTakeTheSurface();
369 if (mSurfaceHolderCallback != null) {
370 mSurfaceHolder = new TakenSurfaceHolder();
Dianne Hackborn289b9b62010-07-09 11:44:11 -0700371 mSurfaceHolder.setFormat(PixelFormat.UNKNOWN);
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700372 }
373 }
Romain Guy1aec9a22011-01-05 09:37:12 -0800374
375 // If the application owns the surface, don't enable hardware acceleration
376 if (mSurfaceHolder == null) {
377 enableHardwareAcceleration(attrs);
378 }
379
Mitsuru Oshima38ed7d772009-07-21 14:39:34 -0700380 Resources resources = mView.getContext().getResources();
381 CompatibilityInfo compatibilityInfo = resources.getCompatibilityInfo();
Mitsuru Oshima589cebe2009-07-22 20:38:58 -0700382 mTranslator = compatibilityInfo.getTranslator();
Mitsuru Oshima38ed7d772009-07-21 14:39:34 -0700383
384 if (mTranslator != null || !compatibilityInfo.supportsScreen()) {
Mitsuru Oshima240f8a72009-07-22 20:39:14 -0700385 mSurface.setCompatibleDisplayMetrics(resources.getDisplayMetrics(),
386 mTranslator);
Mitsuru Oshima38ed7d772009-07-21 14:39:34 -0700387 }
388
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -0700389 boolean restore = false;
Romain Guy35b38ce2009-10-07 13:38:55 -0700390 if (mTranslator != null) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -0700391 restore = true;
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700392 attrs.backup();
393 mTranslator.translateWindowLayout(attrs);
Mitsuru Oshima3d914922009-05-13 22:29:15 -0700394 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700395 if (DEBUG_LAYOUT) Log.d(TAG, "WindowLayout in setView:" + attrs);
396
Mitsuru Oshima1ecf5d22009-07-06 17:20:38 -0700397 if (!compatibilityInfo.supportsScreen()) {
398 attrs.flags |= WindowManager.LayoutParams.FLAG_COMPATIBLE_WINDOW;
399 }
400
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800401 mSoftInputMode = attrs.softInputMode;
402 mWindowAttributesChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800403 mAttachInfo.mRootView = view;
Romain Guy35b38ce2009-10-07 13:38:55 -0700404 mAttachInfo.mScalingRequired = mTranslator != null;
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700405 mAttachInfo.mApplicationScale =
406 mTranslator == null ? 1.0f : mTranslator.applicationScale;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800407 if (panelParentView != null) {
408 mAttachInfo.mPanelParentWindowToken
409 = panelParentView.getApplicationWindowToken();
410 }
411 mAdded = true;
412 int res; /* = WindowManagerImpl.ADD_OKAY; */
Romain Guy8506ab42009-06-11 17:35:47 -0700413
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800414 // Schedule the first layout -before- adding to the window
415 // manager, to make sure we do the relayout before receiving
416 // any other events from the system.
417 requestLayout();
Jeff Brown46b9ac02010-04-22 18:58:52 -0700418 mInputChannel = new InputChannel();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800419 try {
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700420 res = sWindowSession.add(mWindow, mWindowAttributes,
Jeff Brown46b9ac02010-04-22 18:58:52 -0700421 getHostVisibility(), mAttachInfo.mContentInsets,
422 mInputChannel);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800423 } catch (RemoteException e) {
424 mAdded = false;
425 mView = null;
426 mAttachInfo.mRootView = null;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700427 mInputChannel = null;
Joe Onorato86f67862010-11-05 18:57:34 -0700428 mFallbackEventHandler.setView(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800429 unscheduleTraversals();
430 throw new RuntimeException("Adding window failed", e);
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700431 } finally {
432 if (restore) {
433 attrs.restore();
434 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800435 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700436
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700437 if (mTranslator != null) {
438 mTranslator.translateRectInScreenToAppWindow(mAttachInfo.mContentInsets);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700439 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800440 mPendingContentInsets.set(mAttachInfo.mContentInsets);
441 mPendingVisibleInsets.set(0, 0, 0, 0);
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800442 if (DEBUG_LAYOUT) Log.v(TAG, "Added window " + mWindow);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800443 if (res < WindowManagerImpl.ADD_OKAY) {
444 mView = null;
445 mAttachInfo.mRootView = null;
446 mAdded = false;
Joe Onorato86f67862010-11-05 18:57:34 -0700447 mFallbackEventHandler.setView(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800448 unscheduleTraversals();
449 switch (res) {
450 case WindowManagerImpl.ADD_BAD_APP_TOKEN:
451 case WindowManagerImpl.ADD_BAD_SUBWINDOW_TOKEN:
452 throw new WindowManagerImpl.BadTokenException(
453 "Unable to add window -- token " + attrs.token
454 + " is not valid; is your activity running?");
455 case WindowManagerImpl.ADD_NOT_APP_TOKEN:
456 throw new WindowManagerImpl.BadTokenException(
457 "Unable to add window -- token " + attrs.token
458 + " is not for an application");
459 case WindowManagerImpl.ADD_APP_EXITING:
460 throw new WindowManagerImpl.BadTokenException(
461 "Unable to add window -- app for token " + attrs.token
462 + " is exiting");
463 case WindowManagerImpl.ADD_DUPLICATE_ADD:
464 throw new WindowManagerImpl.BadTokenException(
465 "Unable to add window -- window " + mWindow
466 + " has already been added");
467 case WindowManagerImpl.ADD_STARTING_NOT_NEEDED:
468 // Silently ignore -- we would have just removed it
469 // right away, anyway.
470 return;
471 case WindowManagerImpl.ADD_MULTIPLE_SINGLETON:
472 throw new WindowManagerImpl.BadTokenException(
473 "Unable to add window " + mWindow +
474 " -- another window of this type already exists");
475 case WindowManagerImpl.ADD_PERMISSION_DENIED:
476 throw new WindowManagerImpl.BadTokenException(
477 "Unable to add window " + mWindow +
478 " -- permission denied for this window type");
479 }
480 throw new RuntimeException(
481 "Unable to add window -- unknown error code " + res);
482 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700483
Jeff Brown00fa7bd2010-07-02 15:37:36 -0700484 if (view instanceof RootViewSurfaceTaker) {
485 mInputQueueCallback =
486 ((RootViewSurfaceTaker)view).willYouTakeTheInputQueue();
487 }
488 if (mInputQueueCallback != null) {
489 mInputQueue = new InputQueue(mInputChannel);
490 mInputQueueCallback.onInputQueueCreated(mInputQueue);
491 } else {
492 InputQueue.registerInputChannel(mInputChannel, mInputHandler,
493 Looper.myQueue());
Jeff Brown46b9ac02010-04-22 18:58:52 -0700494 }
495
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800496 view.assignParent(this);
497 mAddedTouchMode = (res&WindowManagerImpl.ADD_FLAG_IN_TOUCH_MODE) != 0;
498 mAppVisible = (res&WindowManagerImpl.ADD_FLAG_APP_VISIBLE) != 0;
499 }
500 }
501 }
502
Romain Guy529b60a2010-08-03 18:05:47 -0700503 private void enableHardwareAcceleration(WindowManager.LayoutParams attrs) {
Dianne Hackborn7eec10e2010-11-12 18:03:47 -0800504 mAttachInfo.mHardwareAccelerated = false;
505 mAttachInfo.mHardwareAccelerationRequested = false;
Romain Guy4f6aff32011-01-12 16:21:41 -0800506
Dianne Hackborn7eec10e2010-11-12 18:03:47 -0800507 // Try to enable hardware acceleration if requested
Jim Miller1b365922011-03-09 19:38:07 -0800508 final boolean hardwareAccelerated =
509 (attrs.flags & WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED) != 0;
510
Romain Guy566c3312011-03-21 18:21:28 -0700511 if (hardwareAccelerated) {
Romain Guy1af23a32011-03-24 16:03:55 -0700512 if (!HardwareRenderer.isAvailable()) {
513 mAttachInfo.mHardwareAccelerationRequested = true;
514 return;
515 }
516
Dianne Hackborn7eec10e2010-11-12 18:03:47 -0800517 // Only enable hardware acceleration if we are not in the system process
Joe Onoratoc6cc0f82011-04-12 11:53:13 -0700518 // The window manager creates ViewAncestors to display animated preview windows
Dianne Hackborn7eec10e2010-11-12 18:03:47 -0800519 // of launching apps and we don't want those to be hardware accelerated
Jim Miller1b365922011-03-09 19:38:07 -0800520
521 final boolean systemHwAccelerated =
522 (attrs.flags & WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED_SYSTEM) != 0;
523
524 if (!HardwareRenderer.sRendererDisabled || systemHwAccelerated) {
Romain Guyff26a0c2011-01-20 11:35:46 -0800525 // Don't enable hardware acceleration when we're not on the main thread
Jim Miller1b365922011-03-09 19:38:07 -0800526 if (!systemHwAccelerated && Looper.getMainLooper() != Looper.myLooper()) {
527 Log.w(HardwareRenderer.LOG_TAG, "Attempting to initialize hardware "
Romain Guyff26a0c2011-01-20 11:35:46 -0800528 + "acceleration outside of the main thread, aborting");
529 return;
530 }
531
Romain Guye4d01122010-06-16 18:44:05 -0700532 final boolean translucent = attrs.format != PixelFormat.OPAQUE;
Romain Guyb051e892010-09-28 19:09:36 -0700533 if (mAttachInfo.mHardwareRenderer != null) {
534 mAttachInfo.mHardwareRenderer.destroy(true);
Romain Guy4caa4ed2010-08-25 14:46:24 -0700535 }
Romain Guyb051e892010-09-28 19:09:36 -0700536 mAttachInfo.mHardwareRenderer = HardwareRenderer.createGlRenderer(2, translucent);
Dianne Hackborn7eec10e2010-11-12 18:03:47 -0800537 mAttachInfo.mHardwareAccelerated = mAttachInfo.mHardwareAccelerationRequested
538 = mAttachInfo.mHardwareRenderer != null;
Romain Guye4d01122010-06-16 18:44:05 -0700539 }
540 }
541 }
542
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800543 public View getView() {
544 return mView;
545 }
546
547 final WindowLeaked getLocation() {
548 return mLocation;
549 }
550
551 void setLayoutParams(WindowManager.LayoutParams attrs, boolean newView) {
552 synchronized (this) {
The Android Open Source Project10592532009-03-18 17:39:46 -0700553 int oldSoftInputMode = mWindowAttributes.softInputMode;
Mitsuru Oshima5a2b91d2009-07-16 16:30:02 -0700554 // preserve compatible window flag if exists.
555 int compatibleWindowFlag =
556 mWindowAttributes.flags & WindowManager.LayoutParams.FLAG_COMPATIBLE_WINDOW;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800557 mWindowAttributes.copyFrom(attrs);
Mitsuru Oshima5a2b91d2009-07-16 16:30:02 -0700558 mWindowAttributes.flags |= compatibleWindowFlag;
559
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800560 if (newView) {
561 mSoftInputMode = attrs.softInputMode;
562 requestLayout();
563 }
The Android Open Source Project10592532009-03-18 17:39:46 -0700564 // Don't lose the mode we last auto-computed.
565 if ((attrs.softInputMode&WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST)
566 == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED) {
567 mWindowAttributes.softInputMode = (mWindowAttributes.softInputMode
568 & ~WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST)
569 | (oldSoftInputMode
570 & WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST);
571 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800572 mWindowAttributesChanged = true;
573 scheduleTraversals();
574 }
575 }
576
577 void handleAppVisibility(boolean visible) {
578 if (mAppVisible != visible) {
579 mAppVisible = visible;
580 scheduleTraversals();
581 }
582 }
583
584 void handleGetNewSurface() {
585 mNewSurfaceNeeded = true;
586 mFullRedrawNeeded = true;
587 scheduleTraversals();
588 }
589
590 /**
591 * {@inheritDoc}
592 */
593 public void requestLayout() {
594 checkThread();
595 mLayoutRequested = true;
596 scheduleTraversals();
597 }
598
599 /**
600 * {@inheritDoc}
601 */
602 public boolean isLayoutRequested() {
603 return mLayoutRequested;
604 }
605
606 public void invalidateChild(View child, Rect dirty) {
607 checkThread();
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700608 if (DEBUG_DRAW) Log.v(TAG, "Invalidate child: " + dirty);
Chet Haase70d4ba12010-10-06 09:46:45 -0700609 if (dirty == null) {
610 // Fast invalidation for GL-enabled applications; GL must redraw everything
611 invalidate();
612 return;
613 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700614 if (mCurScrollY != 0 || mTranslator != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800615 mTempRect.set(dirty);
Romain Guy1e095972009-07-07 11:22:45 -0700616 dirty = mTempRect;
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700617 if (mCurScrollY != 0) {
Romain Guy1e095972009-07-07 11:22:45 -0700618 dirty.offset(0, -mCurScrollY);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700619 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700620 if (mTranslator != null) {
Romain Guy1e095972009-07-07 11:22:45 -0700621 mTranslator.translateRectInAppWindowToScreen(dirty);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700622 }
Romain Guy1e095972009-07-07 11:22:45 -0700623 if (mAttachInfo.mScalingRequired) {
624 dirty.inset(-1, -1);
625 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800626 }
Chet Haasedaf98e92011-01-10 14:10:36 -0800627 if (!mDirty.isEmpty() && !mDirty.contains(dirty)) {
Romain Guy7d695942010-12-01 17:22:29 -0800628 mAttachInfo.mIgnoreDirtyState = true;
629 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800630 mDirty.union(dirty);
631 if (!mWillDrawSoon) {
632 scheduleTraversals();
633 }
634 }
Romain Guy0d9275e2010-10-26 14:22:30 -0700635
636 void invalidate() {
637 mDirty.set(0, 0, mWidth, mHeight);
638 scheduleTraversals();
639 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800640
Dianne Hackbornce418e62011-03-01 14:31:38 -0800641 void setStopped(boolean stopped) {
642 if (mStopped != stopped) {
643 mStopped = stopped;
644 if (!stopped) {
645 scheduleTraversals();
646 }
647 }
648 }
649
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800650 public ViewParent getParent() {
651 return null;
652 }
653
654 public ViewParent invalidateChildInParent(final int[] location, final Rect dirty) {
655 invalidateChild(null, dirty);
656 return null;
657 }
658
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700659 public boolean getChildVisibleRect(View child, Rect r, android.graphics.Point offset) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800660 if (child != mView) {
661 throw new RuntimeException("child is not mine, honest!");
662 }
663 // Note: don't apply scroll offset, because we want to know its
664 // visibility in the virtual canvas being given to the view hierarchy.
665 return r.intersect(0, 0, mWidth, mHeight);
666 }
667
668 public void bringChildToFront(View child) {
669 }
670
671 public void scheduleTraversals() {
672 if (!mTraversalScheduled) {
673 mTraversalScheduled = true;
Jeff Brown4e91a182011-04-07 11:38:09 -0700674
675 if (ViewDebug.DEBUG_LATENCY && mLastTraversalFinishedTimeNanos != 0) {
676 final long now = System.nanoTime();
677 Log.d(TAG, "Latency: Scheduled traversal, it has been "
678 + ((now - mLastTraversalFinishedTimeNanos) * 0.000001f)
679 + "ms since the last traversal finished.");
680 }
681
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800682 sendEmptyMessage(DO_TRAVERSAL);
683 }
684 }
685
686 public void unscheduleTraversals() {
687 if (mTraversalScheduled) {
688 mTraversalScheduled = false;
689 removeMessages(DO_TRAVERSAL);
690 }
691 }
692
693 int getHostVisibility() {
694 return mAppVisible ? mView.getVisibility() : View.GONE;
695 }
Romain Guy8506ab42009-06-11 17:35:47 -0700696
Dianne Hackborn0f761d62010-11-30 22:06:10 -0800697 void disposeResizeBitmap() {
698 if (mResizeBitmap != null) {
699 mResizeBitmap.recycle();
700 mResizeBitmap = null;
701 }
702 }
703
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800704 private void performTraversals() {
705 // cache mView since it is used so much below...
706 final View host = mView;
707
708 if (DBG) {
709 System.out.println("======================================");
710 System.out.println("performTraversals");
711 host.debug();
712 }
713
714 if (host == null || !mAdded)
715 return;
716
717 mTraversalScheduled = false;
718 mWillDrawSoon = true;
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800719 boolean windowSizeMayChange = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800720 boolean fullRedrawNeeded = mFullRedrawNeeded;
721 boolean newSurface = false;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700722 boolean surfaceChanged = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800723 WindowManager.LayoutParams lp = mWindowAttributes;
724
725 int desiredWindowWidth;
726 int desiredWindowHeight;
727 int childWidthMeasureSpec;
728 int childHeightMeasureSpec;
729
730 final View.AttachInfo attachInfo = mAttachInfo;
731
732 final int viewVisibility = getHostVisibility();
733 boolean viewVisibilityChanged = mViewVisibility != viewVisibility
734 || mNewSurfaceNeeded;
735
736 WindowManager.LayoutParams params = null;
737 if (mWindowAttributesChanged) {
738 mWindowAttributesChanged = false;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700739 surfaceChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800740 params = lp;
741 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700742 Rect frame = mWinFrame;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800743 if (mFirst) {
744 fullRedrawNeeded = true;
745 mLayoutRequested = true;
746
Romain Guy8506ab42009-06-11 17:35:47 -0700747 DisplayMetrics packageMetrics =
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700748 mView.getContext().getResources().getDisplayMetrics();
749 desiredWindowWidth = packageMetrics.widthPixels;
750 desiredWindowHeight = packageMetrics.heightPixels;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800751
752 // For the very first time, tell the view hierarchy that it
753 // is attached to the window. Note that at this point the surface
754 // object is not initialized to its backing store, but soon it
755 // will be (assuming the window is visible).
756 attachInfo.mSurface = mSurface;
Romain Guyc5d55862011-01-21 19:01:46 -0800757 // We used to use the following condition to choose 32 bits drawing caches:
758 // PixelFormat.hasAlpha(lp.format) || lp.format == PixelFormat.RGBX_8888
759 // However, windows are now always 32 bits by default, so choose 32 bits
760 attachInfo.mUse32BitDrawingCache = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800761 attachInfo.mHasWindowFocus = false;
762 attachInfo.mWindowVisibility = viewVisibility;
763 attachInfo.mRecomputeGlobalAttributes = false;
764 attachInfo.mKeepScreenOn = false;
Joe Onorato664644d2011-01-23 17:53:23 -0800765 attachInfo.mSystemUiVisibility = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800766 viewVisibilityChanged = false;
Dianne Hackborn694f79b2010-03-17 19:44:59 -0700767 mLastConfiguration.setTo(host.getResources().getConfiguration());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800768 host.dispatchAttachedToWindow(attachInfo, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800769 //Log.i(TAG, "Screen on initialized: " + attachInfo.mKeepScreenOn);
svetoslavganov75986cf2009-05-14 22:28:01 -0700770
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800771 } else {
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700772 desiredWindowWidth = frame.width();
773 desiredWindowHeight = frame.height();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800774 if (desiredWindowWidth != mWidth || desiredWindowHeight != mHeight) {
Jeff Brownc5ed5912010-07-14 18:48:53 -0700775 if (DEBUG_ORIENTATION) Log.v(TAG,
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700776 "View " + host + " resized to: " + frame);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800777 fullRedrawNeeded = true;
778 mLayoutRequested = true;
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800779 windowSizeMayChange = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800780 }
781 }
782
783 if (viewVisibilityChanged) {
784 attachInfo.mWindowVisibility = viewVisibility;
785 host.dispatchWindowVisibilityChanged(viewVisibility);
786 if (viewVisibility != View.VISIBLE || mNewSurfaceNeeded) {
Romain Guyb051e892010-09-28 19:09:36 -0700787 if (mAttachInfo.mHardwareRenderer != null) {
788 mAttachInfo.mHardwareRenderer.destroy(false);
Romain Guy4caa4ed2010-08-25 14:46:24 -0700789 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800790 }
791 if (viewVisibility == View.GONE) {
792 // After making a window gone, we will count it as being
793 // shown for the first time the next time it gets focus.
794 mHasHadWindowFocus = false;
795 }
796 }
797
798 boolean insetsChanged = false;
Romain Guy8506ab42009-06-11 17:35:47 -0700799
Dianne Hackbornce418e62011-03-01 14:31:38 -0800800 if (mLayoutRequested && !mStopped) {
Romain Guy15df6702009-08-17 20:17:30 -0700801 // Execute enqueued actions on every layout in case a view that was detached
802 // enqueued an action after being detached
803 getRunQueue().executeActions(attachInfo.mHandler);
804
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800805 final Resources res = mView.getContext().getResources();
806
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800807 if (mFirst) {
808 host.fitSystemWindows(mAttachInfo.mContentInsets);
809 // make sure touch mode code executes by setting cached value
810 // to opposite of the added touch mode.
811 mAttachInfo.mInTouchMode = !mAddedTouchMode;
Romain Guy2d4cff62010-04-09 15:39:00 -0700812 ensureTouchModeLocally(mAddedTouchMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800813 } else {
814 if (!mAttachInfo.mContentInsets.equals(mPendingContentInsets)) {
Dianne Hackborn0f761d62010-11-30 22:06:10 -0800815 if (mWidth > 0 && mHeight > 0 &&
816 mSurface != null && mSurface.isValid() &&
Dianne Hackborn63042d62011-01-26 18:56:29 -0800817 !mAttachInfo.mTurnOffWindowResizeAnim &&
Dianne Hackborn0f761d62010-11-30 22:06:10 -0800818 mAttachInfo.mHardwareRenderer != null &&
819 mAttachInfo.mHardwareRenderer.isEnabled() &&
820 lp != null && !PixelFormat.formatHasAlpha(lp.format)) {
821
822 disposeResizeBitmap();
823
824 boolean completed = false;
825 try {
826 mResizeBitmap = Bitmap.createBitmap(mWidth, mHeight,
827 Bitmap.Config.ARGB_8888);
828 mResizeBitmap.setHasAlpha(false);
829 Canvas canvas = new Canvas(mResizeBitmap);
Romain Guyf90f8172011-01-25 22:53:24 -0800830 canvas.drawColor(0xff000000, PorterDuff.Mode.SRC);
Dianne Hackborn0f761d62010-11-30 22:06:10 -0800831 int yoff;
832 final boolean scrolling = mScroller != null
833 && mScroller.computeScrollOffset();
834 if (scrolling) {
835 yoff = mScroller.getCurrY();
836 mScroller.abortAnimation();
837 } else {
838 yoff = mScrollY;
839 }
840 canvas.translate(0, -yoff);
841 if (mTranslator != null) {
842 mTranslator.translateCanvas(canvas);
843 }
844 canvas.setScreenDensity(mAttachInfo.mScalingRequired
845 ? DisplayMetrics.DENSITY_DEVICE : 0);
846 mView.draw(canvas);
847 mResizeBitmapStartTime = SystemClock.uptimeMillis();
848 mResizeBitmapDuration = mView.getResources().getInteger(
849 com.android.internal.R.integer.config_mediumAnimTime);
850 completed = true;
851 } catch (OutOfMemoryError e) {
852 Log.w(TAG, "Not enough memory for content change anim buffer", e);
853 } finally {
854 if (!completed) {
855 mResizeBitmap = null;
856 }
857 }
858 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800859 mAttachInfo.mContentInsets.set(mPendingContentInsets);
860 host.fitSystemWindows(mAttachInfo.mContentInsets);
861 insetsChanged = true;
862 if (DEBUG_LAYOUT) Log.v(TAG, "Content insets changing to: "
863 + mAttachInfo.mContentInsets);
864 }
865 if (!mAttachInfo.mVisibleInsets.equals(mPendingVisibleInsets)) {
866 mAttachInfo.mVisibleInsets.set(mPendingVisibleInsets);
867 if (DEBUG_LAYOUT) Log.v(TAG, "Visible insets changing to: "
868 + mAttachInfo.mVisibleInsets);
869 }
870 if (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT
871 || lp.height == ViewGroup.LayoutParams.WRAP_CONTENT) {
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800872 windowSizeMayChange = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800873
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800874 DisplayMetrics packageMetrics = res.getDisplayMetrics();
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700875 desiredWindowWidth = packageMetrics.widthPixels;
876 desiredWindowHeight = packageMetrics.heightPixels;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800877 }
878 }
879
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800880 // Ask host how big it wants to be
Jeff Brownc5ed5912010-07-14 18:48:53 -0700881 if (DEBUG_ORIENTATION || DEBUG_LAYOUT) Log.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800882 "Measuring " + host + " in display " + desiredWindowWidth
883 + "x" + desiredWindowHeight + "...");
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800884
885 boolean goodMeasure = false;
886 if (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT
887 || lp.height == ViewGroup.LayoutParams.WRAP_CONTENT) {
888 // On large screens, we don't want to allow dialogs to just
889 // stretch to fill the entire width of the screen to display
890 // one line of text. First try doing the layout at a smaller
891 // size to see if it will fit.
892 final DisplayMetrics packageMetrics = res.getDisplayMetrics();
893 res.getValue(com.android.internal.R.dimen.config_prefDialogWidth, mTmpValue, true);
894 int baseSize = 0;
895 if (mTmpValue.type == TypedValue.TYPE_DIMENSION) {
896 baseSize = (int)mTmpValue.getDimension(packageMetrics);
897 }
898 if (DEBUG_DIALOG) Log.v(TAG, "Window " + mView + ": baseSize=" + baseSize);
Dianne Hackborn7d3a5bc2010-11-29 22:52:12 -0800899 if (baseSize != 0 && desiredWindowWidth > baseSize) {
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800900 childWidthMeasureSpec = getRootMeasureSpec(baseSize, lp.width);
901 childHeightMeasureSpec = getRootMeasureSpec(desiredWindowHeight, lp.height);
902 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
903 if (DEBUG_DIALOG) Log.v(TAG, "Window " + mView + ": measured ("
Dianne Hackborn189ee182010-12-02 21:48:53 -0800904 + host.getMeasuredWidth() + "," + host.getMeasuredHeight() + ")");
905 if ((host.getMeasuredWidthAndState()&View.MEASURED_STATE_TOO_SMALL) == 0) {
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800906 goodMeasure = true;
907 } else {
908 // Didn't fit in that size... try expanding a bit.
909 baseSize = (baseSize+desiredWindowWidth)/2;
910 if (DEBUG_DIALOG) Log.v(TAG, "Window " + mView + ": next baseSize="
911 + baseSize);
Dianne Hackborn189ee182010-12-02 21:48:53 -0800912 childWidthMeasureSpec = getRootMeasureSpec(baseSize, lp.width);
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800913 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
914 if (DEBUG_DIALOG) Log.v(TAG, "Window " + mView + ": measured ("
Dianne Hackborn189ee182010-12-02 21:48:53 -0800915 + host.getMeasuredWidth() + "," + host.getMeasuredHeight() + ")");
916 if ((host.getMeasuredWidthAndState()&View.MEASURED_STATE_TOO_SMALL) == 0) {
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800917 if (DEBUG_DIALOG) Log.v(TAG, "Good!");
918 goodMeasure = true;
919 }
920 }
921 }
922 }
923
924 if (!goodMeasure) {
925 childWidthMeasureSpec = getRootMeasureSpec(desiredWindowWidth, lp.width);
926 childHeightMeasureSpec = getRootMeasureSpec(desiredWindowHeight, lp.height);
927 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
Adam Powellaa0b92c2010-12-13 22:38:53 -0800928 if (mWidth != host.getMeasuredWidth() || mHeight != host.getMeasuredHeight()) {
929 windowSizeMayChange = true;
930 }
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800931 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800932
933 if (DBG) {
934 System.out.println("======================================");
935 System.out.println("performTraversals -- after measure");
936 host.debug();
937 }
938 }
939
Romain Guy6e81e572011-01-25 12:52:58 -0800940 if (attachInfo.mRecomputeGlobalAttributes && host.mAttachInfo != null) {
Joe Onorato664644d2011-01-23 17:53:23 -0800941 //Log.i(TAG, "Computing view hierarchy attributes!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800942 attachInfo.mRecomputeGlobalAttributes = false;
Joe Onorato664644d2011-01-23 17:53:23 -0800943 boolean oldScreenOn = attachInfo.mKeepScreenOn;
944 int oldVis = attachInfo.mSystemUiVisibility;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800945 attachInfo.mKeepScreenOn = false;
Joe Onorato664644d2011-01-23 17:53:23 -0800946 attachInfo.mSystemUiVisibility = 0;
947 attachInfo.mHasSystemUiListeners = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800948 host.dispatchCollectViewAttributes(0);
Joe Onorato14782f72011-01-25 19:53:17 -0800949 if (attachInfo.mKeepScreenOn != oldScreenOn
950 || attachInfo.mSystemUiVisibility != oldVis
951 || attachInfo.mHasSystemUiListeners) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800952 params = lp;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800953 }
954 }
955
956 if (mFirst || attachInfo.mViewVisibilityChanged) {
957 attachInfo.mViewVisibilityChanged = false;
958 int resizeMode = mSoftInputMode &
959 WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST;
960 // If we are in auto resize mode, then we need to determine
961 // what mode to use now.
962 if (resizeMode == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED) {
963 final int N = attachInfo.mScrollContainers.size();
964 for (int i=0; i<N; i++) {
965 if (attachInfo.mScrollContainers.get(i).isShown()) {
966 resizeMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE;
967 }
968 }
969 if (resizeMode == 0) {
970 resizeMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN;
971 }
972 if ((lp.softInputMode &
973 WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) != resizeMode) {
974 lp.softInputMode = (lp.softInputMode &
975 ~WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) |
976 resizeMode;
977 params = lp;
978 }
979 }
980 }
Romain Guy8506ab42009-06-11 17:35:47 -0700981
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800982 if (params != null && (host.mPrivateFlags & View.REQUEST_TRANSPARENT_REGIONS) != 0) {
983 if (!PixelFormat.formatHasAlpha(params.format)) {
984 params.format = PixelFormat.TRANSLUCENT;
985 }
986 }
987
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800988 boolean windowShouldResize = mLayoutRequested && windowSizeMayChange
Dianne Hackborn189ee182010-12-02 21:48:53 -0800989 && ((mWidth != host.getMeasuredWidth() || mHeight != host.getMeasuredHeight())
Romain Guy2e4f4262010-04-06 11:07:52 -0700990 || (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT &&
991 frame.width() < desiredWindowWidth && frame.width() != mWidth)
992 || (lp.height == ViewGroup.LayoutParams.WRAP_CONTENT &&
993 frame.height() < desiredWindowHeight && frame.height() != mHeight));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800994
995 final boolean computesInternalInsets =
996 attachInfo.mTreeObserver.hasComputeInternalInsetsListeners();
Romain Guy812ccbe2010-06-01 14:07:24 -0700997
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800998 boolean insetsPending = false;
999 int relayoutResult = 0;
Romain Guy812ccbe2010-06-01 14:07:24 -07001000
1001 if (mFirst || windowShouldResize || insetsChanged ||
1002 viewVisibilityChanged || params != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001003
1004 if (viewVisibility == View.VISIBLE) {
1005 // If this window is giving internal insets to the window
1006 // manager, and it is being added or changing its visibility,
1007 // then we want to first give the window manager "fake"
1008 // insets to cause it to effectively ignore the content of
1009 // the window during layout. This avoids it briefly causing
1010 // other windows to resize/move based on the raw frame of the
1011 // window, waiting until we can finish laying out this window
1012 // and get back to the window manager with the ultimately
1013 // computed insets.
Romain Guy812ccbe2010-06-01 14:07:24 -07001014 insetsPending = computesInternalInsets && (mFirst || viewVisibilityChanged);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001015 }
1016
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001017 if (mSurfaceHolder != null) {
1018 mSurfaceHolder.mSurfaceLock.lock();
1019 mDrawingAllowed = true;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001020 }
Romain Guy812ccbe2010-06-01 14:07:24 -07001021
Romain Guyc361da82010-10-25 15:29:10 -07001022 boolean hwInitialized = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001023 boolean contentInsetsChanged = false;
Romain Guy13922e02009-05-12 17:56:14 -07001024 boolean visibleInsetsChanged;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001025 boolean hadSurface = mSurface.isValid();
Romain Guy812ccbe2010-06-01 14:07:24 -07001026
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001027 try {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001028 int fl = 0;
1029 if (params != null) {
1030 fl = params.flags;
1031 if (attachInfo.mKeepScreenOn) {
1032 params.flags |= WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
1033 }
Joe Onorato14782f72011-01-25 19:53:17 -08001034 params.subtreeSystemUiVisibility = attachInfo.mSystemUiVisibility;
1035 params.hasSystemUiListeners = attachInfo.mHasSystemUiListeners
1036 || params.subtreeSystemUiVisibility != 0
1037 || params.systemUiVisibility != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001038 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001039 if (DEBUG_LAYOUT) {
Dianne Hackborn189ee182010-12-02 21:48:53 -08001040 Log.i(TAG, "host=w:" + host.getMeasuredWidth() + ", h:" +
1041 host.getMeasuredHeight() + ", params=" + params);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001042 }
Romain Guy2a83f002011-01-18 18:28:21 -08001043
1044 final int surfaceGenerationId = mSurface.getGenerationId();
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001045 relayoutResult = relayoutWindow(params, viewVisibility, insetsPending);
1046
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001047 if (params != null) {
1048 params.flags = fl;
1049 }
1050
1051 if (DEBUG_LAYOUT) Log.v(TAG, "relayout: frame=" + frame.toShortString()
1052 + " content=" + mPendingContentInsets.toShortString()
1053 + " visible=" + mPendingVisibleInsets.toShortString()
1054 + " surface=" + mSurface);
Romain Guy8506ab42009-06-11 17:35:47 -07001055
Dianne Hackborn694f79b2010-03-17 19:44:59 -07001056 if (mPendingConfiguration.seq != 0) {
1057 if (DEBUG_CONFIGURATION) Log.v(TAG, "Visible with new config: "
1058 + mPendingConfiguration);
1059 updateConfiguration(mPendingConfiguration, !mFirst);
1060 mPendingConfiguration.seq = 0;
1061 }
1062
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001063 contentInsetsChanged = !mPendingContentInsets.equals(
1064 mAttachInfo.mContentInsets);
1065 visibleInsetsChanged = !mPendingVisibleInsets.equals(
1066 mAttachInfo.mVisibleInsets);
1067 if (contentInsetsChanged) {
1068 mAttachInfo.mContentInsets.set(mPendingContentInsets);
1069 host.fitSystemWindows(mAttachInfo.mContentInsets);
1070 if (DEBUG_LAYOUT) Log.v(TAG, "Content insets changing to: "
1071 + mAttachInfo.mContentInsets);
1072 }
1073 if (visibleInsetsChanged) {
1074 mAttachInfo.mVisibleInsets.set(mPendingVisibleInsets);
1075 if (DEBUG_LAYOUT) Log.v(TAG, "Visible insets changing to: "
1076 + mAttachInfo.mVisibleInsets);
1077 }
1078
1079 if (!hadSurface) {
1080 if (mSurface.isValid()) {
1081 // If we are creating a new surface, then we need to
1082 // completely redraw it. Also, when we get to the
1083 // point of drawing it we will hold off and schedule
1084 // a new traversal instead. This is so we can tell the
1085 // window manager about all of the windows being displayed
1086 // before actually drawing them, so it can display then
1087 // all at once.
1088 newSurface = true;
1089 fullRedrawNeeded = true;
Jack Palevich61a6e682009-10-09 17:37:50 -07001090 mPreviousTransparentRegion.setEmpty();
Romain Guy8506ab42009-06-11 17:35:47 -07001091
Romain Guyb051e892010-09-28 19:09:36 -07001092 if (mAttachInfo.mHardwareRenderer != null) {
Dianne Hackborn64825172011-03-02 21:32:58 -08001093 try {
1094 hwInitialized = mAttachInfo.mHardwareRenderer.initialize(mHolder);
1095 } catch (Surface.OutOfResourcesException e) {
1096 Log.e(TAG, "OutOfResourcesException initializing HW surface", e);
1097 try {
1098 if (!sWindowSession.outOfMemory(mWindow)) {
1099 Slog.w(TAG, "No processes killed for memory; killing self");
1100 Process.killProcess(Process.myPid());
1101 }
1102 } catch (RemoteException ex) {
1103 }
1104 mLayoutRequested = true; // ask wm for a new surface next time.
1105 return;
1106 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001107 }
1108 }
1109 } else if (!mSurface.isValid()) {
1110 // If the surface has been removed, then reset the scroll
1111 // positions.
1112 mLastScrolledFocus = null;
1113 mScrollY = mCurScrollY = 0;
1114 if (mScroller != null) {
1115 mScroller.abortAnimation();
1116 }
Dianne Hackborn0f761d62010-11-30 22:06:10 -08001117 disposeResizeBitmap();
Romain Guy2a83f002011-01-18 18:28:21 -08001118 } else if (surfaceGenerationId != mSurface.getGenerationId() &&
1119 mSurfaceHolder == null && mAttachInfo.mHardwareRenderer != null) {
Romain Guy7d7b5492011-01-24 16:33:45 -08001120 fullRedrawNeeded = true;
Dianne Hackborn64825172011-03-02 21:32:58 -08001121 try {
1122 mAttachInfo.mHardwareRenderer.updateSurface(mHolder);
1123 } catch (Surface.OutOfResourcesException e) {
1124 Log.e(TAG, "OutOfResourcesException updating HW surface", e);
1125 try {
1126 if (!sWindowSession.outOfMemory(mWindow)) {
1127 Slog.w(TAG, "No processes killed for memory; killing self");
1128 Process.killProcess(Process.myPid());
1129 }
1130 } catch (RemoteException ex) {
1131 }
1132 mLayoutRequested = true; // ask wm for a new surface next time.
1133 return;
1134 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001135 }
1136 } catch (RemoteException e) {
1137 }
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001138
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001139 if (DEBUG_ORIENTATION) Log.v(
Jeff Brownc5ed5912010-07-14 18:48:53 -07001140 TAG, "Relayout returned: frame=" + frame + ", surface=" + mSurface);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001141
1142 attachInfo.mWindowLeft = frame.left;
1143 attachInfo.mWindowTop = frame.top;
1144
1145 // !!FIXME!! This next section handles the case where we did not get the
1146 // window size we asked for. We should avoid this by getting a maximum size from
1147 // the window session beforehand.
1148 mWidth = frame.width();
1149 mHeight = frame.height();
1150
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001151 if (mSurfaceHolder != null) {
1152 // The app owns the surface; tell it about what is going on.
1153 if (mSurface.isValid()) {
1154 // XXX .copyFrom() doesn't work!
1155 //mSurfaceHolder.mSurface.copyFrom(mSurface);
1156 mSurfaceHolder.mSurface = mSurface;
1157 }
Jeff Brown30bc34f2011-01-25 12:56:56 -08001158 mSurfaceHolder.setSurfaceFrameSize(mWidth, mHeight);
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001159 mSurfaceHolder.mSurfaceLock.unlock();
1160 if (mSurface.isValid()) {
1161 if (!hadSurface) {
1162 mSurfaceHolder.ungetCallbacks();
1163
1164 mIsCreating = true;
1165 mSurfaceHolderCallback.surfaceCreated(mSurfaceHolder);
1166 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
1167 if (callbacks != null) {
1168 for (SurfaceHolder.Callback c : callbacks) {
1169 c.surfaceCreated(mSurfaceHolder);
1170 }
1171 }
1172 surfaceChanged = true;
1173 }
1174 if (surfaceChanged) {
1175 mSurfaceHolderCallback.surfaceChanged(mSurfaceHolder,
1176 lp.format, mWidth, mHeight);
1177 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
1178 if (callbacks != null) {
1179 for (SurfaceHolder.Callback c : callbacks) {
1180 c.surfaceChanged(mSurfaceHolder, lp.format,
1181 mWidth, mHeight);
1182 }
1183 }
1184 }
1185 mIsCreating = false;
1186 } else if (hadSurface) {
1187 mSurfaceHolder.ungetCallbacks();
1188 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
1189 mSurfaceHolderCallback.surfaceDestroyed(mSurfaceHolder);
1190 if (callbacks != null) {
1191 for (SurfaceHolder.Callback c : callbacks) {
1192 c.surfaceDestroyed(mSurfaceHolder);
1193 }
1194 }
1195 mSurfaceHolder.mSurfaceLock.lock();
Jozef BABJAK93c5b6a2011-02-22 09:33:19 +01001196 try {
1197 mSurfaceHolder.mSurface = new Surface();
1198 } finally {
1199 mSurfaceHolder.mSurfaceLock.unlock();
1200 }
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001201 }
1202 }
Romain Guy53389bd2010-09-07 17:16:32 -07001203
Romain Guy6b5108b2011-01-04 16:11:10 -08001204 if (hwInitialized || ((windowShouldResize || params != null) &&
Romain Guydbf78bd2010-12-07 17:04:03 -08001205 mAttachInfo.mHardwareRenderer != null &&
1206 mAttachInfo.mHardwareRenderer.isEnabled())) {
Romain Guyb051e892010-09-28 19:09:36 -07001207 mAttachInfo.mHardwareRenderer.setup(mWidth, mHeight);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001208 }
1209
Dianne Hackbornce418e62011-03-01 14:31:38 -08001210 if (!mStopped) {
1211 boolean focusChangedDueToTouchMode = ensureTouchModeLocally(
1212 (relayoutResult&WindowManagerImpl.RELAYOUT_IN_TOUCH_MODE) != 0);
1213 if (focusChangedDueToTouchMode || mWidth != host.getMeasuredWidth()
1214 || mHeight != host.getMeasuredHeight() || contentInsetsChanged) {
1215 childWidthMeasureSpec = getRootMeasureSpec(mWidth, lp.width);
1216 childHeightMeasureSpec = getRootMeasureSpec(mHeight, lp.height);
1217
1218 if (DEBUG_LAYOUT) Log.v(TAG, "Ooops, something changed! mWidth="
1219 + mWidth + " measuredWidth=" + host.getMeasuredWidth()
1220 + " mHeight=" + mHeight
1221 + " measuredHeight=" + host.getMeasuredHeight()
1222 + " coveredInsetsChanged=" + contentInsetsChanged);
1223
1224 // Ask host how big it wants to be
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001225 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
Dianne Hackbornce418e62011-03-01 14:31:38 -08001226
1227 // Implementation of weights from WindowManager.LayoutParams
1228 // We just grow the dimensions as needed and re-measure if
1229 // needs be
1230 int width = host.getMeasuredWidth();
1231 int height = host.getMeasuredHeight();
1232 boolean measureAgain = false;
1233
1234 if (lp.horizontalWeight > 0.0f) {
1235 width += (int) ((mWidth - width) * lp.horizontalWeight);
1236 childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(width,
1237 MeasureSpec.EXACTLY);
1238 measureAgain = true;
1239 }
1240 if (lp.verticalWeight > 0.0f) {
1241 height += (int) ((mHeight - height) * lp.verticalWeight);
1242 childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(height,
1243 MeasureSpec.EXACTLY);
1244 measureAgain = true;
1245 }
1246
1247 if (measureAgain) {
1248 if (DEBUG_LAYOUT) Log.v(TAG,
1249 "And hey let's measure once more: width=" + width
1250 + " height=" + height);
1251 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
1252 }
1253
1254 mLayoutRequested = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001255 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001256 }
1257 }
1258
Dianne Hackbornce418e62011-03-01 14:31:38 -08001259 final boolean didLayout = mLayoutRequested && !mStopped;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001260 boolean triggerGlobalLayoutListener = didLayout
1261 || attachInfo.mRecomputeGlobalAttributes;
1262 if (didLayout) {
1263 mLayoutRequested = false;
1264 mScrollMayChange = true;
1265 if (DEBUG_ORIENTATION || DEBUG_LAYOUT) Log.v(
Jeff Brownc5ed5912010-07-14 18:48:53 -07001266 TAG, "Laying out " + host + " to (" +
Dianne Hackborn189ee182010-12-02 21:48:53 -08001267 host.getMeasuredWidth() + ", " + host.getMeasuredHeight() + ")");
Romain Guy13922e02009-05-12 17:56:14 -07001268 long startTime = 0L;
Romain Guy5429e1d2010-09-07 12:38:00 -07001269 if (ViewDebug.DEBUG_PROFILE_LAYOUT) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001270 startTime = SystemClock.elapsedRealtime();
1271 }
Dianne Hackborn189ee182010-12-02 21:48:53 -08001272 host.layout(0, 0, host.getMeasuredWidth(), host.getMeasuredHeight());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001273
Joe Onorato43a17652011-04-06 19:22:23 -07001274 if (false && ViewDebug.consistencyCheckEnabled) {
Romain Guy13922e02009-05-12 17:56:14 -07001275 if (!host.dispatchConsistencyCheck(ViewDebug.CONSISTENCY_LAYOUT)) {
1276 throw new IllegalStateException("The view hierarchy is an inconsistent state,"
1277 + "please refer to the logs with the tag "
1278 + ViewDebug.CONSISTENCY_LOG_TAG + " for more infomation.");
1279 }
1280 }
1281
Romain Guy5429e1d2010-09-07 12:38:00 -07001282 if (ViewDebug.DEBUG_PROFILE_LAYOUT) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001283 EventLog.writeEvent(60001, SystemClock.elapsedRealtime() - startTime);
1284 }
1285
1286 // By this point all views have been sized and positionned
1287 // We can compute the transparent area
1288
1289 if ((host.mPrivateFlags & View.REQUEST_TRANSPARENT_REGIONS) != 0) {
1290 // start out transparent
1291 // TODO: AVOID THAT CALL BY CACHING THE RESULT?
1292 host.getLocationInWindow(mTmpLocation);
1293 mTransparentRegion.set(mTmpLocation[0], mTmpLocation[1],
1294 mTmpLocation[0] + host.mRight - host.mLeft,
1295 mTmpLocation[1] + host.mBottom - host.mTop);
1296
1297 host.gatherTransparentRegion(mTransparentRegion);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001298 if (mTranslator != null) {
1299 mTranslator.translateRegionInWindowToScreen(mTransparentRegion);
1300 }
1301
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001302 if (!mTransparentRegion.equals(mPreviousTransparentRegion)) {
1303 mPreviousTransparentRegion.set(mTransparentRegion);
1304 // reconfigure window manager
1305 try {
1306 sWindowSession.setTransparentRegion(mWindow, mTransparentRegion);
1307 } catch (RemoteException e) {
1308 }
1309 }
1310 }
1311
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001312 if (DBG) {
1313 System.out.println("======================================");
1314 System.out.println("performTraversals -- after setFrame");
1315 host.debug();
1316 }
1317 }
1318
1319 if (triggerGlobalLayoutListener) {
1320 attachInfo.mRecomputeGlobalAttributes = false;
1321 attachInfo.mTreeObserver.dispatchOnGlobalLayout();
1322 }
1323
1324 if (computesInternalInsets) {
Jeff Brownfbf09772011-01-16 14:06:57 -08001325 // Clear the original insets.
1326 final ViewTreeObserver.InternalInsetsInfo insets = attachInfo.mGivenInternalInsets;
1327 insets.reset();
1328
1329 // Compute new insets in place.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001330 attachInfo.mTreeObserver.dispatchOnComputeInternalInsets(insets);
Jeff Brownfbf09772011-01-16 14:06:57 -08001331
1332 // Tell the window manager.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001333 if (insetsPending || !mLastGivenInsets.equals(insets)) {
1334 mLastGivenInsets.set(insets);
Jeff Brownfbf09772011-01-16 14:06:57 -08001335
1336 // Translate insets to screen coordinates if needed.
1337 final Rect contentInsets;
1338 final Rect visibleInsets;
1339 final Region touchableRegion;
1340 if (mTranslator != null) {
1341 contentInsets = mTranslator.getTranslatedContentInsets(insets.contentInsets);
1342 visibleInsets = mTranslator.getTranslatedVisibleInsets(insets.visibleInsets);
1343 touchableRegion = mTranslator.getTranslatedTouchableArea(insets.touchableRegion);
1344 } else {
1345 contentInsets = insets.contentInsets;
1346 visibleInsets = insets.visibleInsets;
1347 touchableRegion = insets.touchableRegion;
1348 }
1349
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001350 try {
1351 sWindowSession.setInsets(mWindow, insets.mTouchableInsets,
Jeff Brownfbf09772011-01-16 14:06:57 -08001352 contentInsets, visibleInsets, touchableRegion);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001353 } catch (RemoteException e) {
1354 }
1355 }
1356 }
Romain Guy8506ab42009-06-11 17:35:47 -07001357
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001358 if (mFirst) {
1359 // handle first focus request
1360 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: mView.hasFocus()="
1361 + mView.hasFocus());
1362 if (mView != null) {
1363 if (!mView.hasFocus()) {
1364 mView.requestFocus(View.FOCUS_FORWARD);
1365 mFocusedView = mRealFocusedView = mView.findFocus();
1366 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: requested focused view="
1367 + mFocusedView);
1368 } else {
1369 mRealFocusedView = mView.findFocus();
1370 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: existing focused view="
1371 + mRealFocusedView);
1372 }
1373 }
1374 }
1375
1376 mFirst = false;
1377 mWillDrawSoon = false;
1378 mNewSurfaceNeeded = false;
1379 mViewVisibility = viewVisibility;
1380
1381 if (mAttachInfo.mHasWindowFocus) {
1382 final boolean imTarget = WindowManager.LayoutParams
1383 .mayUseInputMethod(mWindowAttributes.flags);
1384 if (imTarget != mLastWasImTarget) {
1385 mLastWasImTarget = imTarget;
1386 InputMethodManager imm = InputMethodManager.peekInstance();
1387 if (imm != null && imTarget) {
1388 imm.startGettingWindowFocus(mView);
1389 imm.onWindowFocus(mView, mView.findFocus(),
1390 mWindowAttributes.softInputMode,
1391 !mHasHadWindowFocus, mWindowAttributes.flags);
1392 }
1393 }
1394 }
Romain Guy8506ab42009-06-11 17:35:47 -07001395
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001396 boolean cancelDraw = attachInfo.mTreeObserver.dispatchOnPreDraw();
1397
1398 if (!cancelDraw && !newSurface) {
1399 mFullRedrawNeeded = false;
Jeff Brown4e91a182011-04-07 11:38:09 -07001400
1401 final long drawStartTime;
1402 if (ViewDebug.DEBUG_LATENCY) {
1403 drawStartTime = System.nanoTime();
1404 }
1405
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001406 draw(fullRedrawNeeded);
1407
Jeff Brown4e91a182011-04-07 11:38:09 -07001408 if (ViewDebug.DEBUG_LATENCY) {
1409 mLastDrawDurationNanos = System.nanoTime() - drawStartTime;
1410 }
1411
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001412 if ((relayoutResult&WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0
1413 || mReportNextDraw) {
1414 if (LOCAL_LOGV) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001415 Log.v(TAG, "FINISHED DRAWING: " + mWindowAttributes.getTitle());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001416 }
1417 mReportNextDraw = false;
Dianne Hackbornd76b67c2010-07-13 17:48:30 -07001418 if (mSurfaceHolder != null && mSurface.isValid()) {
1419 mSurfaceHolderCallback.surfaceRedrawNeeded(mSurfaceHolder);
1420 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
1421 if (callbacks != null) {
1422 for (SurfaceHolder.Callback c : callbacks) {
1423 if (c instanceof SurfaceHolder.Callback2) {
1424 ((SurfaceHolder.Callback2)c).surfaceRedrawNeeded(
1425 mSurfaceHolder);
1426 }
1427 }
1428 }
1429 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001430 try {
1431 sWindowSession.finishDrawing(mWindow);
1432 } catch (RemoteException e) {
1433 }
1434 }
1435 } else {
1436 // We were supposed to report when we are done drawing. Since we canceled the
1437 // draw, remember it here.
1438 if ((relayoutResult&WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0) {
1439 mReportNextDraw = true;
1440 }
1441 if (fullRedrawNeeded) {
1442 mFullRedrawNeeded = true;
1443 }
1444 // Try again
1445 scheduleTraversals();
1446 }
1447 }
1448
1449 public void requestTransparentRegion(View child) {
1450 // the test below should not fail unless someone is messing with us
1451 checkThread();
1452 if (mView == child) {
1453 mView.mPrivateFlags |= View.REQUEST_TRANSPARENT_REGIONS;
1454 // Need to make sure we re-evaluate the window attributes next
1455 // time around, to ensure the window has the correct format.
1456 mWindowAttributesChanged = true;
Mathias Agopian1bd80ad2010-11-04 17:13:39 -07001457 requestLayout();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001458 }
1459 }
1460
1461 /**
1462 * Figures out the measure spec for the root view in a window based on it's
1463 * layout params.
1464 *
1465 * @param windowSize
1466 * The available width or height of the window
1467 *
1468 * @param rootDimension
1469 * The layout params for one dimension (width or height) of the
1470 * window.
1471 *
1472 * @return The measure spec to use to measure the root view.
1473 */
1474 private int getRootMeasureSpec(int windowSize, int rootDimension) {
1475 int measureSpec;
1476 switch (rootDimension) {
1477
Romain Guy980a9382010-01-08 15:06:28 -08001478 case ViewGroup.LayoutParams.MATCH_PARENT:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001479 // Window can't resize. Force root view to be windowSize.
1480 measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.EXACTLY);
1481 break;
1482 case ViewGroup.LayoutParams.WRAP_CONTENT:
1483 // Window can resize. Set max size for root view.
1484 measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.AT_MOST);
1485 break;
1486 default:
1487 // Window wants to be an exact size. Force root view to be that size.
1488 measureSpec = MeasureSpec.makeMeasureSpec(rootDimension, MeasureSpec.EXACTLY);
1489 break;
1490 }
1491 return measureSpec;
1492 }
1493
Dianne Hackborn0f761d62010-11-30 22:06:10 -08001494 int mHardwareYOffset;
1495 int mResizeAlpha;
1496 final Paint mResizePaint = new Paint();
1497
1498 public void onHardwarePreDraw(Canvas canvas) {
1499 canvas.translate(0, -mHardwareYOffset);
1500 }
1501
1502 public void onHardwarePostDraw(Canvas canvas) {
1503 if (mResizeBitmap != null) {
1504 canvas.translate(0, mHardwareYOffset);
1505 mResizePaint.setAlpha(mResizeAlpha);
1506 canvas.drawBitmap(mResizeBitmap, 0, 0, mResizePaint);
1507 }
1508 }
1509
Chet Haaseed30fd82011-04-22 16:18:45 -07001510 /**
1511 * @hide
1512 */
1513 void outputDisplayList(View view) {
1514 if (mAttachInfo != null && mAttachInfo.mHardwareCanvas != null) {
1515
1516 HardwareCanvas canvas = (HardwareCanvas) mAttachInfo.mHardwareCanvas;
1517 DisplayList displayList = view.getDisplayList();
1518 if (displayList != null) {
1519 canvas.outputDisplayList(displayList);
1520 }
1521 }
1522 }
1523
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001524 private void draw(boolean fullRedrawNeeded) {
1525 Surface surface = mSurface;
1526 if (surface == null || !surface.isValid()) {
1527 return;
1528 }
1529
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001530 if (!sFirstDrawComplete) {
1531 synchronized (sFirstDrawHandlers) {
1532 sFirstDrawComplete = true;
Romain Guy812ccbe2010-06-01 14:07:24 -07001533 final int count = sFirstDrawHandlers.size();
1534 for (int i = 0; i< count; i++) {
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001535 post(sFirstDrawHandlers.get(i));
1536 }
1537 }
1538 }
1539
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001540 scrollToRectOrFocus(null, false);
1541
1542 if (mAttachInfo.mViewScrollChanged) {
1543 mAttachInfo.mViewScrollChanged = false;
1544 mAttachInfo.mTreeObserver.dispatchOnScrollChanged();
1545 }
Romain Guy8506ab42009-06-11 17:35:47 -07001546
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001547 int yoff;
Dianne Hackborn0f761d62010-11-30 22:06:10 -08001548 boolean animating = mScroller != null && mScroller.computeScrollOffset();
1549 if (animating) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001550 yoff = mScroller.getCurrY();
1551 } else {
1552 yoff = mScrollY;
1553 }
1554 if (mCurScrollY != yoff) {
1555 mCurScrollY = yoff;
1556 fullRedrawNeeded = true;
1557 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001558 float appScale = mAttachInfo.mApplicationScale;
1559 boolean scalingRequired = mAttachInfo.mScalingRequired;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001560
Dianne Hackborn0f761d62010-11-30 22:06:10 -08001561 int resizeAlpha = 0;
1562 if (mResizeBitmap != null) {
1563 long deltaTime = SystemClock.uptimeMillis() - mResizeBitmapStartTime;
1564 if (deltaTime < mResizeBitmapDuration) {
1565 float amt = deltaTime/(float)mResizeBitmapDuration;
1566 amt = mResizeInterpolator.getInterpolation(amt);
1567 animating = true;
1568 resizeAlpha = 255 - (int)(amt*255);
1569 } else {
1570 disposeResizeBitmap();
1571 }
1572 }
1573
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001574 Rect dirty = mDirty;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001575 if (mSurfaceHolder != null) {
1576 // The app owns the surface, we won't draw.
1577 dirty.setEmpty();
Dianne Hackborn0f761d62010-11-30 22:06:10 -08001578 if (animating) {
1579 if (mScroller != null) {
1580 mScroller.abortAnimation();
1581 }
1582 disposeResizeBitmap();
1583 }
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001584 return;
1585 }
Romain Guy58ef7fb2010-09-13 12:52:37 -07001586
1587 if (fullRedrawNeeded) {
1588 mAttachInfo.mIgnoreDirtyState = true;
1589 dirty.union(0, 0, (int) (mWidth * appScale + 0.5f), (int) (mHeight * appScale + 0.5f));
1590 }
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001591
Romain Guyb051e892010-09-28 19:09:36 -07001592 if (mAttachInfo.mHardwareRenderer != null && mAttachInfo.mHardwareRenderer.isEnabled()) {
Romain Guyfd507262010-10-10 15:42:49 -07001593 if (!dirty.isEmpty() || mIsAnimating) {
Romain Guy101e2ae2010-10-11 12:41:21 -07001594 mIsAnimating = false;
Dianne Hackborn0f761d62010-11-30 22:06:10 -08001595 mHardwareYOffset = yoff;
1596 mResizeAlpha = resizeAlpha;
Romain Guy7d7b5492011-01-24 16:33:45 -08001597
1598 mCurrentDirty.set(dirty);
1599 mCurrentDirty.union(mPreviousDirty);
1600 mPreviousDirty.set(dirty);
1601 dirty.setEmpty();
1602
Romain Guyf90f8172011-01-25 22:53:24 -08001603 Rect currentDirty = mCurrentDirty;
1604 if (animating) {
1605 currentDirty = null;
1606 }
1607
1608 mAttachInfo.mHardwareRenderer.draw(mView, mAttachInfo, this, currentDirty);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001609 }
Romain Guy812ccbe2010-06-01 14:07:24 -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 }
Romain Guy812ccbe2010-06-01 14:07:24 -07001615
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001616 return;
1617 }
1618
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001619 if (DEBUG_ORIENTATION || DEBUG_DRAW) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001620 Log.v(TAG, "Draw " + mView + "/"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001621 + mWindowAttributes.getTitle()
1622 + ": dirty={" + dirty.left + "," + dirty.top
1623 + "," + dirty.right + "," + dirty.bottom + "} surface="
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001624 + surface + " surface.isValid()=" + surface.isValid() + ", appScale:" +
1625 appScale + ", width=" + mWidth + ", height=" + mHeight);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001626 }
1627
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001628 if (!dirty.isEmpty() || mIsAnimating) {
1629 Canvas canvas;
1630 try {
1631 int left = dirty.left;
1632 int top = dirty.top;
1633 int right = dirty.right;
1634 int bottom = dirty.bottom;
Romain Guyfea12b82011-01-27 15:36:40 -08001635
Jeff Brown4e91a182011-04-07 11:38:09 -07001636 final long lockCanvasStartTime;
1637 if (ViewDebug.DEBUG_LATENCY) {
1638 lockCanvasStartTime = System.nanoTime();
1639 }
1640
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001641 canvas = surface.lockCanvas(dirty);
Romain Guy5bcdff42009-05-14 21:27:18 -07001642
Jeff Brown4e91a182011-04-07 11:38:09 -07001643 if (ViewDebug.DEBUG_LATENCY) {
1644 long now = System.nanoTime();
1645 Log.d(TAG, "Latency: Spent "
1646 + ((now - lockCanvasStartTime) * 0.000001f)
1647 + "ms waiting for surface.lockCanvas()");
1648 }
1649
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001650 if (left != dirty.left || top != dirty.top || right != dirty.right ||
1651 bottom != dirty.bottom) {
1652 mAttachInfo.mIgnoreDirtyState = true;
1653 }
1654
1655 // TODO: Do this in native
1656 canvas.setDensity(mDensity);
1657 } catch (Surface.OutOfResourcesException e) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001658 Log.e(TAG, "OutOfResourcesException locking surface", e);
Dianne Hackborn64825172011-03-02 21:32:58 -08001659 try {
1660 if (!sWindowSession.outOfMemory(mWindow)) {
1661 Slog.w(TAG, "No processes killed for memory; killing self");
1662 Process.killProcess(Process.myPid());
1663 }
1664 } catch (RemoteException ex) {
1665 }
Dianne Hackborn83a6f452011-01-27 17:17:19 -08001666 mLayoutRequested = true; // ask wm for a new surface next time.
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001667 return;
1668 } catch (IllegalArgumentException e) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001669 Log.e(TAG, "IllegalArgumentException locking surface", e);
Dianne Hackborndb773c52011-03-04 16:43:41 -08001670 // Don't assume this is due to out of memory, it could be
1671 // something else, and if it is something else then we could
1672 // kill stuff (or ourself) for no reason.
Dianne Hackborn83a6f452011-01-27 17:17:19 -08001673 mLayoutRequested = true; // ask wm for a new surface next time.
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001674 return;
Romain Guy5bcdff42009-05-14 21:27:18 -07001675 }
1676
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001677 try {
1678 if (!dirty.isEmpty() || mIsAnimating) {
1679 long startTime = 0L;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001680
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001681 if (DEBUG_ORIENTATION || DEBUG_DRAW) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001682 Log.v(TAG, "Surface " + surface + " drawing to bitmap w="
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001683 + canvas.getWidth() + ", h=" + canvas.getHeight());
1684 //canvas.drawARGB(255, 255, 0, 0);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001685 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001686
Romain Guy5429e1d2010-09-07 12:38:00 -07001687 if (ViewDebug.DEBUG_PROFILE_DRAWING) {
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001688 startTime = SystemClock.elapsedRealtime();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001689 }
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001690
1691 // If this bitmap's format includes an alpha channel, we
1692 // need to clear it before drawing so that the child will
1693 // properly re-composite its drawing on a transparent
1694 // background. This automatically respects the clip/dirty region
1695 // or
1696 // If we are applying an offset, we need to clear the area
1697 // where the offset doesn't appear to avoid having garbage
1698 // left in the blank areas.
1699 if (!canvas.isOpaque() || yoff != 0) {
1700 canvas.drawColor(0, PorterDuff.Mode.CLEAR);
1701 }
1702
1703 dirty.setEmpty();
1704 mIsAnimating = false;
1705 mAttachInfo.mDrawingTime = SystemClock.uptimeMillis();
1706 mView.mPrivateFlags |= View.DRAWN;
1707
1708 if (DEBUG_DRAW) {
1709 Context cxt = mView.getContext();
1710 Log.i(TAG, "Drawing: package:" + cxt.getPackageName() +
1711 ", metrics=" + cxt.getResources().getDisplayMetrics() +
1712 ", compatibilityInfo=" + cxt.getResources().getCompatibilityInfo());
1713 }
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001714 try {
1715 canvas.translate(0, -yoff);
1716 if (mTranslator != null) {
1717 mTranslator.translateCanvas(canvas);
1718 }
1719 canvas.setScreenDensity(scalingRequired
1720 ? DisplayMetrics.DENSITY_DEVICE : 0);
1721 mView.draw(canvas);
1722 } finally {
1723 mAttachInfo.mIgnoreDirtyState = false;
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001724 }
1725
Joe Onorato43a17652011-04-06 19:22:23 -07001726 if (false && ViewDebug.consistencyCheckEnabled) {
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001727 mView.dispatchConsistencyCheck(ViewDebug.CONSISTENCY_DRAWING);
1728 }
1729
Romain Guy5429e1d2010-09-07 12:38:00 -07001730 if (SHOW_FPS || ViewDebug.DEBUG_SHOW_FPS) {
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001731 int now = (int)SystemClock.elapsedRealtime();
1732 if (sDrawTime != 0) {
1733 nativeShowFPS(canvas, now - sDrawTime);
1734 }
1735 sDrawTime = now;
1736 }
1737
Romain Guy5429e1d2010-09-07 12:38:00 -07001738 if (ViewDebug.DEBUG_PROFILE_DRAWING) {
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001739 EventLog.writeEvent(60000, SystemClock.elapsedRealtime() - startTime);
1740 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001741 }
1742
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001743 } finally {
1744 surface.unlockCanvasAndPost(canvas);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001745 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001746 }
1747
1748 if (LOCAL_LOGV) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001749 Log.v(TAG, "Surface " + surface + " unlockCanvasAndPost");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001750 }
Romain Guy8506ab42009-06-11 17:35:47 -07001751
Dianne Hackborn0f761d62010-11-30 22:06:10 -08001752 if (animating) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001753 mFullRedrawNeeded = true;
1754 scheduleTraversals();
1755 }
1756 }
1757
1758 boolean scrollToRectOrFocus(Rect rectangle, boolean immediate) {
1759 final View.AttachInfo attachInfo = mAttachInfo;
1760 final Rect ci = attachInfo.mContentInsets;
1761 final Rect vi = attachInfo.mVisibleInsets;
1762 int scrollY = 0;
1763 boolean handled = false;
Romain Guy8506ab42009-06-11 17:35:47 -07001764
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001765 if (vi.left > ci.left || vi.top > ci.top
1766 || vi.right > ci.right || vi.bottom > ci.bottom) {
1767 // We'll assume that we aren't going to change the scroll
1768 // offset, since we want to avoid that unless it is actually
1769 // going to make the focus visible... otherwise we scroll
1770 // all over the place.
1771 scrollY = mScrollY;
1772 // We can be called for two different situations: during a draw,
1773 // to update the scroll position if the focus has changed (in which
1774 // case 'rectangle' is null), or in response to a
1775 // requestChildRectangleOnScreen() call (in which case 'rectangle'
1776 // is non-null and we just want to scroll to whatever that
1777 // rectangle is).
1778 View focus = mRealFocusedView;
Romain Guye8b16522009-07-14 13:06:42 -07001779
1780 // When in touch mode, focus points to the previously focused view,
1781 // which may have been removed from the view hierarchy. The following
Joe Onoratob71193b2009-11-24 18:34:42 -05001782 // line checks whether the view is still in our hierarchy.
1783 if (focus == null || focus.mAttachInfo != mAttachInfo) {
Romain Guye8b16522009-07-14 13:06:42 -07001784 mRealFocusedView = null;
1785 return false;
1786 }
1787
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001788 if (focus != mLastScrolledFocus) {
1789 // If the focus has changed, then ignore any requests to scroll
1790 // to a rectangle; first we want to make sure the entire focus
1791 // view is visible.
1792 rectangle = null;
1793 }
1794 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Eval scroll: focus=" + focus
1795 + " rectangle=" + rectangle + " ci=" + ci
1796 + " vi=" + vi);
1797 if (focus == mLastScrolledFocus && !mScrollMayChange
1798 && rectangle == null) {
1799 // Optimization: if the focus hasn't changed since last
1800 // time, and no layout has happened, then just leave things
1801 // as they are.
1802 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Keeping scroll y="
1803 + mScrollY + " vi=" + vi.toShortString());
1804 } else if (focus != null) {
1805 // We need to determine if the currently focused view is
1806 // within the visible part of the window and, if not, apply
1807 // a pan so it can be seen.
1808 mLastScrolledFocus = focus;
1809 mScrollMayChange = false;
1810 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Need to scroll?");
1811 // Try to find the rectangle from the focus view.
1812 if (focus.getGlobalVisibleRect(mVisRect, null)) {
1813 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Root w="
1814 + mView.getWidth() + " h=" + mView.getHeight()
1815 + " ci=" + ci.toShortString()
1816 + " vi=" + vi.toShortString());
1817 if (rectangle == null) {
1818 focus.getFocusedRect(mTempRect);
1819 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Focus " + focus
1820 + ": focusRect=" + mTempRect.toShortString());
Dianne Hackborn1c6a8942010-03-23 16:34:20 -07001821 if (mView instanceof ViewGroup) {
1822 ((ViewGroup) mView).offsetDescendantRectToMyCoords(
1823 focus, mTempRect);
1824 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001825 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1826 "Focus in window: focusRect="
1827 + mTempRect.toShortString()
1828 + " visRect=" + mVisRect.toShortString());
1829 } else {
1830 mTempRect.set(rectangle);
1831 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1832 "Request scroll to rect: "
1833 + mTempRect.toShortString()
1834 + " visRect=" + mVisRect.toShortString());
1835 }
1836 if (mTempRect.intersect(mVisRect)) {
1837 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1838 "Focus window visible rect: "
1839 + mTempRect.toShortString());
1840 if (mTempRect.height() >
1841 (mView.getHeight()-vi.top-vi.bottom)) {
1842 // If the focus simply is not going to fit, then
1843 // best is probably just to leave things as-is.
1844 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1845 "Too tall; leaving scrollY=" + scrollY);
1846 } else if ((mTempRect.top-scrollY) < vi.top) {
1847 scrollY -= vi.top - (mTempRect.top-scrollY);
1848 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1849 "Top covered; scrollY=" + scrollY);
1850 } else if ((mTempRect.bottom-scrollY)
1851 > (mView.getHeight()-vi.bottom)) {
1852 scrollY += (mTempRect.bottom-scrollY)
1853 - (mView.getHeight()-vi.bottom);
1854 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1855 "Bottom covered; scrollY=" + scrollY);
1856 }
1857 handled = true;
1858 }
1859 }
1860 }
1861 }
Romain Guy8506ab42009-06-11 17:35:47 -07001862
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001863 if (scrollY != mScrollY) {
1864 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Pan scroll changed: old="
1865 + mScrollY + " , new=" + scrollY);
Dianne Hackborn0f761d62010-11-30 22:06:10 -08001866 if (!immediate && mResizeBitmap == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001867 if (mScroller == null) {
1868 mScroller = new Scroller(mView.getContext());
1869 }
1870 mScroller.startScroll(0, mScrollY, 0, scrollY-mScrollY);
1871 } else if (mScroller != null) {
1872 mScroller.abortAnimation();
1873 }
1874 mScrollY = scrollY;
1875 }
Romain Guy8506ab42009-06-11 17:35:47 -07001876
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001877 return handled;
1878 }
Romain Guy8506ab42009-06-11 17:35:47 -07001879
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001880 public void requestChildFocus(View child, View focused) {
1881 checkThread();
1882 if (mFocusedView != focused) {
1883 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(mFocusedView, focused);
1884 scheduleTraversals();
1885 }
1886 mFocusedView = mRealFocusedView = focused;
1887 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Request child focus: focus now "
1888 + mFocusedView);
1889 }
1890
1891 public void clearChildFocus(View child) {
1892 checkThread();
1893
1894 View oldFocus = mFocusedView;
1895
1896 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Clearing child focus");
1897 mFocusedView = mRealFocusedView = null;
1898 if (mView != null && !mView.hasFocus()) {
1899 // If a view gets the focus, the listener will be invoked from requestChildFocus()
1900 if (!mView.requestFocus(View.FOCUS_FORWARD)) {
1901 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
1902 }
1903 } else if (oldFocus != null) {
1904 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
1905 }
1906 }
1907
1908
1909 public void focusableViewAvailable(View v) {
1910 checkThread();
1911
1912 if (mView != null && !mView.hasFocus()) {
1913 v.requestFocus();
1914 } else {
1915 // the one case where will transfer focus away from the current one
1916 // is if the current view is a view group that prefers to give focus
1917 // to its children first AND the view is a descendant of it.
1918 mFocusedView = mView.findFocus();
1919 boolean descendantsHaveDibsOnFocus =
1920 (mFocusedView instanceof ViewGroup) &&
1921 (((ViewGroup) mFocusedView).getDescendantFocusability() ==
1922 ViewGroup.FOCUS_AFTER_DESCENDANTS);
1923 if (descendantsHaveDibsOnFocus && isViewDescendantOf(v, mFocusedView)) {
1924 // If a view gets the focus, the listener will be invoked from requestChildFocus()
1925 v.requestFocus();
1926 }
1927 }
1928 }
1929
1930 public void recomputeViewAttributes(View child) {
1931 checkThread();
1932 if (mView == child) {
1933 mAttachInfo.mRecomputeGlobalAttributes = true;
1934 if (!mWillDrawSoon) {
1935 scheduleTraversals();
1936 }
1937 }
1938 }
1939
1940 void dispatchDetachedFromWindow() {
Romain Guy90fc03b2011-01-16 13:07:15 -08001941 if (mView != null && mView.mAttachInfo != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001942 mView.dispatchDetachedFromWindow();
1943 }
1944
1945 mView = null;
1946 mAttachInfo.mRootView = null;
Mathias Agopian5583dc62009-07-09 16:28:11 -07001947 mAttachInfo.mSurface = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001948
Romain Guy29d89972010-09-22 16:10:57 -07001949 destroyHardwareRenderer();
Romain Guy4caa4ed2010-08-25 14:46:24 -07001950
Dianne Hackborn0586a1b2009-09-06 21:08:27 -07001951 mSurface.release();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001952
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001953 if (mInputChannel != null) {
1954 if (mInputQueueCallback != null) {
1955 mInputQueueCallback.onInputQueueDestroyed(mInputQueue);
1956 mInputQueueCallback = null;
1957 } else {
1958 InputQueue.unregisterInputChannel(mInputChannel);
Jeff Brown46b9ac02010-04-22 18:58:52 -07001959 }
1960 }
1961
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001962 try {
1963 sWindowSession.remove(mWindow);
1964 } catch (RemoteException e) {
1965 }
Jeff Brown349703e2010-06-22 01:27:15 -07001966
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001967 // Dispose the input channel after removing the window so the Window Manager
1968 // doesn't interpret the input channel being closed as an abnormal termination.
1969 if (mInputChannel != null) {
1970 mInputChannel.dispose();
1971 mInputChannel = null;
Jeff Brown349703e2010-06-22 01:27:15 -07001972 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001973 }
Romain Guy8506ab42009-06-11 17:35:47 -07001974
Dianne Hackborn694f79b2010-03-17 19:44:59 -07001975 void updateConfiguration(Configuration config, boolean force) {
1976 if (DEBUG_CONFIGURATION) Log.v(TAG,
1977 "Applying new config to window "
1978 + mWindowAttributes.getTitle()
1979 + ": " + config);
1980 synchronized (sConfigCallbacks) {
1981 for (int i=sConfigCallbacks.size()-1; i>=0; i--) {
1982 sConfigCallbacks.get(i).onConfigurationChanged(config);
1983 }
1984 }
1985 if (mView != null) {
1986 // At this point the resources have been updated to
1987 // have the most recent config, whatever that is. Use
1988 // the on in them which may be newer.
1989 if (mView != null) {
1990 config = mView.getResources().getConfiguration();
1991 }
1992 if (force || mLastConfiguration.diff(config) != 0) {
1993 mLastConfiguration.setTo(config);
1994 mView.dispatchConfigurationChanged(config);
1995 }
1996 }
1997 }
1998
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001999 /**
2000 * Return true if child is an ancestor of parent, (or equal to the parent).
2001 */
2002 private static boolean isViewDescendantOf(View child, View parent) {
2003 if (child == parent) {
2004 return true;
2005 }
2006
2007 final ViewParent theParent = child.getParent();
2008 return (theParent instanceof ViewGroup) && isViewDescendantOf((View) theParent, parent);
2009 }
2010
Romain Guycdb86672010-03-18 18:54:50 -07002011 private static void forceLayout(View view) {
2012 view.forceLayout();
2013 if (view instanceof ViewGroup) {
2014 ViewGroup group = (ViewGroup) view;
2015 final int count = group.getChildCount();
2016 for (int i = 0; i < count; i++) {
2017 forceLayout(group.getChildAt(i));
2018 }
2019 }
2020 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002021
2022 public final static int DO_TRAVERSAL = 1000;
2023 public final static int DIE = 1001;
2024 public final static int RESIZED = 1002;
2025 public final static int RESIZED_REPORT = 1003;
2026 public final static int WINDOW_FOCUS_CHANGED = 1004;
2027 public final static int DISPATCH_KEY = 1005;
2028 public final static int DISPATCH_POINTER = 1006;
2029 public final static int DISPATCH_TRACKBALL = 1007;
2030 public final static int DISPATCH_APP_VISIBILITY = 1008;
2031 public final static int DISPATCH_GET_NEW_SURFACE = 1009;
2032 public final static int FINISHED_EVENT = 1010;
2033 public final static int DISPATCH_KEY_FROM_IME = 1011;
2034 public final static int FINISH_INPUT_CONNECTION = 1012;
2035 public final static int CHECK_FOCUS = 1013;
Dianne Hackbornffa42482009-09-23 22:20:11 -07002036 public final static int CLOSE_SYSTEM_DIALOGS = 1014;
Christopher Tatea53146c2010-09-07 11:57:52 -07002037 public final static int DISPATCH_DRAG_EVENT = 1015;
Chris Tate91e9bb32010-10-12 12:58:43 -07002038 public final static int DISPATCH_DRAG_LOCATION_EVENT = 1016;
Joe Onorato664644d2011-01-23 17:53:23 -08002039 public final static int DISPATCH_SYSTEM_UI_VISIBILITY = 1017;
Joe Onorato10f41262011-01-24 13:16:08 -08002040 public final static int DISPATCH_GENERIC_MOTION = 1018;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002041
2042 @Override
2043 public void handleMessage(Message msg) {
2044 switch (msg.what) {
2045 case View.AttachInfo.INVALIDATE_MSG:
2046 ((View) msg.obj).invalidate();
2047 break;
2048 case View.AttachInfo.INVALIDATE_RECT_MSG:
2049 final View.AttachInfo.InvalidateInfo info = (View.AttachInfo.InvalidateInfo) msg.obj;
2050 info.target.invalidate(info.left, info.top, info.right, info.bottom);
2051 info.release();
2052 break;
2053 case DO_TRAVERSAL:
2054 if (mProfile) {
Joe Onoratoc6cc0f82011-04-12 11:53:13 -07002055 Debug.startMethodTracing("ViewAncestor");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002056 }
2057
Jeff Brown4e91a182011-04-07 11:38:09 -07002058 final long traversalStartTime;
2059 if (ViewDebug.DEBUG_LATENCY) {
2060 traversalStartTime = System.nanoTime();
2061 mLastDrawDurationNanos = 0;
2062 }
2063
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002064 performTraversals();
2065
Jeff Brown4e91a182011-04-07 11:38:09 -07002066 if (ViewDebug.DEBUG_LATENCY) {
2067 long now = System.nanoTime();
2068 Log.d(TAG, "Latency: Spent "
2069 + ((now - traversalStartTime) * 0.000001f)
2070 + "ms in performTraversals(), with "
2071 + (mLastDrawDurationNanos * 0.000001f)
2072 + "ms of that time in draw()");
2073 mLastTraversalFinishedTimeNanos = now;
2074 }
2075
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002076 if (mProfile) {
2077 Debug.stopMethodTracing();
2078 mProfile = false;
2079 }
2080 break;
2081 case FINISHED_EVENT:
2082 handleFinishedEvent(msg.arg1, msg.arg2 != 0);
2083 break;
2084 case DISPATCH_KEY:
Jeff Brown92ff1dd2010-08-11 16:16:06 -07002085 deliverKeyEvent((KeyEvent)msg.obj, msg.arg1 != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002086 break;
Jeff Brown3915bb82010-11-05 15:02:16 -07002087 case DISPATCH_POINTER:
2088 deliverPointerEvent((MotionEvent) msg.obj, msg.arg1 != 0);
2089 break;
2090 case DISPATCH_TRACKBALL:
2091 deliverTrackballEvent((MotionEvent) msg.obj, msg.arg1 != 0);
2092 break;
Jeff Browncb1404e2011-01-15 18:14:15 -08002093 case DISPATCH_GENERIC_MOTION:
2094 deliverGenericMotionEvent((MotionEvent) msg.obj, msg.arg1 != 0);
2095 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002096 case DISPATCH_APP_VISIBILITY:
2097 handleAppVisibility(msg.arg1 != 0);
2098 break;
2099 case DISPATCH_GET_NEW_SURFACE:
2100 handleGetNewSurface();
2101 break;
2102 case RESIZED:
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002103 ResizedInfo ri = (ResizedInfo)msg.obj;
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002104
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002105 if (mWinFrame.width() == msg.arg1 && mWinFrame.height() == msg.arg2
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002106 && mPendingContentInsets.equals(ri.coveredInsets)
Dianne Hackbornd49258f2010-03-26 00:44:29 -07002107 && mPendingVisibleInsets.equals(ri.visibleInsets)
2108 && ((ResizedInfo)msg.obj).newConfig == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002109 break;
2110 }
2111 // fall through...
2112 case RESIZED_REPORT:
2113 if (mAdded) {
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002114 Configuration config = ((ResizedInfo)msg.obj).newConfig;
2115 if (config != null) {
Dianne Hackborn694f79b2010-03-17 19:44:59 -07002116 updateConfiguration(config, false);
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002117 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002118 mWinFrame.left = 0;
2119 mWinFrame.right = msg.arg1;
2120 mWinFrame.top = 0;
2121 mWinFrame.bottom = msg.arg2;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002122 mPendingContentInsets.set(((ResizedInfo)msg.obj).coveredInsets);
2123 mPendingVisibleInsets.set(((ResizedInfo)msg.obj).visibleInsets);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002124 if (msg.what == RESIZED_REPORT) {
2125 mReportNextDraw = true;
2126 }
Romain Guycdb86672010-03-18 18:54:50 -07002127
2128 if (mView != null) {
2129 forceLayout(mView);
2130 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002131 requestLayout();
2132 }
2133 break;
2134 case WINDOW_FOCUS_CHANGED: {
2135 if (mAdded) {
2136 boolean hasWindowFocus = msg.arg1 != 0;
2137 mAttachInfo.mHasWindowFocus = hasWindowFocus;
2138 if (hasWindowFocus) {
2139 boolean inTouchMode = msg.arg2 != 0;
Romain Guy2d4cff62010-04-09 15:39:00 -07002140 ensureTouchModeLocally(inTouchMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002141
Romain Guyc361da82010-10-25 15:29:10 -07002142 if (mAttachInfo.mHardwareRenderer != null &&
2143 mSurface != null && mSurface.isValid()) {
Romain Guy7d7b5492011-01-24 16:33:45 -08002144 mFullRedrawNeeded = true;
Dianne Hackborn64825172011-03-02 21:32:58 -08002145 try {
2146 mAttachInfo.mHardwareRenderer.initializeIfNeeded(mWidth, mHeight,
2147 mAttachInfo, mHolder);
2148 } catch (Surface.OutOfResourcesException e) {
2149 Log.e(TAG, "OutOfResourcesException locking surface", e);
2150 try {
2151 if (!sWindowSession.outOfMemory(mWindow)) {
2152 Slog.w(TAG, "No processes killed for memory; killing self");
2153 Process.killProcess(Process.myPid());
2154 }
2155 } catch (RemoteException ex) {
2156 }
2157 // Retry in a bit.
2158 sendMessageDelayed(obtainMessage(msg.what, msg.arg1, msg.arg2), 500);
2159 return;
2160 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002161 }
2162 }
Romain Guy8506ab42009-06-11 17:35:47 -07002163
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002164 mLastWasImTarget = WindowManager.LayoutParams
2165 .mayUseInputMethod(mWindowAttributes.flags);
Romain Guy8506ab42009-06-11 17:35:47 -07002166
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002167 InputMethodManager imm = InputMethodManager.peekInstance();
2168 if (mView != null) {
2169 if (hasWindowFocus && imm != null && mLastWasImTarget) {
2170 imm.startGettingWindowFocus(mView);
2171 }
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07002172 mAttachInfo.mKeyDispatchState.reset();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002173 mView.dispatchWindowFocusChanged(hasWindowFocus);
2174 }
svetoslavganov75986cf2009-05-14 22:28:01 -07002175
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002176 // Note: must be done after the focus change callbacks,
2177 // so all of the view state is set up correctly.
2178 if (hasWindowFocus) {
2179 if (imm != null && mLastWasImTarget) {
2180 imm.onWindowFocus(mView, mView.findFocus(),
2181 mWindowAttributes.softInputMode,
2182 !mHasHadWindowFocus, mWindowAttributes.flags);
2183 }
2184 // Clear the forward bit. We can just do this directly, since
2185 // the window manager doesn't care about it.
2186 mWindowAttributes.softInputMode &=
2187 ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
2188 ((WindowManager.LayoutParams)mView.getLayoutParams())
2189 .softInputMode &=
2190 ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
2191 mHasHadWindowFocus = true;
2192 }
svetoslavganov75986cf2009-05-14 22:28:01 -07002193
2194 if (hasWindowFocus && mView != null) {
2195 sendAccessibilityEvents();
2196 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002197 }
2198 } break;
2199 case DIE:
Dianne Hackborn94d69142009-09-28 22:14:42 -07002200 doDie();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002201 break;
The Android Open Source Project10592532009-03-18 17:39:46 -07002202 case DISPATCH_KEY_FROM_IME: {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002203 if (LOCAL_LOGV) Log.v(
Jeff Brownc5ed5912010-07-14 18:48:53 -07002204 TAG, "Dispatching key "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002205 + msg.obj + " from IME to " + mView);
The Android Open Source Project10592532009-03-18 17:39:46 -07002206 KeyEvent event = (KeyEvent)msg.obj;
2207 if ((event.getFlags()&KeyEvent.FLAG_FROM_SYSTEM) != 0) {
2208 // The IME is trying to say this event is from the
2209 // system! Bad bad bad!
Romain Guy812ccbe2010-06-01 14:07:24 -07002210 event = KeyEvent.changeFlags(event, event.getFlags() & ~KeyEvent.FLAG_FROM_SYSTEM);
The Android Open Source Project10592532009-03-18 17:39:46 -07002211 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002212 deliverKeyEventPostIme((KeyEvent)msg.obj, false);
The Android Open Source Project10592532009-03-18 17:39:46 -07002213 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002214 case FINISH_INPUT_CONNECTION: {
2215 InputMethodManager imm = InputMethodManager.peekInstance();
2216 if (imm != null) {
2217 imm.reportFinishInputConnection((InputConnection)msg.obj);
2218 }
2219 } break;
2220 case CHECK_FOCUS: {
2221 InputMethodManager imm = InputMethodManager.peekInstance();
2222 if (imm != null) {
2223 imm.checkFocus();
2224 }
2225 } break;
Dianne Hackbornffa42482009-09-23 22:20:11 -07002226 case CLOSE_SYSTEM_DIALOGS: {
2227 if (mView != null) {
2228 mView.onCloseSystemDialogs((String)msg.obj);
2229 }
2230 } break;
Chris Tate91e9bb32010-10-12 12:58:43 -07002231 case DISPATCH_DRAG_EVENT:
2232 case DISPATCH_DRAG_LOCATION_EVENT: {
Christopher Tate7fb8b562011-01-20 13:46:41 -08002233 DragEvent event = (DragEvent)msg.obj;
2234 event.mLocalState = mLocalDragState; // only present when this app called startDrag()
2235 handleDragEvent(event);
Christopher Tatea53146c2010-09-07 11:57:52 -07002236 } break;
Joe Onorato664644d2011-01-23 17:53:23 -08002237 case DISPATCH_SYSTEM_UI_VISIBILITY: {
2238 handleDispatchSystemUiVisibilityChanged(msg.arg1);
2239 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002240 }
2241 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002242
Jeff Brown4e91a182011-04-07 11:38:09 -07002243 private void startInputEvent(InputEvent event, InputQueue.FinishedCallback finishedCallback) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07002244 if (mFinishedCallback != null) {
2245 Slog.w(TAG, "Received a new input event from the input queue but there is "
2246 + "already an unfinished input event in progress.");
2247 }
2248
Jeff Brown4e91a182011-04-07 11:38:09 -07002249 if (ViewDebug.DEBUG_LATENCY) {
2250 mInputEventReceiveTimeNanos = System.nanoTime();
2251 mInputEventDeliverTimeNanos = 0;
2252 mInputEventDeliverPostImeTimeNanos = 0;
2253 }
2254
Jeff Brown93ed4e32010-09-23 13:51:48 -07002255 mFinishedCallback = finishedCallback;
2256 }
2257
Jeff Brown4e91a182011-04-07 11:38:09 -07002258 private void finishInputEvent(InputEvent event, boolean handled) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07002259 if (LOCAL_LOGV) Log.v(TAG, "Telling window manager input event is finished");
Jeff Brown92ff1dd2010-08-11 16:16:06 -07002260
Jeff Brown4e91a182011-04-07 11:38:09 -07002261 if (mFinishedCallback == null) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07002262 Slog.w(TAG, "Attempted to tell the input queue that the current input event "
2263 + "is finished but there is no input event actually in progress.");
Jeff Brown4e91a182011-04-07 11:38:09 -07002264 return;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002265 }
Jeff Brown4e91a182011-04-07 11:38:09 -07002266
2267 if (ViewDebug.DEBUG_LATENCY) {
2268 final long now = System.nanoTime();
2269 final long eventTime = event.getEventTimeNano();
2270 final StringBuilder msg = new StringBuilder();
2271 msg.append("Latency: Spent ");
2272 msg.append((now - mInputEventReceiveTimeNanos) * 0.000001f);
2273 msg.append("ms processing ");
2274 if (event instanceof KeyEvent) {
2275 final KeyEvent keyEvent = (KeyEvent)event;
2276 msg.append("key event, action=");
2277 msg.append(KeyEvent.actionToString(keyEvent.getAction()));
2278 } else {
2279 final MotionEvent motionEvent = (MotionEvent)event;
2280 msg.append("motion event, action=");
2281 msg.append(MotionEvent.actionToString(motionEvent.getAction()));
2282 msg.append(", historySize=");
2283 msg.append(motionEvent.getHistorySize());
2284 }
2285 msg.append(", handled=");
2286 msg.append(handled);
2287 msg.append(", received at +");
2288 msg.append((mInputEventReceiveTimeNanos - eventTime) * 0.000001f);
2289 if (mInputEventDeliverTimeNanos != 0) {
2290 msg.append("ms, delivered at +");
2291 msg.append((mInputEventDeliverTimeNanos - eventTime) * 0.000001f);
2292 }
2293 if (mInputEventDeliverPostImeTimeNanos != 0) {
2294 msg.append("ms, delivered post IME at +");
2295 msg.append((mInputEventDeliverPostImeTimeNanos - eventTime) * 0.000001f);
2296 }
2297 msg.append("ms, finished at +");
2298 msg.append((now - eventTime) * 0.000001f);
2299 msg.append("ms.");
2300 Log.d(TAG, msg.toString());
2301 }
2302
2303 mFinishedCallback.finished(handled);
2304 mFinishedCallback = null;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002305 }
2306
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002307 /**
2308 * Something in the current window tells us we need to change the touch mode. For
2309 * example, we are not in touch mode, and the user touches the screen.
2310 *
2311 * If the touch mode has changed, tell the window manager, and handle it locally.
2312 *
2313 * @param inTouchMode Whether we want to be in touch mode.
2314 * @return True if the touch mode changed and focus changed was changed as a result
2315 */
2316 boolean ensureTouchMode(boolean inTouchMode) {
2317 if (DBG) Log.d("touchmode", "ensureTouchMode(" + inTouchMode + "), current "
2318 + "touch mode is " + mAttachInfo.mInTouchMode);
2319 if (mAttachInfo.mInTouchMode == inTouchMode) return false;
2320
2321 // tell the window manager
2322 try {
2323 sWindowSession.setInTouchMode(inTouchMode);
2324 } catch (RemoteException e) {
2325 throw new RuntimeException(e);
2326 }
2327
2328 // handle the change
Romain Guy2d4cff62010-04-09 15:39:00 -07002329 return ensureTouchModeLocally(inTouchMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002330 }
2331
2332 /**
2333 * Ensure that the touch mode for this window is set, and if it is changing,
2334 * take the appropriate action.
2335 * @param inTouchMode Whether we want to be in touch mode.
2336 * @return True if the touch mode changed and focus changed was changed as a result
2337 */
Romain Guy2d4cff62010-04-09 15:39:00 -07002338 private boolean ensureTouchModeLocally(boolean inTouchMode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002339 if (DBG) Log.d("touchmode", "ensureTouchModeLocally(" + inTouchMode + "), current "
2340 + "touch mode is " + mAttachInfo.mInTouchMode);
2341
2342 if (mAttachInfo.mInTouchMode == inTouchMode) return false;
2343
2344 mAttachInfo.mInTouchMode = inTouchMode;
2345 mAttachInfo.mTreeObserver.dispatchOnTouchModeChanged(inTouchMode);
2346
Romain Guy2d4cff62010-04-09 15:39:00 -07002347 return (inTouchMode) ? enterTouchMode() : leaveTouchMode();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002348 }
2349
2350 private boolean enterTouchMode() {
2351 if (mView != null) {
2352 if (mView.hasFocus()) {
2353 // note: not relying on mFocusedView here because this could
2354 // be when the window is first being added, and mFocused isn't
2355 // set yet.
2356 final View focused = mView.findFocus();
2357 if (focused != null && !focused.isFocusableInTouchMode()) {
2358
2359 final ViewGroup ancestorToTakeFocus =
2360 findAncestorToTakeFocusInTouchMode(focused);
2361 if (ancestorToTakeFocus != null) {
2362 // there is an ancestor that wants focus after its descendants that
2363 // is focusable in touch mode.. give it focus
2364 return ancestorToTakeFocus.requestFocus();
2365 } else {
2366 // nothing appropriate to have focus in touch mode, clear it out
2367 mView.unFocus();
2368 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(focused, null);
2369 mFocusedView = null;
2370 return true;
2371 }
2372 }
2373 }
2374 }
2375 return false;
2376 }
2377
2378
2379 /**
2380 * Find an ancestor of focused that wants focus after its descendants and is
2381 * focusable in touch mode.
2382 * @param focused The currently focused view.
2383 * @return An appropriate view, or null if no such view exists.
2384 */
2385 private ViewGroup findAncestorToTakeFocusInTouchMode(View focused) {
2386 ViewParent parent = focused.getParent();
2387 while (parent instanceof ViewGroup) {
2388 final ViewGroup vgParent = (ViewGroup) parent;
2389 if (vgParent.getDescendantFocusability() == ViewGroup.FOCUS_AFTER_DESCENDANTS
2390 && vgParent.isFocusableInTouchMode()) {
2391 return vgParent;
2392 }
2393 if (vgParent.isRootNamespace()) {
2394 return null;
2395 } else {
2396 parent = vgParent.getParent();
2397 }
2398 }
2399 return null;
2400 }
2401
2402 private boolean leaveTouchMode() {
2403 if (mView != null) {
2404 if (mView.hasFocus()) {
2405 // i learned the hard way to not trust mFocusedView :)
2406 mFocusedView = mView.findFocus();
2407 if (!(mFocusedView instanceof ViewGroup)) {
2408 // some view has focus, let it keep it
2409 return false;
2410 } else if (((ViewGroup)mFocusedView).getDescendantFocusability() !=
2411 ViewGroup.FOCUS_AFTER_DESCENDANTS) {
2412 // some view group has focus, and doesn't prefer its children
2413 // over itself for focus, so let them keep it.
2414 return false;
2415 }
2416 }
2417
2418 // find the best view to give focus to in this brave new non-touch-mode
2419 // world
2420 final View focused = focusSearch(null, View.FOCUS_DOWN);
2421 if (focused != null) {
2422 return focused.requestFocus(View.FOCUS_DOWN);
2423 }
2424 }
2425 return false;
2426 }
2427
Jeff Brown3915bb82010-11-05 15:02:16 -07002428 private void deliverPointerEvent(MotionEvent event, boolean sendDone) {
Jeff Brown4e91a182011-04-07 11:38:09 -07002429 if (ViewDebug.DEBUG_LATENCY) {
2430 mInputEventDeliverTimeNanos = System.nanoTime();
2431 }
2432
Jeff Brown21bc5c92011-02-28 18:27:14 -08002433 if (mInputEventConsistencyVerifier != null) {
2434 if (event.isTouchEvent()) {
2435 mInputEventConsistencyVerifier.onTouchEvent(event, 0);
2436 } else {
2437 mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
2438 }
2439 }
2440
Jeff Brown3915bb82010-11-05 15:02:16 -07002441 // If there is no view, then the event will not be handled.
2442 if (mView == null || !mAdded) {
Jeff Brown33bbfd22011-02-24 20:55:35 -08002443 finishMotionEvent(event, sendDone, false);
Jeff Brown3915bb82010-11-05 15:02:16 -07002444 return;
2445 }
2446
2447 // Translate the pointer event for compatibility, if needed.
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002448 if (mTranslator != null) {
2449 mTranslator.translateEventInScreenToAppWindow(event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002450 }
2451
Jeff Brown3915bb82010-11-05 15:02:16 -07002452 // Enter touch mode on the down.
2453 boolean isDown = event.getAction() == MotionEvent.ACTION_DOWN;
2454 if (isDown) {
2455 ensureTouchMode(true);
2456 }
Joe Onorato43a17652011-04-06 19:22:23 -07002457 if(false) {
Jeff Brown3915bb82010-11-05 15:02:16 -07002458 captureMotionLog("captureDispatchPointer", event);
2459 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002460
Jeff Brown3915bb82010-11-05 15:02:16 -07002461 // Offset the scroll position.
2462 if (mCurScrollY != 0) {
2463 event.offsetLocation(0, mCurScrollY);
2464 }
2465 if (MEASURE_LATENCY) {
Jeff Brown33bbfd22011-02-24 20:55:35 -08002466 lt.sample("A Dispatching PointerEvents", System.nanoTime() - event.getEventTimeNano());
Jeff Brown3915bb82010-11-05 15:02:16 -07002467 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002468
Jeff Brown3915bb82010-11-05 15:02:16 -07002469 // Remember the touch position for possible drag-initiation.
2470 mLastTouchPoint.x = event.getRawX();
2471 mLastTouchPoint.y = event.getRawY();
2472
2473 // Dispatch touch to view hierarchy.
Jeff Brown33bbfd22011-02-24 20:55:35 -08002474 boolean handled = mView.dispatchPointerEvent(event);
Jeff Brown3915bb82010-11-05 15:02:16 -07002475 if (MEASURE_LATENCY) {
Jeff Brown33bbfd22011-02-24 20:55:35 -08002476 lt.sample("B Dispatched PointerEvents ", System.nanoTime() - event.getEventTimeNano());
Jeff Brown3915bb82010-11-05 15:02:16 -07002477 }
2478 if (handled) {
Jeff Brown33bbfd22011-02-24 20:55:35 -08002479 finishMotionEvent(event, sendDone, true);
Jeff Brown3915bb82010-11-05 15:02:16 -07002480 return;
2481 }
2482
2483 // Apply edge slop and try again, if appropriate.
2484 final int edgeFlags = event.getEdgeFlags();
2485 if (edgeFlags != 0 && mView instanceof ViewGroup) {
2486 final int edgeSlop = mViewConfiguration.getScaledEdgeSlop();
2487 int direction = View.FOCUS_UP;
2488 int x = (int)event.getX();
2489 int y = (int)event.getY();
2490 final int[] deltas = new int[2];
2491
2492 if ((edgeFlags & MotionEvent.EDGE_TOP) != 0) {
2493 direction = View.FOCUS_DOWN;
2494 if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
2495 deltas[0] = edgeSlop;
2496 x += edgeSlop;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002497 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
Jeff Brown3915bb82010-11-05 15:02:16 -07002498 deltas[0] = -edgeSlop;
2499 x -= edgeSlop;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002500 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002501 } else if ((edgeFlags & MotionEvent.EDGE_BOTTOM) != 0) {
2502 direction = View.FOCUS_UP;
2503 if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
2504 deltas[0] = edgeSlop;
2505 x += edgeSlop;
2506 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
2507 deltas[0] = -edgeSlop;
2508 x -= edgeSlop;
2509 }
2510 } else if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
2511 direction = View.FOCUS_RIGHT;
2512 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
2513 direction = View.FOCUS_LEFT;
2514 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002515
Jeff Brown3915bb82010-11-05 15:02:16 -07002516 View nearest = FocusFinder.getInstance().findNearestTouchable(
2517 ((ViewGroup) mView), x, y, direction, deltas);
2518 if (nearest != null) {
2519 event.offsetLocation(deltas[0], deltas[1]);
2520 event.setEdgeFlags(0);
Jeff Brown33bbfd22011-02-24 20:55:35 -08002521 if (mView.dispatchPointerEvent(event)) {
2522 finishMotionEvent(event, sendDone, true);
Jeff Brown3915bb82010-11-05 15:02:16 -07002523 return;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002524 }
2525 }
2526 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002527
2528 // Pointer event was unhandled.
Jeff Brown33bbfd22011-02-24 20:55:35 -08002529 finishMotionEvent(event, sendDone, false);
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002530 }
2531
Jeff Brown33bbfd22011-02-24 20:55:35 -08002532 private void finishMotionEvent(MotionEvent event, boolean sendDone, boolean handled) {
Jeff Brown3915bb82010-11-05 15:02:16 -07002533 event.recycle();
2534 if (sendDone) {
Jeff Brown4e91a182011-04-07 11:38:09 -07002535 finishInputEvent(event, handled);
Jeff Brown3915bb82010-11-05 15:02:16 -07002536 }
Jeff Brown33bbfd22011-02-24 20:55:35 -08002537 if (LOCAL_LOGV || WATCH_POINTER) {
2538 if ((event.getSource() & InputDevice.SOURCE_CLASS_POINTER) != 0) {
2539 Log.i(TAG, "Done dispatching!");
2540 }
2541 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002542 }
2543
2544 private void deliverTrackballEvent(MotionEvent event, boolean sendDone) {
Jeff Brown4e91a182011-04-07 11:38:09 -07002545 if (ViewDebug.DEBUG_LATENCY) {
2546 mInputEventDeliverTimeNanos = System.nanoTime();
2547 }
2548
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002549 if (DEBUG_TRACKBALL) Log.v(TAG, "Motion event:" + event);
2550
Jeff Brown21bc5c92011-02-28 18:27:14 -08002551 if (mInputEventConsistencyVerifier != null) {
2552 mInputEventConsistencyVerifier.onTrackballEvent(event, 0);
2553 }
2554
Jeff Brown3915bb82010-11-05 15:02:16 -07002555 // If there is no view, then the event will not be handled.
2556 if (mView == null || !mAdded) {
Jeff Brown33bbfd22011-02-24 20:55:35 -08002557 finishMotionEvent(event, sendDone, false);
Jeff Brown3915bb82010-11-05 15:02:16 -07002558 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002559 }
2560
Jeff Brown3915bb82010-11-05 15:02:16 -07002561 // Deliver the trackball event to the view.
2562 if (mView.dispatchTrackballEvent(event)) {
2563 // If we reach this, we delivered a trackball event to mView and
2564 // mView consumed it. Because we will not translate the trackball
2565 // event into a key event, touch mode will not exit, so we exit
2566 // touch mode here.
2567 ensureTouchMode(false);
2568
Jeff Brown33bbfd22011-02-24 20:55:35 -08002569 finishMotionEvent(event, sendDone, true);
Jeff Brown3915bb82010-11-05 15:02:16 -07002570 mLastTrackballTime = Integer.MIN_VALUE;
2571 return;
2572 }
2573
2574 // Translate the trackball event into DPAD keys and try to deliver those.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002575 final TrackballAxis x = mTrackballAxisX;
2576 final TrackballAxis y = mTrackballAxisY;
2577
2578 long curTime = SystemClock.uptimeMillis();
Jeff Brown3915bb82010-11-05 15:02:16 -07002579 if ((mLastTrackballTime + MAX_TRACKBALL_DELAY) < curTime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002580 // It has been too long since the last movement,
2581 // so restart at the beginning.
2582 x.reset(0);
2583 y.reset(0);
2584 mLastTrackballTime = curTime;
2585 }
2586
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002587 final int action = event.getAction();
Jeff Brown49ed71d2010-12-06 17:13:33 -08002588 final int metaState = event.getMetaState();
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002589 switch (action) {
2590 case MotionEvent.ACTION_DOWN:
2591 x.reset(2);
2592 y.reset(2);
2593 deliverKeyEvent(new KeyEvent(curTime, curTime,
Jeff Brown49ed71d2010-12-06 17:13:33 -08002594 KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_CENTER, 0, metaState,
2595 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
2596 InputDevice.SOURCE_KEYBOARD), false);
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002597 break;
2598 case MotionEvent.ACTION_UP:
2599 x.reset(2);
2600 y.reset(2);
2601 deliverKeyEvent(new KeyEvent(curTime, curTime,
Jeff Brown49ed71d2010-12-06 17:13:33 -08002602 KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_CENTER, 0, metaState,
2603 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
2604 InputDevice.SOURCE_KEYBOARD), false);
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002605 break;
2606 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002607
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002608 if (DEBUG_TRACKBALL) Log.v(TAG, "TB X=" + x.position + " step="
2609 + x.step + " dir=" + x.dir + " acc=" + x.acceleration
2610 + " move=" + event.getX()
2611 + " / Y=" + y.position + " step="
2612 + y.step + " dir=" + y.dir + " acc=" + y.acceleration
2613 + " move=" + event.getY());
2614 final float xOff = x.collect(event.getX(), event.getEventTime(), "X");
2615 final float yOff = y.collect(event.getY(), event.getEventTime(), "Y");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002616
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002617 // Generate DPAD events based on the trackball movement.
2618 // We pick the axis that has moved the most as the direction of
2619 // the DPAD. When we generate DPAD events for one axis, then the
2620 // other axis is reset -- we don't want to perform DPAD jumps due
2621 // to slight movements in the trackball when making major movements
2622 // along the other axis.
2623 int keycode = 0;
2624 int movement = 0;
2625 float accel = 1;
2626 if (xOff > yOff) {
2627 movement = x.generate((2/event.getXPrecision()));
2628 if (movement != 0) {
2629 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_RIGHT
2630 : KeyEvent.KEYCODE_DPAD_LEFT;
2631 accel = x.acceleration;
2632 y.reset(2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002633 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002634 } else if (yOff > 0) {
2635 movement = y.generate((2/event.getYPrecision()));
2636 if (movement != 0) {
2637 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_DOWN
2638 : KeyEvent.KEYCODE_DPAD_UP;
2639 accel = y.acceleration;
2640 x.reset(2);
2641 }
2642 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002643
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002644 if (keycode != 0) {
2645 if (movement < 0) movement = -movement;
2646 int accelMovement = (int)(movement * accel);
2647 if (DEBUG_TRACKBALL) Log.v(TAG, "Move: movement=" + movement
2648 + " accelMovement=" + accelMovement
2649 + " accel=" + accel);
2650 if (accelMovement > movement) {
2651 if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: "
2652 + keycode);
2653 movement--;
Jeff Brown49ed71d2010-12-06 17:13:33 -08002654 int repeatCount = accelMovement - movement;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002655 deliverKeyEvent(new KeyEvent(curTime, curTime,
Jeff Brown49ed71d2010-12-06 17:13:33 -08002656 KeyEvent.ACTION_MULTIPLE, keycode, repeatCount, metaState,
2657 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
2658 InputDevice.SOURCE_KEYBOARD), false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002659 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002660 while (movement > 0) {
2661 if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: "
2662 + keycode);
2663 movement--;
2664 curTime = SystemClock.uptimeMillis();
2665 deliverKeyEvent(new KeyEvent(curTime, curTime,
Jeff Brown49ed71d2010-12-06 17:13:33 -08002666 KeyEvent.ACTION_DOWN, keycode, 0, metaState,
2667 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
2668 InputDevice.SOURCE_KEYBOARD), false);
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002669 deliverKeyEvent(new KeyEvent(curTime, curTime,
Jeff Brown49ed71d2010-12-06 17:13:33 -08002670 KeyEvent.ACTION_UP, keycode, 0, metaState,
2671 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
2672 InputDevice.SOURCE_KEYBOARD), false);
2673 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002674 mLastTrackballTime = curTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002675 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002676
2677 // Unfortunately we can't tell whether the application consumed the keys, so
2678 // we always consider the trackball event handled.
Jeff Brown33bbfd22011-02-24 20:55:35 -08002679 finishMotionEvent(event, sendDone, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002680 }
2681
Jeff Browncb1404e2011-01-15 18:14:15 -08002682 private void deliverGenericMotionEvent(MotionEvent event, boolean sendDone) {
Jeff Brown4e91a182011-04-07 11:38:09 -07002683 if (ViewDebug.DEBUG_LATENCY) {
2684 mInputEventDeliverTimeNanos = System.nanoTime();
2685 }
2686
Jeff Brown21bc5c92011-02-28 18:27:14 -08002687 if (mInputEventConsistencyVerifier != null) {
2688 mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
2689 }
2690
Jeff Browncb1404e2011-01-15 18:14:15 -08002691 final int source = event.getSource();
2692 final boolean isJoystick = (source & InputDevice.SOURCE_CLASS_JOYSTICK) != 0;
2693
2694 // If there is no view, then the event will not be handled.
2695 if (mView == null || !mAdded) {
2696 if (isJoystick) {
2697 updateJoystickDirection(event, false);
2698 }
Jeff Brown33bbfd22011-02-24 20:55:35 -08002699 finishMotionEvent(event, sendDone, false);
Jeff Browncb1404e2011-01-15 18:14:15 -08002700 return;
2701 }
2702
2703 // Deliver the event to the view.
2704 if (mView.dispatchGenericMotionEvent(event)) {
Jeff Browncb1404e2011-01-15 18:14:15 -08002705 if (isJoystick) {
2706 updateJoystickDirection(event, false);
2707 }
Jeff Brown33bbfd22011-02-24 20:55:35 -08002708 finishMotionEvent(event, sendDone, true);
Jeff Browncb1404e2011-01-15 18:14:15 -08002709 return;
2710 }
2711
2712 if (isJoystick) {
2713 // Translate the joystick event into DPAD keys and try to deliver those.
2714 updateJoystickDirection(event, true);
Jeff Brown33bbfd22011-02-24 20:55:35 -08002715 finishMotionEvent(event, sendDone, true);
Jeff Browncb1404e2011-01-15 18:14:15 -08002716 } else {
Jeff Brown33bbfd22011-02-24 20:55:35 -08002717 finishMotionEvent(event, sendDone, false);
Jeff Browncb1404e2011-01-15 18:14:15 -08002718 }
2719 }
2720
2721 private void updateJoystickDirection(MotionEvent event, boolean synthesizeNewKeys) {
2722 final long time = event.getEventTime();
2723 final int metaState = event.getMetaState();
2724 final int deviceId = event.getDeviceId();
2725 final int source = event.getSource();
Jeff Brown6f2fba42011-02-19 01:08:02 -08002726
2727 int xDirection = joystickAxisValueToDirection(event.getAxisValue(MotionEvent.AXIS_HAT_X));
2728 if (xDirection == 0) {
2729 xDirection = joystickAxisValueToDirection(event.getX());
2730 }
2731
2732 int yDirection = joystickAxisValueToDirection(event.getAxisValue(MotionEvent.AXIS_HAT_Y));
2733 if (yDirection == 0) {
2734 yDirection = joystickAxisValueToDirection(event.getY());
2735 }
Jeff Browncb1404e2011-01-15 18:14:15 -08002736
2737 if (xDirection != mLastJoystickXDirection) {
2738 if (mLastJoystickXKeyCode != 0) {
2739 deliverKeyEvent(new KeyEvent(time, time,
2740 KeyEvent.ACTION_UP, mLastJoystickXKeyCode, 0, metaState,
2741 deviceId, 0, KeyEvent.FLAG_FALLBACK, source), false);
2742 mLastJoystickXKeyCode = 0;
2743 }
2744
2745 mLastJoystickXDirection = xDirection;
2746
2747 if (xDirection != 0 && synthesizeNewKeys) {
2748 mLastJoystickXKeyCode = xDirection > 0
2749 ? KeyEvent.KEYCODE_DPAD_RIGHT : KeyEvent.KEYCODE_DPAD_LEFT;
2750 deliverKeyEvent(new KeyEvent(time, time,
2751 KeyEvent.ACTION_DOWN, mLastJoystickXKeyCode, 0, metaState,
2752 deviceId, 0, KeyEvent.FLAG_FALLBACK, source), false);
2753 }
2754 }
2755
2756 if (yDirection != mLastJoystickYDirection) {
2757 if (mLastJoystickYKeyCode != 0) {
2758 deliverKeyEvent(new KeyEvent(time, time,
2759 KeyEvent.ACTION_UP, mLastJoystickYKeyCode, 0, metaState,
2760 deviceId, 0, KeyEvent.FLAG_FALLBACK, source), false);
2761 mLastJoystickYKeyCode = 0;
2762 }
2763
2764 mLastJoystickYDirection = yDirection;
2765
2766 if (yDirection != 0 && synthesizeNewKeys) {
2767 mLastJoystickYKeyCode = yDirection > 0
2768 ? KeyEvent.KEYCODE_DPAD_DOWN : KeyEvent.KEYCODE_DPAD_UP;
2769 deliverKeyEvent(new KeyEvent(time, time,
2770 KeyEvent.ACTION_DOWN, mLastJoystickYKeyCode, 0, metaState,
2771 deviceId, 0, KeyEvent.FLAG_FALLBACK, source), false);
2772 }
2773 }
2774 }
2775
2776 private static int joystickAxisValueToDirection(float value) {
2777 if (value >= 0.5f) {
2778 return 1;
2779 } else if (value <= -0.5f) {
2780 return -1;
2781 } else {
2782 return 0;
2783 }
2784 }
2785
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002786 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08002787 * Returns true if the key is used for keyboard navigation.
2788 * @param keyEvent The key event.
2789 * @return True if the key is used for keyboard navigation.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002790 */
Jeff Brown4e6319b2010-12-13 10:36:51 -08002791 private static boolean isNavigationKey(KeyEvent keyEvent) {
2792 switch (keyEvent.getKeyCode()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002793 case KeyEvent.KEYCODE_DPAD_LEFT:
2794 case KeyEvent.KEYCODE_DPAD_RIGHT:
2795 case KeyEvent.KEYCODE_DPAD_UP:
2796 case KeyEvent.KEYCODE_DPAD_DOWN:
Jeff Brown4e6319b2010-12-13 10:36:51 -08002797 case KeyEvent.KEYCODE_DPAD_CENTER:
2798 case KeyEvent.KEYCODE_PAGE_UP:
2799 case KeyEvent.KEYCODE_PAGE_DOWN:
2800 case KeyEvent.KEYCODE_MOVE_HOME:
2801 case KeyEvent.KEYCODE_MOVE_END:
2802 case KeyEvent.KEYCODE_TAB:
2803 case KeyEvent.KEYCODE_SPACE:
2804 case KeyEvent.KEYCODE_ENTER:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002805 return true;
2806 }
2807 return false;
2808 }
2809
2810 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08002811 * Returns true if the key is used for typing.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002812 * @param keyEvent The key event.
Jeff Brown4e6319b2010-12-13 10:36:51 -08002813 * @return True if the key is used for typing.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002814 */
Jeff Brown4e6319b2010-12-13 10:36:51 -08002815 private static boolean isTypingKey(KeyEvent keyEvent) {
2816 return keyEvent.getUnicodeChar() > 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002817 }
2818
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002819 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08002820 * 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 -08002821 * @param event The key event.
2822 * @return Whether this key event should be consumed (meaning the act of
2823 * leaving touch mode alone is considered the event).
2824 */
2825 private boolean checkForLeavingTouchModeAndConsume(KeyEvent event) {
Jeff Brown4e6319b2010-12-13 10:36:51 -08002826 // Only relevant in touch mode.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002827 if (!mAttachInfo.mInTouchMode) {
2828 return false;
2829 }
2830
Jeff Brown4e6319b2010-12-13 10:36:51 -08002831 // Only consider leaving touch mode on DOWN or MULTIPLE actions, never on UP.
2832 final int action = event.getAction();
2833 if (action != KeyEvent.ACTION_DOWN && action != KeyEvent.ACTION_MULTIPLE) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002834 return false;
2835 }
2836
Jeff Brown4e6319b2010-12-13 10:36:51 -08002837 // Don't leave touch mode if the IME told us not to.
2838 if ((event.getFlags() & KeyEvent.FLAG_KEEP_TOUCH_MODE) != 0) {
2839 return false;
2840 }
2841
2842 // If the key can be used for keyboard navigation then leave touch mode
2843 // and select a focused view if needed (in ensureTouchMode).
2844 // When a new focused view is selected, we consume the navigation key because
2845 // navigation doesn't make much sense unless a view already has focus so
2846 // the key's purpose is to set focus.
2847 if (isNavigationKey(event)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002848 return ensureTouchMode(false);
2849 }
Jeff Brown4e6319b2010-12-13 10:36:51 -08002850
2851 // If the key can be used for typing then leave touch mode
2852 // and select a focused view if needed (in ensureTouchMode).
2853 // Always allow the view to process the typing key.
2854 if (isTypingKey(event)) {
2855 ensureTouchMode(false);
2856 return false;
2857 }
2858
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002859 return false;
2860 }
2861
2862 /**
Romain Guy8506ab42009-06-11 17:35:47 -07002863 * log motion events
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002864 */
2865 private static void captureMotionLog(String subTag, MotionEvent ev) {
Romain Guy8506ab42009-06-11 17:35:47 -07002866 //check dynamic switch
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002867 if (ev == null ||
2868 SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_EVENT, 0) == 0) {
2869 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002870 }
Romain Guy8506ab42009-06-11 17:35:47 -07002871
2872 StringBuilder sb = new StringBuilder(subTag + ": ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002873 sb.append(ev.getDownTime()).append(',');
2874 sb.append(ev.getEventTime()).append(',');
2875 sb.append(ev.getAction()).append(',');
Romain Guy8506ab42009-06-11 17:35:47 -07002876 sb.append(ev.getX()).append(',');
2877 sb.append(ev.getY()).append(',');
2878 sb.append(ev.getPressure()).append(',');
2879 sb.append(ev.getSize()).append(',');
2880 sb.append(ev.getMetaState()).append(',');
2881 sb.append(ev.getXPrecision()).append(',');
2882 sb.append(ev.getYPrecision()).append(',');
2883 sb.append(ev.getDeviceId()).append(',');
2884 sb.append(ev.getEdgeFlags());
2885 Log.d(TAG, sb.toString());
2886 }
2887 /**
2888 * log motion events
2889 */
2890 private static void captureKeyLog(String subTag, KeyEvent ev) {
2891 //check dynamic switch
2892 if (ev == null ||
2893 SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_EVENT, 0) == 0) {
2894 return;
2895 }
2896 StringBuilder sb = new StringBuilder(subTag + ": ");
2897 sb.append(ev.getDownTime()).append(',');
2898 sb.append(ev.getEventTime()).append(',');
2899 sb.append(ev.getAction()).append(',');
2900 sb.append(ev.getKeyCode()).append(',');
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002901 sb.append(ev.getRepeatCount()).append(',');
2902 sb.append(ev.getMetaState()).append(',');
2903 sb.append(ev.getDeviceId()).append(',');
2904 sb.append(ev.getScanCode());
Romain Guy8506ab42009-06-11 17:35:47 -07002905 Log.d(TAG, sb.toString());
2906 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002907
2908 int enqueuePendingEvent(Object event, boolean sendDone) {
2909 int seq = mPendingEventSeq+1;
2910 if (seq < 0) seq = 0;
2911 mPendingEventSeq = seq;
2912 mPendingEvents.put(seq, event);
2913 return sendDone ? seq : -seq;
2914 }
2915
2916 Object retrievePendingEvent(int seq) {
2917 if (seq < 0) seq = -seq;
2918 Object event = mPendingEvents.get(seq);
2919 if (event != null) {
2920 mPendingEvents.remove(seq);
2921 }
2922 return event;
2923 }
Romain Guy8506ab42009-06-11 17:35:47 -07002924
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002925 private void deliverKeyEvent(KeyEvent event, boolean sendDone) {
Jeff Brown4e91a182011-04-07 11:38:09 -07002926 if (ViewDebug.DEBUG_LATENCY) {
2927 mInputEventDeliverTimeNanos = System.nanoTime();
2928 }
2929
Jeff Brown21bc5c92011-02-28 18:27:14 -08002930 if (mInputEventConsistencyVerifier != null) {
2931 mInputEventConsistencyVerifier.onKeyEvent(event, 0);
2932 }
2933
Jeff Brown3915bb82010-11-05 15:02:16 -07002934 // If there is no view, then the event will not be handled.
2935 if (mView == null || !mAdded) {
2936 finishKeyEvent(event, sendDone, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002937 return;
2938 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002939
2940 if (LOCAL_LOGV) Log.v(TAG, "Dispatching key " + event + " to " + mView);
2941
2942 // Perform predispatching before the IME.
2943 if (mView.dispatchKeyEventPreIme(event)) {
2944 finishKeyEvent(event, sendDone, true);
2945 return;
2946 }
2947
2948 // Dispatch to the IME before propagating down the view hierarchy.
2949 // The IME will eventually call back into handleFinishedEvent.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002950 if (mLastWasImTarget) {
2951 InputMethodManager imm = InputMethodManager.peekInstance();
Jeff Brown3915bb82010-11-05 15:02:16 -07002952 if (imm != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002953 int seq = enqueuePendingEvent(event, sendDone);
2954 if (DEBUG_IMF) Log.v(TAG, "Sending key event to IME: seq="
2955 + seq + " event=" + event);
Jeff Brown3915bb82010-11-05 15:02:16 -07002956 imm.dispatchKeyEvent(mView.getContext(), seq, event, mInputMethodCallback);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002957 return;
2958 }
2959 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002960
2961 // Not dispatching to IME, continue with post IME actions.
2962 deliverKeyEventPostIme(event, sendDone);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002963 }
2964
Jeff Brown3915bb82010-11-05 15:02:16 -07002965 private void handleFinishedEvent(int seq, boolean handled) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002966 final KeyEvent event = (KeyEvent)retrievePendingEvent(seq);
2967 if (DEBUG_IMF) Log.v(TAG, "IME finished event: seq=" + seq
2968 + " handled=" + handled + " event=" + event);
2969 if (event != null) {
2970 final boolean sendDone = seq >= 0;
Jeff Brown3915bb82010-11-05 15:02:16 -07002971 if (handled) {
2972 finishKeyEvent(event, sendDone, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002973 } else {
Jeff Brown3915bb82010-11-05 15:02:16 -07002974 deliverKeyEventPostIme(event, sendDone);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002975 }
2976 }
2977 }
Romain Guy8506ab42009-06-11 17:35:47 -07002978
Jeff Brown3915bb82010-11-05 15:02:16 -07002979 private void deliverKeyEventPostIme(KeyEvent event, boolean sendDone) {
Jeff Brown4e91a182011-04-07 11:38:09 -07002980 if (ViewDebug.DEBUG_LATENCY) {
2981 mInputEventDeliverPostImeTimeNanos = System.nanoTime();
2982 }
2983
Jeff Brown3915bb82010-11-05 15:02:16 -07002984 // If the view went away, then the event will not be handled.
2985 if (mView == null || !mAdded) {
2986 finishKeyEvent(event, sendDone, false);
2987 return;
2988 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002989
Jeff Brown3915bb82010-11-05 15:02:16 -07002990 // If the key's purpose is to exit touch mode then we consume it and consider it handled.
2991 if (checkForLeavingTouchModeAndConsume(event)) {
2992 finishKeyEvent(event, sendDone, true);
2993 return;
2994 }
Romain Guy8506ab42009-06-11 17:35:47 -07002995
Joe Onorato43a17652011-04-06 19:22:23 -07002996 if (false) {
Jeff Brown3915bb82010-11-05 15:02:16 -07002997 captureKeyLog("captureDispatchKeyEvent", event);
2998 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002999
Jeff Brown90655042010-12-02 13:50:46 -08003000 // Make sure the fallback event policy sees all keys that will be delivered to the
3001 // view hierarchy.
3002 mFallbackEventHandler.preDispatchKeyEvent(event);
3003
Jeff Brown3915bb82010-11-05 15:02:16 -07003004 // Deliver the key to the view hierarchy.
3005 if (mView.dispatchKeyEvent(event)) {
3006 finishKeyEvent(event, sendDone, true);
3007 return;
3008 }
Joe Onorato86f67862010-11-05 18:57:34 -07003009
Jeff Brownc1df9072010-12-21 16:38:50 -08003010 // If the Control modifier is held, try to interpret the key as a shortcut.
3011 if (event.getAction() == KeyEvent.ACTION_UP
3012 && event.isCtrlPressed()
3013 && !KeyEvent.isModifierKey(event.getKeyCode())) {
3014 if (mView.dispatchKeyShortcutEvent(event)) {
3015 finishKeyEvent(event, sendDone, true);
3016 return;
3017 }
3018 }
3019
Jeff Brown3915bb82010-11-05 15:02:16 -07003020 // Apply the fallback event policy.
3021 if (mFallbackEventHandler.dispatchKeyEvent(event)) {
3022 finishKeyEvent(event, sendDone, true);
3023 return;
3024 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003025
Jeff Brown3915bb82010-11-05 15:02:16 -07003026 // Handle automatic focus changes.
3027 if (event.getAction() == KeyEvent.ACTION_DOWN) {
3028 int direction = 0;
3029 switch (event.getKeyCode()) {
3030 case KeyEvent.KEYCODE_DPAD_LEFT:
Jeff Brown4e6319b2010-12-13 10:36:51 -08003031 if (event.hasNoModifiers()) {
3032 direction = View.FOCUS_LEFT;
3033 }
Jeff Brown3915bb82010-11-05 15:02:16 -07003034 break;
3035 case KeyEvent.KEYCODE_DPAD_RIGHT:
Jeff Brown4e6319b2010-12-13 10:36:51 -08003036 if (event.hasNoModifiers()) {
3037 direction = View.FOCUS_RIGHT;
3038 }
Jeff Brown3915bb82010-11-05 15:02:16 -07003039 break;
3040 case KeyEvent.KEYCODE_DPAD_UP:
Jeff Brown4e6319b2010-12-13 10:36:51 -08003041 if (event.hasNoModifiers()) {
3042 direction = View.FOCUS_UP;
3043 }
Jeff Brown3915bb82010-11-05 15:02:16 -07003044 break;
3045 case KeyEvent.KEYCODE_DPAD_DOWN:
Jeff Brown4e6319b2010-12-13 10:36:51 -08003046 if (event.hasNoModifiers()) {
3047 direction = View.FOCUS_DOWN;
3048 }
3049 break;
3050 case KeyEvent.KEYCODE_TAB:
3051 if (event.hasNoModifiers()) {
3052 direction = View.FOCUS_FORWARD;
3053 } else if (event.hasModifiers(KeyEvent.META_SHIFT_ON)) {
3054 direction = View.FOCUS_BACKWARD;
3055 }
Jeff Brown3915bb82010-11-05 15:02:16 -07003056 break;
3057 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003058
Jeff Brown3915bb82010-11-05 15:02:16 -07003059 if (direction != 0) {
3060 View focused = mView != null ? mView.findFocus() : null;
3061 if (focused != null) {
3062 View v = focused.focusSearch(direction);
3063 if (v != null && v != focused) {
3064 // do the math the get the interesting rect
3065 // of previous focused into the coord system of
3066 // newly focused view
3067 focused.getFocusedRect(mTempRect);
3068 if (mView instanceof ViewGroup) {
3069 ((ViewGroup) mView).offsetDescendantRectToMyCoords(
3070 focused, mTempRect);
3071 ((ViewGroup) mView).offsetRectIntoDescendantCoords(
3072 v, mTempRect);
3073 }
3074 if (v.requestFocus(direction, mTempRect)) {
3075 playSoundEffect(
3076 SoundEffectConstants.getContantForFocusDirection(direction));
3077 finishKeyEvent(event, sendDone, true);
3078 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003079 }
3080 }
Jeff Brown3915bb82010-11-05 15:02:16 -07003081
3082 // Give the focused view a last chance to handle the dpad key.
3083 if (mView.dispatchUnhandledMove(focused, direction)) {
3084 finishKeyEvent(event, sendDone, true);
3085 return;
3086 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003087 }
3088 }
Jeff Brown3915bb82010-11-05 15:02:16 -07003089 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003090
Jeff Brown3915bb82010-11-05 15:02:16 -07003091 // Key was unhandled.
3092 finishKeyEvent(event, sendDone, false);
3093 }
3094
3095 private void finishKeyEvent(KeyEvent event, boolean sendDone, boolean handled) {
3096 if (sendDone) {
Jeff Brown4e91a182011-04-07 11:38:09 -07003097 finishInputEvent(event, handled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003098 }
3099 }
3100
Christopher Tatea53146c2010-09-07 11:57:52 -07003101 /* drag/drop */
Christopher Tate407b4e92010-11-30 17:14:08 -08003102 void setLocalDragState(Object obj) {
3103 mLocalDragState = obj;
3104 }
3105
Christopher Tatea53146c2010-09-07 11:57:52 -07003106 private void handleDragEvent(DragEvent event) {
3107 // From the root, only drag start/end/location are dispatched. entered/exited
3108 // are determined and dispatched by the viewgroup hierarchy, who then report
3109 // that back here for ultimate reporting back to the framework.
3110 if (mView != null && mAdded) {
3111 final int what = event.mAction;
3112
3113 if (what == DragEvent.ACTION_DRAG_EXITED) {
3114 // A direct EXITED event means that the window manager knows we've just crossed
3115 // a window boundary, so the current drag target within this one must have
3116 // just been exited. Send it the usual notifications and then we're done
3117 // for now.
Chris Tate9d1ab882010-11-02 15:55:39 -07003118 mView.dispatchDragEvent(event);
Christopher Tatea53146c2010-09-07 11:57:52 -07003119 } else {
3120 // Cache the drag description when the operation starts, then fill it in
3121 // on subsequent calls as a convenience
3122 if (what == DragEvent.ACTION_DRAG_STARTED) {
Chris Tate9d1ab882010-11-02 15:55:39 -07003123 mCurrentDragView = null; // Start the current-recipient tracking
Christopher Tatea53146c2010-09-07 11:57:52 -07003124 mDragDescription = event.mClipDescription;
3125 } else {
3126 event.mClipDescription = mDragDescription;
3127 }
3128
3129 // For events with a [screen] location, translate into window coordinates
3130 if ((what == DragEvent.ACTION_DRAG_LOCATION) || (what == DragEvent.ACTION_DROP)) {
3131 mDragPoint.set(event.mX, event.mY);
3132 if (mTranslator != null) {
3133 mTranslator.translatePointInScreenToAppWindow(mDragPoint);
3134 }
3135
3136 if (mCurScrollY != 0) {
3137 mDragPoint.offset(0, mCurScrollY);
3138 }
3139
3140 event.mX = mDragPoint.x;
3141 event.mY = mDragPoint.y;
3142 }
3143
3144 // Remember who the current drag target is pre-dispatch
3145 final View prevDragView = mCurrentDragView;
3146
3147 // Now dispatch the drag/drop event
Chris Tated4533f12010-10-19 15:15:08 -07003148 boolean result = mView.dispatchDragEvent(event);
Christopher Tatea53146c2010-09-07 11:57:52 -07003149
3150 // If we changed apparent drag target, tell the OS about it
3151 if (prevDragView != mCurrentDragView) {
3152 try {
3153 if (prevDragView != null) {
3154 sWindowSession.dragRecipientExited(mWindow);
3155 }
3156 if (mCurrentDragView != null) {
3157 sWindowSession.dragRecipientEntered(mWindow);
3158 }
3159 } catch (RemoteException e) {
3160 Slog.e(TAG, "Unable to note drag target change");
3161 }
Christopher Tatea53146c2010-09-07 11:57:52 -07003162 }
Chris Tated4533f12010-10-19 15:15:08 -07003163
Christopher Tate407b4e92010-11-30 17:14:08 -08003164 // Report the drop result when we're done
Chris Tated4533f12010-10-19 15:15:08 -07003165 if (what == DragEvent.ACTION_DROP) {
Christopher Tate1fc014f2011-01-19 12:56:26 -08003166 mDragDescription = null;
Chris Tated4533f12010-10-19 15:15:08 -07003167 try {
3168 Log.i(TAG, "Reporting drop result: " + result);
3169 sWindowSession.reportDropResult(mWindow, result);
3170 } catch (RemoteException e) {
3171 Log.e(TAG, "Unable to report drop result");
3172 }
3173 }
Christopher Tate407b4e92010-11-30 17:14:08 -08003174
3175 // When the drag operation ends, release any local state object
3176 // that may have been in use
3177 if (what == DragEvent.ACTION_DRAG_ENDED) {
3178 setLocalDragState(null);
3179 }
Christopher Tatea53146c2010-09-07 11:57:52 -07003180 }
3181 }
3182 event.recycle();
3183 }
3184
Joe Onorato664644d2011-01-23 17:53:23 -08003185 public void handleDispatchSystemUiVisibilityChanged(int visibility) {
3186 if (mView == null) return;
Joe Onorato14782f72011-01-25 19:53:17 -08003187 if (mAttachInfo != null) {
3188 mAttachInfo.mSystemUiVisibility = visibility;
3189 }
Joe Onorato664644d2011-01-23 17:53:23 -08003190 mView.dispatchSystemUiVisibilityChanged(visibility);
3191 }
3192
Christopher Tate2c095f32010-10-04 14:13:40 -07003193 public void getLastTouchPoint(Point outLocation) {
3194 outLocation.x = (int) mLastTouchPoint.x;
3195 outLocation.y = (int) mLastTouchPoint.y;
3196 }
3197
Chris Tate9d1ab882010-11-02 15:55:39 -07003198 public void setDragFocus(View newDragTarget) {
Christopher Tatea53146c2010-09-07 11:57:52 -07003199 if (mCurrentDragView != newDragTarget) {
Chris Tate048691c2010-10-12 17:39:18 -07003200 mCurrentDragView = newDragTarget;
Christopher Tatea53146c2010-09-07 11:57:52 -07003201 }
Christopher Tatea53146c2010-09-07 11:57:52 -07003202 }
3203
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003204 private AudioManager getAudioManager() {
3205 if (mView == null) {
3206 throw new IllegalStateException("getAudioManager called when there is no mView");
3207 }
3208 if (mAudioManager == null) {
3209 mAudioManager = (AudioManager) mView.getContext().getSystemService(Context.AUDIO_SERVICE);
3210 }
3211 return mAudioManager;
3212 }
3213
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07003214 private int relayoutWindow(WindowManager.LayoutParams params, int viewVisibility,
3215 boolean insetsPending) throws RemoteException {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07003216
3217 float appScale = mAttachInfo.mApplicationScale;
Mitsuru Oshima3d914922009-05-13 22:29:15 -07003218 boolean restore = false;
Mitsuru Oshima64f59342009-06-21 00:03:11 -07003219 if (params != null && mTranslator != null) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07003220 restore = true;
3221 params.backup();
Mitsuru Oshima64f59342009-06-21 00:03:11 -07003222 mTranslator.translateWindowLayout(params);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07003223 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07003224 if (params != null) {
3225 if (DBG) Log.d(TAG, "WindowLayout in layoutWindow:" + params);
Mitsuru Oshima3d914922009-05-13 22:29:15 -07003226 }
Dianne Hackborn694f79b2010-03-17 19:44:59 -07003227 mPendingConfiguration.seq = 0;
Dianne Hackbornf123e492010-09-24 11:16:23 -07003228 //Log.d(TAG, ">>>>>> CALLING relayout");
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07003229 int relayoutResult = sWindowSession.relayout(
3230 mWindow, params,
Dianne Hackborn189ee182010-12-02 21:48:53 -08003231 (int) (mView.getMeasuredWidth() * appScale + 0.5f),
3232 (int) (mView.getMeasuredHeight() * appScale + 0.5f),
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07003233 viewVisibility, insetsPending, mWinFrame,
Dianne Hackborn694f79b2010-03-17 19:44:59 -07003234 mPendingContentInsets, mPendingVisibleInsets,
3235 mPendingConfiguration, mSurface);
Dianne Hackbornf123e492010-09-24 11:16:23 -07003236 //Log.d(TAG, "<<<<<< BACK FROM relayout");
Mitsuru Oshima3d914922009-05-13 22:29:15 -07003237 if (restore) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07003238 params.restore();
Mitsuru Oshima3d914922009-05-13 22:29:15 -07003239 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07003240
3241 if (mTranslator != null) {
3242 mTranslator.translateRectInScreenToAppWinFrame(mWinFrame);
3243 mTranslator.translateRectInScreenToAppWindow(mPendingContentInsets);
3244 mTranslator.translateRectInScreenToAppWindow(mPendingVisibleInsets);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07003245 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07003246 return relayoutResult;
3247 }
Romain Guy8506ab42009-06-11 17:35:47 -07003248
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07003249 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003250 * {@inheritDoc}
3251 */
3252 public void playSoundEffect(int effectId) {
3253 checkThread();
3254
Jean-Michel Trivi13b18fd2010-05-05 09:18:15 -07003255 try {
3256 final AudioManager audioManager = getAudioManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003257
Jean-Michel Trivi13b18fd2010-05-05 09:18:15 -07003258 switch (effectId) {
3259 case SoundEffectConstants.CLICK:
3260 audioManager.playSoundEffect(AudioManager.FX_KEY_CLICK);
3261 return;
3262 case SoundEffectConstants.NAVIGATION_DOWN:
3263 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_DOWN);
3264 return;
3265 case SoundEffectConstants.NAVIGATION_LEFT:
3266 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_LEFT);
3267 return;
3268 case SoundEffectConstants.NAVIGATION_RIGHT:
3269 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_RIGHT);
3270 return;
3271 case SoundEffectConstants.NAVIGATION_UP:
3272 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_UP);
3273 return;
3274 default:
3275 throw new IllegalArgumentException("unknown effect id " + effectId +
3276 " not defined in " + SoundEffectConstants.class.getCanonicalName());
3277 }
3278 } catch (IllegalStateException e) {
3279 // Exception thrown by getAudioManager() when mView is null
3280 Log.e(TAG, "FATAL EXCEPTION when attempting to play sound effect: " + e);
3281 e.printStackTrace();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003282 }
3283 }
3284
3285 /**
3286 * {@inheritDoc}
3287 */
3288 public boolean performHapticFeedback(int effectId, boolean always) {
3289 try {
3290 return sWindowSession.performHapticFeedback(mWindow, effectId, always);
3291 } catch (RemoteException e) {
3292 return false;
3293 }
3294 }
3295
3296 /**
3297 * {@inheritDoc}
3298 */
3299 public View focusSearch(View focused, int direction) {
3300 checkThread();
3301 if (!(mView instanceof ViewGroup)) {
3302 return null;
3303 }
3304 return FocusFinder.getInstance().findNextFocus((ViewGroup) mView, focused, direction);
3305 }
3306
3307 public void debug() {
3308 mView.debug();
3309 }
3310
3311 public void die(boolean immediate) {
Dianne Hackborn94d69142009-09-28 22:14:42 -07003312 if (immediate) {
3313 doDie();
3314 } else {
3315 sendEmptyMessage(DIE);
3316 }
3317 }
3318
3319 void doDie() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003320 checkThread();
Jeff Brownb75fa302010-07-15 23:47:29 -07003321 if (LOCAL_LOGV) Log.v(TAG, "DIE in " + this + " of " + mSurface);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003322 synchronized (this) {
3323 if (mAdded && !mFirst) {
Romain Guy29d89972010-09-22 16:10:57 -07003324 destroyHardwareRenderer();
3325
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003326 int viewVisibility = mView.getVisibility();
3327 boolean viewVisibilityChanged = mViewVisibility != viewVisibility;
3328 if (mWindowAttributesChanged || viewVisibilityChanged) {
3329 // If layout params have been changed, first give them
3330 // to the window manager to make sure it has the correct
3331 // animation info.
3332 try {
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07003333 if ((relayoutWindow(mWindowAttributes, viewVisibility, false)
3334 & WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003335 sWindowSession.finishDrawing(mWindow);
3336 }
3337 } catch (RemoteException e) {
3338 }
3339 }
3340
Dianne Hackborn0586a1b2009-09-06 21:08:27 -07003341 mSurface.release();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003342 }
3343 if (mAdded) {
3344 mAdded = false;
Dianne Hackborn94d69142009-09-28 22:14:42 -07003345 dispatchDetachedFromWindow();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003346 }
3347 }
3348 }
3349
Romain Guy29d89972010-09-22 16:10:57 -07003350 private void destroyHardwareRenderer() {
Romain Guyb051e892010-09-28 19:09:36 -07003351 if (mAttachInfo.mHardwareRenderer != null) {
3352 mAttachInfo.mHardwareRenderer.destroy(true);
3353 mAttachInfo.mHardwareRenderer = null;
Romain Guy29d89972010-09-22 16:10:57 -07003354 mAttachInfo.mHardwareAccelerated = false;
3355 }
3356 }
3357
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003358 public void dispatchFinishedEvent(int seq, boolean handled) {
3359 Message msg = obtainMessage(FINISHED_EVENT);
3360 msg.arg1 = seq;
3361 msg.arg2 = handled ? 1 : 0;
3362 sendMessage(msg);
3363 }
Mitsuru Oshima3d914922009-05-13 22:29:15 -07003364
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003365 public void dispatchResized(int w, int h, Rect coveredInsets,
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003366 Rect visibleInsets, boolean reportDraw, Configuration newConfig) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003367 if (DEBUG_LAYOUT) Log.v(TAG, "Resizing " + this + ": w=" + w
3368 + " h=" + h + " coveredInsets=" + coveredInsets.toShortString()
3369 + " visibleInsets=" + visibleInsets.toShortString()
3370 + " reportDraw=" + reportDraw);
3371 Message msg = obtainMessage(reportDraw ? RESIZED_REPORT :RESIZED);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07003372 if (mTranslator != null) {
3373 mTranslator.translateRectInScreenToAppWindow(coveredInsets);
3374 mTranslator.translateRectInScreenToAppWindow(visibleInsets);
3375 w *= mTranslator.applicationInvertedScale;
3376 h *= mTranslator.applicationInvertedScale;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07003377 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07003378 msg.arg1 = w;
3379 msg.arg2 = h;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003380 ResizedInfo ri = new ResizedInfo();
3381 ri.coveredInsets = new Rect(coveredInsets);
3382 ri.visibleInsets = new Rect(visibleInsets);
3383 ri.newConfig = newConfig;
3384 msg.obj = ri;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003385 sendMessage(msg);
3386 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07003387
Jeff Brown4e91a182011-04-07 11:38:09 -07003388 private long mInputEventReceiveTimeNanos;
3389 private long mInputEventDeliverTimeNanos;
3390 private long mInputEventDeliverPostImeTimeNanos;
Jeff Brown3915bb82010-11-05 15:02:16 -07003391 private InputQueue.FinishedCallback mFinishedCallback;
Jeff Brown46b9ac02010-04-22 18:58:52 -07003392
3393 private final InputHandler mInputHandler = new InputHandler() {
Jeff Brown3915bb82010-11-05 15:02:16 -07003394 public void handleKey(KeyEvent event, InputQueue.FinishedCallback finishedCallback) {
Jeff Brown4e91a182011-04-07 11:38:09 -07003395 startInputEvent(event, finishedCallback);
Jeff Brown92ff1dd2010-08-11 16:16:06 -07003396 dispatchKey(event, true);
Jeff Brown46b9ac02010-04-22 18:58:52 -07003397 }
3398
Jeff Brown3915bb82010-11-05 15:02:16 -07003399 public void handleMotion(MotionEvent event, InputQueue.FinishedCallback finishedCallback) {
Jeff Brown4e91a182011-04-07 11:38:09 -07003400 startInputEvent(event, finishedCallback);
Jeff Brown93ed4e32010-09-23 13:51:48 -07003401 dispatchMotion(event, true);
Jeff Brown46b9ac02010-04-22 18:58:52 -07003402 }
3403 };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003404
3405 public void dispatchKey(KeyEvent event) {
Jeff Brown92ff1dd2010-08-11 16:16:06 -07003406 dispatchKey(event, false);
3407 }
3408
3409 private void dispatchKey(KeyEvent event, boolean sendDone) {
3410 //noinspection ConstantConditions
3411 if (false && event.getAction() == KeyEvent.ACTION_DOWN) {
3412 if (event.getKeyCode() == KeyEvent.KEYCODE_CAMERA) {
Romain Guy812ccbe2010-06-01 14:07:24 -07003413 if (DBG) Log.d("keydisp", "===================================================");
3414 if (DBG) Log.d("keydisp", "Focused view Hierarchy is:");
3415
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003416 debug();
3417
Romain Guy812ccbe2010-06-01 14:07:24 -07003418 if (DBG) Log.d("keydisp", "===================================================");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003419 }
3420 }
3421
3422 Message msg = obtainMessage(DISPATCH_KEY);
3423 msg.obj = event;
Jeff Brown92ff1dd2010-08-11 16:16:06 -07003424 msg.arg1 = sendDone ? 1 : 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003425
3426 if (LOCAL_LOGV) Log.v(
Jeff Brownc5ed5912010-07-14 18:48:53 -07003427 TAG, "sending key " + event + " to " + mView);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003428
3429 sendMessageAtTime(msg, event.getEventTime());
3430 }
Jeff Brownc5ed5912010-07-14 18:48:53 -07003431
3432 public void dispatchMotion(MotionEvent event) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07003433 dispatchMotion(event, false);
3434 }
3435
3436 private void dispatchMotion(MotionEvent event, boolean sendDone) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07003437 int source = event.getSource();
3438 if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07003439 dispatchPointer(event, sendDone);
Jeff Brownc5ed5912010-07-14 18:48:53 -07003440 } else if ((source & InputDevice.SOURCE_CLASS_TRACKBALL) != 0) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07003441 dispatchTrackball(event, sendDone);
Jeff Brownc5ed5912010-07-14 18:48:53 -07003442 } else {
Jeff Browncb1404e2011-01-15 18:14:15 -08003443 dispatchGenericMotion(event, sendDone);
Jeff Brownc5ed5912010-07-14 18:48:53 -07003444 }
3445 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003446
Jeff Brown00fa7bd2010-07-02 15:37:36 -07003447 public void dispatchPointer(MotionEvent event) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07003448 dispatchPointer(event, false);
3449 }
3450
3451 private void dispatchPointer(MotionEvent event, boolean sendDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003452 Message msg = obtainMessage(DISPATCH_POINTER);
3453 msg.obj = event;
Jeff Brown93ed4e32010-09-23 13:51:48 -07003454 msg.arg1 = sendDone ? 1 : 0;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07003455 sendMessageAtTime(msg, event.getEventTime());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003456 }
3457
Jeff Brown00fa7bd2010-07-02 15:37:36 -07003458 public void dispatchTrackball(MotionEvent event) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07003459 dispatchTrackball(event, false);
3460 }
3461
3462 private void dispatchTrackball(MotionEvent event, boolean sendDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003463 Message msg = obtainMessage(DISPATCH_TRACKBALL);
3464 msg.obj = event;
Jeff Brown93ed4e32010-09-23 13:51:48 -07003465 msg.arg1 = sendDone ? 1 : 0;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07003466 sendMessageAtTime(msg, event.getEventTime());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003467 }
Jeff Browncb1404e2011-01-15 18:14:15 -08003468
3469 private void dispatchGenericMotion(MotionEvent event, boolean sendDone) {
3470 Message msg = obtainMessage(DISPATCH_GENERIC_MOTION);
3471 msg.obj = event;
3472 msg.arg1 = sendDone ? 1 : 0;
3473 sendMessageAtTime(msg, event.getEventTime());
3474 }
3475
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003476 public void dispatchAppVisibility(boolean visible) {
3477 Message msg = obtainMessage(DISPATCH_APP_VISIBILITY);
3478 msg.arg1 = visible ? 1 : 0;
3479 sendMessage(msg);
3480 }
3481
3482 public void dispatchGetNewSurface() {
3483 Message msg = obtainMessage(DISPATCH_GET_NEW_SURFACE);
3484 sendMessage(msg);
3485 }
3486
3487 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
3488 Message msg = Message.obtain();
3489 msg.what = WINDOW_FOCUS_CHANGED;
3490 msg.arg1 = hasFocus ? 1 : 0;
3491 msg.arg2 = inTouchMode ? 1 : 0;
3492 sendMessage(msg);
3493 }
3494
Dianne Hackbornffa42482009-09-23 22:20:11 -07003495 public void dispatchCloseSystemDialogs(String reason) {
3496 Message msg = Message.obtain();
3497 msg.what = CLOSE_SYSTEM_DIALOGS;
3498 msg.obj = reason;
3499 sendMessage(msg);
3500 }
Christopher Tatea53146c2010-09-07 11:57:52 -07003501
3502 public void dispatchDragEvent(DragEvent event) {
Chris Tate91e9bb32010-10-12 12:58:43 -07003503 final int what;
3504 if (event.getAction() == DragEvent.ACTION_DRAG_LOCATION) {
3505 what = DISPATCH_DRAG_LOCATION_EVENT;
3506 removeMessages(what);
3507 } else {
3508 what = DISPATCH_DRAG_EVENT;
3509 }
3510 Message msg = obtainMessage(what, event);
Christopher Tatea53146c2010-09-07 11:57:52 -07003511 sendMessage(msg);
3512 }
3513
Joe Onorato664644d2011-01-23 17:53:23 -08003514 public void dispatchSystemUiVisibilityChanged(int visibility) {
3515 sendMessage(obtainMessage(DISPATCH_SYSTEM_UI_VISIBILITY, visibility, 0));
3516 }
3517
svetoslavganov75986cf2009-05-14 22:28:01 -07003518 /**
3519 * The window is getting focus so if there is anything focused/selected
3520 * send an {@link AccessibilityEvent} to announce that.
3521 */
3522 private void sendAccessibilityEvents() {
3523 if (!AccessibilityManager.getInstance(mView.getContext()).isEnabled()) {
3524 return;
3525 }
3526 mView.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
3527 View focusedView = mView.findFocus();
3528 if (focusedView != null && focusedView != mView) {
3529 focusedView.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
3530 }
3531 }
3532
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003533 public boolean showContextMenuForChild(View originalView) {
3534 return false;
3535 }
3536
Adam Powell6e346362010-07-23 10:18:23 -07003537 public ActionMode startActionModeForChild(View originalView, ActionMode.Callback callback) {
3538 return null;
3539 }
3540
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003541 public void createContextMenu(ContextMenu menu) {
3542 }
3543
3544 public void childDrawableStateChanged(View child) {
3545 }
3546
Svetoslav Ganov736c2752011-04-22 18:30:36 -07003547 public boolean requestSendAccessibilityEvent(View child, AccessibilityEvent event) {
3548 if (mView == null) {
3549 return false;
3550 }
3551 AccessibilityManager.getInstance(child.mContext).sendAccessibilityEvent(event);
3552 return true;
3553 }
3554
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003555 void checkThread() {
3556 if (mThread != Thread.currentThread()) {
3557 throw new CalledFromWrongThreadException(
3558 "Only the original thread that created a view hierarchy can touch its views.");
3559 }
3560 }
3561
3562 public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
Joe Onoratoc6cc0f82011-04-12 11:53:13 -07003563 // ViewAncestor never intercepts touch event, so this can be a no-op
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003564 }
3565
3566 public boolean requestChildRectangleOnScreen(View child, Rect rectangle,
3567 boolean immediate) {
3568 return scrollToRectOrFocus(rectangle, immediate);
3569 }
Romain Guy8506ab42009-06-11 17:35:47 -07003570
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07003571 class TakenSurfaceHolder extends BaseSurfaceHolder {
3572 @Override
3573 public boolean onAllowLockCanvas() {
3574 return mDrawingAllowed;
3575 }
3576
3577 @Override
3578 public void onRelayoutContainer() {
3579 // Not currently interesting -- from changing between fixed and layout size.
3580 }
3581
3582 public void setFormat(int format) {
3583 ((RootViewSurfaceTaker)mView).setSurfaceFormat(format);
3584 }
3585
3586 public void setType(int type) {
3587 ((RootViewSurfaceTaker)mView).setSurfaceType(type);
3588 }
3589
3590 @Override
3591 public void onUpdateSurface() {
3592 // We take care of format and type changes on our own.
3593 throw new IllegalStateException("Shouldn't be here");
3594 }
3595
3596 public boolean isCreating() {
3597 return mIsCreating;
3598 }
3599
3600 @Override
3601 public void setFixedSize(int width, int height) {
3602 throw new UnsupportedOperationException(
3603 "Currently only support sizing from layout");
3604 }
3605
3606 public void setKeepScreenOn(boolean screenOn) {
3607 ((RootViewSurfaceTaker)mView).setSurfaceKeepScreenOn(screenOn);
3608 }
3609 }
3610
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003611 static class InputMethodCallback extends IInputMethodCallback.Stub {
Joe Onoratoc6cc0f82011-04-12 11:53:13 -07003612 private WeakReference<ViewAncestor> mViewAncestor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003613
Joe Onoratoc6cc0f82011-04-12 11:53:13 -07003614 public InputMethodCallback(ViewAncestor viewRoot) {
3615 mViewAncestor = new WeakReference<ViewAncestor>(viewRoot);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003616 }
Romain Guy8506ab42009-06-11 17:35:47 -07003617
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003618 public void finishedEvent(int seq, boolean handled) {
Joe Onoratoc6cc0f82011-04-12 11:53:13 -07003619 final ViewAncestor viewRoot = mViewAncestor.get();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003620 if (viewRoot != null) {
3621 viewRoot.dispatchFinishedEvent(seq, handled);
3622 }
3623 }
3624
3625 public void sessionCreated(IInputMethodSession session) throws RemoteException {
3626 // Stub -- not for use in the client.
3627 }
3628 }
Romain Guy8506ab42009-06-11 17:35:47 -07003629
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003630 static class W extends IWindow.Stub {
Joe Onoratoc6cc0f82011-04-12 11:53:13 -07003631 private final WeakReference<ViewAncestor> mViewAncestor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003632
Joe Onoratoc6cc0f82011-04-12 11:53:13 -07003633 W(ViewAncestor viewRoot) {
3634 mViewAncestor = new WeakReference<ViewAncestor>(viewRoot);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003635 }
3636
Romain Guyfb8b7632010-08-23 21:05:08 -07003637 public void resized(int w, int h, Rect coveredInsets, Rect visibleInsets,
3638 boolean reportDraw, Configuration newConfig) {
Joe Onoratoc6cc0f82011-04-12 11:53:13 -07003639 final ViewAncestor viewRoot = mViewAncestor.get();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003640 if (viewRoot != null) {
Romain Guyfb8b7632010-08-23 21:05:08 -07003641 viewRoot.dispatchResized(w, h, coveredInsets, visibleInsets, reportDraw, newConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003642 }
3643 }
3644
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003645 public void dispatchAppVisibility(boolean visible) {
Joe Onoratoc6cc0f82011-04-12 11:53:13 -07003646 final ViewAncestor viewRoot = mViewAncestor.get();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003647 if (viewRoot != null) {
3648 viewRoot.dispatchAppVisibility(visible);
3649 }
3650 }
3651
3652 public void dispatchGetNewSurface() {
Joe Onoratoc6cc0f82011-04-12 11:53:13 -07003653 final ViewAncestor viewRoot = mViewAncestor.get();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003654 if (viewRoot != null) {
3655 viewRoot.dispatchGetNewSurface();
3656 }
3657 }
3658
3659 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
Joe Onoratoc6cc0f82011-04-12 11:53:13 -07003660 final ViewAncestor viewRoot = mViewAncestor.get();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003661 if (viewRoot != null) {
3662 viewRoot.windowFocusChanged(hasFocus, inTouchMode);
3663 }
3664 }
3665
3666 private static int checkCallingPermission(String permission) {
3667 if (!Process.supportsProcesses()) {
3668 return PackageManager.PERMISSION_GRANTED;
3669 }
3670
3671 try {
3672 return ActivityManagerNative.getDefault().checkPermission(
3673 permission, Binder.getCallingPid(), Binder.getCallingUid());
3674 } catch (RemoteException e) {
3675 return PackageManager.PERMISSION_DENIED;
3676 }
3677 }
3678
3679 public void executeCommand(String command, String parameters, ParcelFileDescriptor out) {
Joe Onoratoc6cc0f82011-04-12 11:53:13 -07003680 final ViewAncestor viewRoot = mViewAncestor.get();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003681 if (viewRoot != null) {
3682 final View view = viewRoot.mView;
3683 if (view != null) {
3684 if (checkCallingPermission(Manifest.permission.DUMP) !=
3685 PackageManager.PERMISSION_GRANTED) {
3686 throw new SecurityException("Insufficient permissions to invoke"
3687 + " executeCommand() from pid=" + Binder.getCallingPid()
3688 + ", uid=" + Binder.getCallingUid());
3689 }
3690
3691 OutputStream clientStream = null;
3692 try {
3693 clientStream = new ParcelFileDescriptor.AutoCloseOutputStream(out);
3694 ViewDebug.dispatchCommand(view, command, parameters, clientStream);
3695 } catch (IOException e) {
3696 e.printStackTrace();
3697 } finally {
3698 if (clientStream != null) {
3699 try {
3700 clientStream.close();
3701 } catch (IOException e) {
3702 e.printStackTrace();
3703 }
3704 }
3705 }
3706 }
3707 }
3708 }
Dianne Hackborn72c82ab2009-08-11 21:13:54 -07003709
Dianne Hackbornffa42482009-09-23 22:20:11 -07003710 public void closeSystemDialogs(String reason) {
Joe Onoratoc6cc0f82011-04-12 11:53:13 -07003711 final ViewAncestor viewRoot = mViewAncestor.get();
Dianne Hackbornffa42482009-09-23 22:20:11 -07003712 if (viewRoot != null) {
3713 viewRoot.dispatchCloseSystemDialogs(reason);
3714 }
3715 }
3716
Marco Nelissenbf6956b2009-11-09 15:21:13 -08003717 public void dispatchWallpaperOffsets(float x, float y, float xStep, float yStep,
3718 boolean sync) {
Dianne Hackborn19382ac2009-09-11 21:13:37 -07003719 if (sync) {
3720 try {
3721 sWindowSession.wallpaperOffsetsComplete(asBinder());
3722 } catch (RemoteException e) {
3723 }
3724 }
Dianne Hackborn72c82ab2009-08-11 21:13:54 -07003725 }
Dianne Hackborn75804932009-10-20 20:15:20 -07003726
3727 public void dispatchWallpaperCommand(String action, int x, int y,
3728 int z, Bundle extras, boolean sync) {
3729 if (sync) {
3730 try {
3731 sWindowSession.wallpaperCommandComplete(asBinder(), null);
3732 } catch (RemoteException e) {
3733 }
3734 }
3735 }
Christopher Tatea53146c2010-09-07 11:57:52 -07003736
3737 /* Drag/drop */
3738 public void dispatchDragEvent(DragEvent event) {
Joe Onoratoc6cc0f82011-04-12 11:53:13 -07003739 final ViewAncestor viewRoot = mViewAncestor.get();
Christopher Tatea53146c2010-09-07 11:57:52 -07003740 if (viewRoot != null) {
3741 viewRoot.dispatchDragEvent(event);
3742 }
3743 }
Joe Onorato664644d2011-01-23 17:53:23 -08003744
3745 @Override
3746 public void dispatchSystemUiVisibilityChanged(int visibility) {
Joe Onoratoc6cc0f82011-04-12 11:53:13 -07003747 final ViewAncestor viewRoot = mViewAncestor.get();
Joe Onorato664644d2011-01-23 17:53:23 -08003748 if (viewRoot != null) {
3749 viewRoot.dispatchSystemUiVisibilityChanged(visibility);
3750 }
3751 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003752 }
3753
3754 /**
3755 * Maintains state information for a single trackball axis, generating
3756 * discrete (DPAD) movements based on raw trackball motion.
3757 */
3758 static final class TrackballAxis {
3759 /**
3760 * The maximum amount of acceleration we will apply.
3761 */
3762 static final float MAX_ACCELERATION = 20;
Romain Guy8506ab42009-06-11 17:35:47 -07003763
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003764 /**
3765 * The maximum amount of time (in milliseconds) between events in order
3766 * for us to consider the user to be doing fast trackball movements,
3767 * and thus apply an acceleration.
3768 */
3769 static final long FAST_MOVE_TIME = 150;
Romain Guy8506ab42009-06-11 17:35:47 -07003770
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003771 /**
3772 * Scaling factor to the time (in milliseconds) between events to how
3773 * much to multiple/divide the current acceleration. When movement
3774 * is < FAST_MOVE_TIME this multiplies the acceleration; when >
3775 * FAST_MOVE_TIME it divides it.
3776 */
3777 static final float ACCEL_MOVE_SCALING_FACTOR = (1.0f/40);
Romain Guy8506ab42009-06-11 17:35:47 -07003778
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003779 float position;
3780 float absPosition;
3781 float acceleration = 1;
3782 long lastMoveTime = 0;
3783 int step;
3784 int dir;
3785 int nonAccelMovement;
3786
3787 void reset(int _step) {
3788 position = 0;
3789 acceleration = 1;
3790 lastMoveTime = 0;
3791 step = _step;
3792 dir = 0;
3793 }
3794
3795 /**
3796 * Add trackball movement into the state. If the direction of movement
3797 * has been reversed, the state is reset before adding the
3798 * movement (so that you don't have to compensate for any previously
3799 * collected movement before see the result of the movement in the
3800 * new direction).
3801 *
3802 * @return Returns the absolute value of the amount of movement
3803 * collected so far.
3804 */
3805 float collect(float off, long time, String axis) {
3806 long normTime;
3807 if (off > 0) {
3808 normTime = (long)(off * FAST_MOVE_TIME);
3809 if (dir < 0) {
3810 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to positive!");
3811 position = 0;
3812 step = 0;
3813 acceleration = 1;
3814 lastMoveTime = 0;
3815 }
3816 dir = 1;
3817 } else if (off < 0) {
3818 normTime = (long)((-off) * FAST_MOVE_TIME);
3819 if (dir > 0) {
3820 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to negative!");
3821 position = 0;
3822 step = 0;
3823 acceleration = 1;
3824 lastMoveTime = 0;
3825 }
3826 dir = -1;
3827 } else {
3828 normTime = 0;
3829 }
Romain Guy8506ab42009-06-11 17:35:47 -07003830
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003831 // The number of milliseconds between each movement that is
3832 // considered "normal" and will not result in any acceleration
3833 // or deceleration, scaled by the offset we have here.
3834 if (normTime > 0) {
3835 long delta = time - lastMoveTime;
3836 lastMoveTime = time;
3837 float acc = acceleration;
3838 if (delta < normTime) {
3839 // The user is scrolling rapidly, so increase acceleration.
3840 float scale = (normTime-delta) * ACCEL_MOVE_SCALING_FACTOR;
3841 if (scale > 1) acc *= scale;
3842 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " accelerate: off="
3843 + off + " normTime=" + normTime + " delta=" + delta
3844 + " scale=" + scale + " acc=" + acc);
3845 acceleration = acc < MAX_ACCELERATION ? acc : MAX_ACCELERATION;
3846 } else {
3847 // The user is scrolling slowly, so decrease acceleration.
3848 float scale = (delta-normTime) * ACCEL_MOVE_SCALING_FACTOR;
3849 if (scale > 1) acc /= scale;
3850 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " deccelerate: off="
3851 + off + " normTime=" + normTime + " delta=" + delta
3852 + " scale=" + scale + " acc=" + acc);
3853 acceleration = acc > 1 ? acc : 1;
3854 }
3855 }
3856 position += off;
3857 return (absPosition = Math.abs(position));
3858 }
3859
3860 /**
3861 * Generate the number of discrete movement events appropriate for
3862 * the currently collected trackball movement.
3863 *
3864 * @param precision The minimum movement required to generate the
3865 * first discrete movement.
3866 *
3867 * @return Returns the number of discrete movements, either positive
3868 * or negative, or 0 if there is not enough trackball movement yet
3869 * for a discrete movement.
3870 */
3871 int generate(float precision) {
3872 int movement = 0;
3873 nonAccelMovement = 0;
3874 do {
3875 final int dir = position >= 0 ? 1 : -1;
3876 switch (step) {
3877 // If we are going to execute the first step, then we want
3878 // to do this as soon as possible instead of waiting for
3879 // a full movement, in order to make things look responsive.
3880 case 0:
3881 if (absPosition < precision) {
3882 return movement;
3883 }
3884 movement += dir;
3885 nonAccelMovement += dir;
3886 step = 1;
3887 break;
3888 // If we have generated the first movement, then we need
3889 // to wait for the second complete trackball motion before
3890 // generating the second discrete movement.
3891 case 1:
3892 if (absPosition < 2) {
3893 return movement;
3894 }
3895 movement += dir;
3896 nonAccelMovement += dir;
3897 position += dir > 0 ? -2 : 2;
3898 absPosition = Math.abs(position);
3899 step = 2;
3900 break;
3901 // After the first two, we generate discrete movements
3902 // consistently with the trackball, applying an acceleration
3903 // if the trackball is moving quickly. This is a simple
3904 // acceleration on top of what we already compute based
3905 // on how quickly the wheel is being turned, to apply
3906 // a longer increasing acceleration to continuous movement
3907 // in one direction.
3908 default:
3909 if (absPosition < 1) {
3910 return movement;
3911 }
3912 movement += dir;
3913 position += dir >= 0 ? -1 : 1;
3914 absPosition = Math.abs(position);
3915 float acc = acceleration;
3916 acc *= 1.1f;
3917 acceleration = acc < MAX_ACCELERATION ? acc : acceleration;
3918 break;
3919 }
3920 } while (true);
3921 }
3922 }
3923
3924 public static final class CalledFromWrongThreadException extends AndroidRuntimeException {
3925 public CalledFromWrongThreadException(String msg) {
3926 super(msg);
3927 }
3928 }
3929
3930 private SurfaceHolder mHolder = new SurfaceHolder() {
3931 // we only need a SurfaceHolder for opengl. it would be nice
3932 // to implement everything else though, especially the callback
3933 // support (opengl doesn't make use of it right now, but eventually
3934 // will).
3935 public Surface getSurface() {
3936 return mSurface;
3937 }
3938
3939 public boolean isCreating() {
3940 return false;
3941 }
3942
3943 public void addCallback(Callback callback) {
3944 }
3945
3946 public void removeCallback(Callback callback) {
3947 }
3948
3949 public void setFixedSize(int width, int height) {
3950 }
3951
3952 public void setSizeFromLayout() {
3953 }
3954
3955 public void setFormat(int format) {
3956 }
3957
3958 public void setType(int type) {
3959 }
3960
3961 public void setKeepScreenOn(boolean screenOn) {
3962 }
3963
3964 public Canvas lockCanvas() {
3965 return null;
3966 }
3967
3968 public Canvas lockCanvas(Rect dirty) {
3969 return null;
3970 }
3971
3972 public void unlockCanvasAndPost(Canvas canvas) {
3973 }
3974 public Rect getSurfaceFrame() {
3975 return null;
3976 }
3977 };
3978
3979 static RunQueue getRunQueue() {
3980 RunQueue rq = sRunQueues.get();
3981 if (rq != null) {
3982 return rq;
3983 }
3984 rq = new RunQueue();
3985 sRunQueues.set(rq);
3986 return rq;
3987 }
Romain Guy8506ab42009-06-11 17:35:47 -07003988
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003989 /**
3990 * @hide
3991 */
3992 static final class RunQueue {
3993 private final ArrayList<HandlerAction> mActions = new ArrayList<HandlerAction>();
3994
3995 void post(Runnable action) {
3996 postDelayed(action, 0);
3997 }
3998
3999 void postDelayed(Runnable action, long delayMillis) {
4000 HandlerAction handlerAction = new HandlerAction();
4001 handlerAction.action = action;
4002 handlerAction.delay = delayMillis;
4003
4004 synchronized (mActions) {
4005 mActions.add(handlerAction);
4006 }
4007 }
4008
4009 void removeCallbacks(Runnable action) {
4010 final HandlerAction handlerAction = new HandlerAction();
4011 handlerAction.action = action;
4012
4013 synchronized (mActions) {
4014 final ArrayList<HandlerAction> actions = mActions;
4015
4016 while (actions.remove(handlerAction)) {
4017 // Keep going
4018 }
4019 }
4020 }
4021
4022 void executeActions(Handler handler) {
4023 synchronized (mActions) {
4024 final ArrayList<HandlerAction> actions = mActions;
4025 final int count = actions.size();
4026
4027 for (int i = 0; i < count; i++) {
4028 final HandlerAction handlerAction = actions.get(i);
4029 handler.postDelayed(handlerAction.action, handlerAction.delay);
4030 }
4031
Romain Guy15df6702009-08-17 20:17:30 -07004032 actions.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004033 }
4034 }
4035
4036 private static class HandlerAction {
4037 Runnable action;
4038 long delay;
4039
4040 @Override
4041 public boolean equals(Object o) {
4042 if (this == o) return true;
4043 if (o == null || getClass() != o.getClass()) return false;
4044
4045 HandlerAction that = (HandlerAction) o;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004046 return !(action != null ? !action.equals(that.action) : that.action != null);
4047
4048 }
4049
4050 @Override
4051 public int hashCode() {
4052 int result = action != null ? action.hashCode() : 0;
4053 result = 31 * result + (int) (delay ^ (delay >>> 32));
4054 return result;
4055 }
4056 }
4057 }
4058
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004059 private static native void nativeShowFPS(Canvas canvas, int durationMillis);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004060}