blob: b21af410b3069d3458785b1f73ed63096f458ecd [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.view;
18
Romain Guy6b7bd242010-10-06 19:49:23 -070019import android.Manifest;
20import android.app.ActivityManagerNative;
21import android.content.ClipDescription;
22import android.content.ComponentCallbacks;
23import android.content.Context;
24import android.content.pm.PackageManager;
25import android.content.res.CompatibilityInfo;
26import android.content.res.Configuration;
27import android.content.res.Resources;
Dianne Hackborn0f761d62010-11-30 22:06:10 -080028import android.graphics.Bitmap;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080029import android.graphics.Canvas;
Dianne Hackborn0f761d62010-11-30 22:06:10 -080030import android.graphics.Paint;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080031import android.graphics.PixelFormat;
Christopher Tate2c095f32010-10-04 14:13:40 -070032import android.graphics.Point;
Christopher Tatea53146c2010-09-07 11:57:52 -070033import android.graphics.PointF;
Romain Guy6b7bd242010-10-06 19:49:23 -070034import android.graphics.PorterDuff;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080035import android.graphics.Rect;
36import android.graphics.Region;
Romain Guy6b7bd242010-10-06 19:49:23 -070037import android.media.AudioManager;
38import android.os.Binder;
39import android.os.Bundle;
40import android.os.Debug;
41import android.os.Handler;
42import android.os.LatencyTimer;
43import android.os.Looper;
44import android.os.Message;
45import android.os.ParcelFileDescriptor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080046import android.os.Process;
Romain Guy6b7bd242010-10-06 19:49:23 -070047import android.os.RemoteException;
48import android.os.ServiceManager;
49import android.os.SystemClock;
50import android.os.SystemProperties;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080051import android.util.AndroidRuntimeException;
52import android.util.Config;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -070053import android.util.DisplayMetrics;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080054import android.util.EventLog;
Romain Guy6b7bd242010-10-06 19:49:23 -070055import android.util.Log;
Chet Haase949dbf72010-08-11 18:41:06 -070056import android.util.Slog;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080057import android.util.SparseArray;
Dianne Hackborn711e62a2010-11-29 16:38:22 -080058import android.util.TypedValue;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080059import android.view.View.MeasureSpec;
svetoslavganov75986cf2009-05-14 22:28:01 -070060import android.view.accessibility.AccessibilityEvent;
61import android.view.accessibility.AccessibilityManager;
Dianne Hackborn0f761d62010-11-30 22:06:10 -080062import android.view.animation.AccelerateDecelerateInterpolator;
63import android.view.animation.Interpolator;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080064import android.view.inputmethod.InputConnection;
65import android.view.inputmethod.InputMethodManager;
66import android.widget.Scroller;
Joe Onorato86f67862010-11-05 18:57:34 -070067import com.android.internal.policy.PolicyManager;
Romain Guy6b7bd242010-10-06 19:49:23 -070068import com.android.internal.view.BaseSurfaceHolder;
69import com.android.internal.view.IInputMethodCallback;
70import com.android.internal.view.IInputMethodSession;
71import com.android.internal.view.RootViewSurfaceTaker;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080072
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080073import java.io.IOException;
74import java.io.OutputStream;
Romain Guy6b7bd242010-10-06 19:49:23 -070075import java.lang.ref.WeakReference;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080076import java.util.ArrayList;
77
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080078/**
79 * The top of a view hierarchy, implementing the needed protocol between View
80 * and the WindowManager. This is for the most part an internal implementation
81 * detail of {@link WindowManagerImpl}.
82 *
83 * {@hide}
84 */
Romain Guy812ccbe2010-06-01 14:07:24 -070085@SuppressWarnings({"EmptyCatchBlock", "PointlessBooleanExpression"})
Dianne Hackborn0f761d62010-11-30 22:06:10 -080086public final class ViewRoot extends Handler implements ViewParent,
87 View.AttachInfo.Callbacks, HardwareRenderer.HardwareDrawCallbacks {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080088 private static final String TAG = "ViewRoot";
89 private static final boolean DBG = false;
Mike Reedfd716532009-10-12 14:42:56 -040090 private static final boolean SHOW_FPS = false;
Romain Guy812ccbe2010-06-01 14:07:24 -070091 private static final boolean LOCAL_LOGV = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080092 /** @noinspection PointlessBooleanExpression*/
93 private static final boolean DEBUG_DRAW = false || LOCAL_LOGV;
94 private static final boolean DEBUG_LAYOUT = false || LOCAL_LOGV;
Dianne Hackborn711e62a2010-11-29 16:38:22 -080095 private static final boolean DEBUG_DIALOG = false || LOCAL_LOGV;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080096 private static final boolean DEBUG_INPUT_RESIZE = false || LOCAL_LOGV;
97 private static final boolean DEBUG_ORIENTATION = false || LOCAL_LOGV;
98 private static final boolean DEBUG_TRACKBALL = false || LOCAL_LOGV;
99 private static final boolean DEBUG_IMF = false || LOCAL_LOGV;
Dianne Hackborn694f79b2010-03-17 19:44:59 -0700100 private static final boolean DEBUG_CONFIGURATION = false || LOCAL_LOGV;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800101 private static final boolean WATCH_POINTER = false;
102
Michael Chan53071d62009-05-13 17:29:48 -0700103 private static final boolean MEASURE_LATENCY = false;
104 private static LatencyTimer lt;
105
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800106 /**
107 * Maximum time we allow the user to roll the trackball enough to generate
108 * a key event, before resetting the counters.
109 */
110 static final int MAX_TRACKBALL_DELAY = 250;
111
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800112 static IWindowSession sWindowSession;
113
114 static final Object mStaticInit = new Object();
115 static boolean mInitialized = false;
116
117 static final ThreadLocal<RunQueue> sRunQueues = new ThreadLocal<RunQueue>();
118
Dianne Hackborn2a9094d2010-02-03 19:20:09 -0800119 static final ArrayList<Runnable> sFirstDrawHandlers = new ArrayList<Runnable>();
120 static boolean sFirstDrawComplete = false;
121
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800122 static final ArrayList<ComponentCallbacks> sConfigCallbacks
123 = new ArrayList<ComponentCallbacks>();
124
Romain Guy8506ab42009-06-11 17:35:47 -0700125 private static int sDrawTime;
Romain Guy13922e02009-05-12 17:56:14 -0700126
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800127 long mLastTrackballTime = 0;
128 final TrackballAxis mTrackballAxisX = new TrackballAxis();
129 final TrackballAxis mTrackballAxisY = new TrackballAxis();
130
131 final int[] mTmpLocation = new int[2];
Romain Guy8506ab42009-06-11 17:35:47 -0700132
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800133 final TypedValue mTmpValue = new TypedValue();
134
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800135 final InputMethodCallback mInputMethodCallback;
136 final SparseArray<Object> mPendingEvents = new SparseArray<Object>();
137 int mPendingEventSeq = 0;
Romain Guy8506ab42009-06-11 17:35:47 -0700138
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800139 final Thread mThread;
140
141 final WindowLeaked mLocation;
142
143 final WindowManager.LayoutParams mWindowAttributes = new WindowManager.LayoutParams();
144
145 final W mWindow;
146
147 View mView;
148 View mFocusedView;
149 View mRealFocusedView; // this is not set to null in touch mode
150 int mViewVisibility;
151 boolean mAppVisible = true;
152
Dianne Hackbornd76b67c2010-07-13 17:48:30 -0700153 SurfaceHolder.Callback2 mSurfaceHolderCallback;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700154 BaseSurfaceHolder mSurfaceHolder;
155 boolean mIsCreating;
156 boolean mDrawingAllowed;
157
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800158 final Region mTransparentRegion;
159 final Region mPreviousTransparentRegion;
160
161 int mWidth;
162 int mHeight;
Romain Guy7d7b5492011-01-24 16:33:45 -0800163 Rect mDirty;
164 final Rect mCurrentDirty = new Rect();
165 final Rect mPreviousDirty = new Rect();
Romain Guybb93d552009-03-24 21:04:15 -0700166 boolean mIsAnimating;
Romain Guy8506ab42009-06-11 17:35:47 -0700167
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700168 CompatibilityInfo.Translator mTranslator;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800169
170 final View.AttachInfo mAttachInfo;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700171 InputChannel mInputChannel;
Dianne Hackborn1e4b9f32010-06-23 14:10:57 -0700172 InputQueue.Callback mInputQueueCallback;
173 InputQueue mInputQueue;
Joe Onorato86f67862010-11-05 18:57:34 -0700174 FallbackEventHandler mFallbackEventHandler;
Dianne Hackborna95e4cb2010-06-18 18:09:33 -0700175
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800176 final Rect mTempRect; // used in the transaction to not thrash the heap.
177 final Rect mVisRect; // used to retrieve visible rect of focused view.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800178
179 boolean mTraversalScheduled;
180 boolean mWillDrawSoon;
181 boolean mLayoutRequested;
182 boolean mFirst;
183 boolean mReportNextDraw;
184 boolean mFullRedrawNeeded;
185 boolean mNewSurfaceNeeded;
186 boolean mHasHadWindowFocus;
187 boolean mLastWasImTarget;
188
189 boolean mWindowAttributesChanged = false;
190
191 // These can be accessed by any thread, must be protected with a lock.
Mathias Agopian5583dc62009-07-09 16:28:11 -0700192 // Surface can never be reassigned or cleared (use Surface.clear()).
193 private final Surface mSurface = new Surface();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800194
195 boolean mAdded;
196 boolean mAddedTouchMode;
197
198 /*package*/ int mAddNesting;
199
200 // These are accessed by multiple threads.
201 final Rect mWinFrame; // frame given by window manager.
202
203 final Rect mPendingVisibleInsets = new Rect();
204 final Rect mPendingContentInsets = new Rect();
205 final ViewTreeObserver.InternalInsetsInfo mLastGivenInsets
206 = new ViewTreeObserver.InternalInsetsInfo();
207
Dianne Hackborn694f79b2010-03-17 19:44:59 -0700208 final Configuration mLastConfiguration = new Configuration();
209 final Configuration mPendingConfiguration = new Configuration();
210
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800211 class ResizedInfo {
212 Rect coveredInsets;
213 Rect visibleInsets;
214 Configuration newConfig;
215 }
216
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800217 boolean mScrollMayChange;
218 int mSoftInputMode;
219 View mLastScrolledFocus;
220 int mScrollY;
221 int mCurScrollY;
222 Scroller mScroller;
Dianne Hackborn0f761d62010-11-30 22:06:10 -0800223 Bitmap mResizeBitmap;
224 long mResizeBitmapStartTime;
225 int mResizeBitmapDuration;
226 static final Interpolator mResizeInterpolator = new AccelerateDecelerateInterpolator();
Romain Guy8506ab42009-06-11 17:35:47 -0700227
Romain Guy8506ab42009-06-11 17:35:47 -0700228 final ViewConfiguration mViewConfiguration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800229
Christopher Tatea53146c2010-09-07 11:57:52 -0700230 /* Drag/drop */
231 ClipDescription mDragDescription;
232 View mCurrentDragView;
Christopher Tate7fb8b562011-01-20 13:46:41 -0800233 volatile Object mLocalDragState;
Christopher Tatea53146c2010-09-07 11:57:52 -0700234 final PointF mDragPoint = new PointF();
Christopher Tate2c095f32010-10-04 14:13:40 -0700235 final PointF mLastTouchPoint = new PointF();
Christopher Tatea53146c2010-09-07 11:57:52 -0700236
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800237 /**
238 * see {@link #playSoundEffect(int)}
239 */
240 AudioManager mAudioManager;
241
Dianne Hackborn11ea3342009-07-22 21:48:55 -0700242 private final int mDensity;
Adam Powellb08013c2010-09-16 16:28:11 -0700243
Dianne Hackborn4c62fc02009-08-08 20:40:27 -0700244 public static IWindowSession getWindowSession(Looper mainLooper) {
245 synchronized (mStaticInit) {
246 if (!mInitialized) {
247 try {
248 InputMethodManager imm = InputMethodManager.getInstance(mainLooper);
249 sWindowSession = IWindowManager.Stub.asInterface(
250 ServiceManager.getService("window"))
251 .openSession(imm.getClient(), imm.getInputContext());
252 mInitialized = true;
253 } catch (RemoteException e) {
254 }
255 }
256 return sWindowSession;
257 }
258 }
259
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800260 public ViewRoot(Context context) {
261 super();
262
Romain Guy812ccbe2010-06-01 14:07:24 -0700263 if (MEASURE_LATENCY) {
264 if (lt == null) {
265 lt = new LatencyTimer(100, 1000);
266 }
Michael Chan53071d62009-05-13 17:29:48 -0700267 }
268
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800269 // Initialize the statics when this class is first instantiated. This is
270 // done here instead of in the static block because Zygote does not
271 // allow the spawning of threads.
Dianne Hackborn4c62fc02009-08-08 20:40:27 -0700272 getWindowSession(context.getMainLooper());
273
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800274 mThread = Thread.currentThread();
275 mLocation = new WindowLeaked(null);
276 mLocation.fillInStackTrace();
277 mWidth = -1;
278 mHeight = -1;
279 mDirty = new Rect();
280 mTempRect = new Rect();
281 mVisRect = new Rect();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800282 mWinFrame = new Rect();
Romain Guyfb8b7632010-08-23 21:05:08 -0700283 mWindow = new W(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800284 mInputMethodCallback = new InputMethodCallback(this);
285 mViewVisibility = View.GONE;
286 mTransparentRegion = new Region();
287 mPreviousTransparentRegion = new Region();
288 mFirst = true; // true for the first time the view is added
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800289 mAdded = false;
290 mAttachInfo = new View.AttachInfo(sWindowSession, mWindow, this, this);
291 mViewConfiguration = ViewConfiguration.get(context);
Dianne Hackborn11ea3342009-07-22 21:48:55 -0700292 mDensity = context.getResources().getDisplayMetrics().densityDpi;
Joe Onorato86f67862010-11-05 18:57:34 -0700293 mFallbackEventHandler = PolicyManager.makeNewFallbackEventHandler(context);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800294 }
295
Dianne Hackborn2a9094d2010-02-03 19:20:09 -0800296 public static void addFirstDrawHandler(Runnable callback) {
297 synchronized (sFirstDrawHandlers) {
298 if (!sFirstDrawComplete) {
299 sFirstDrawHandlers.add(callback);
300 }
301 }
302 }
303
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800304 public static void addConfigCallback(ComponentCallbacks callback) {
305 synchronized (sConfigCallbacks) {
306 sConfigCallbacks.add(callback);
307 }
308 }
309
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800310 // FIXME for perf testing only
311 private boolean mProfile = false;
312
313 /**
314 * Call this to profile the next traversal call.
315 * FIXME for perf testing only. Remove eventually
316 */
317 public void profile() {
318 mProfile = true;
319 }
320
321 /**
322 * Indicates whether we are in touch mode. Calling this method triggers an IPC
323 * call and should be avoided whenever possible.
324 *
325 * @return True, if the device is in touch mode, false otherwise.
326 *
327 * @hide
328 */
329 static boolean isInTouchMode() {
330 if (mInitialized) {
331 try {
332 return sWindowSession.getInTouchMode();
333 } catch (RemoteException e) {
334 }
335 }
336 return false;
337 }
338
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800339 /**
340 * We have one child
341 */
Romain Guye4d01122010-06-16 18:44:05 -0700342 public void setView(View view, WindowManager.LayoutParams attrs, View panelParentView) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800343 synchronized (this) {
344 if (mView == null) {
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700345 mView = view;
Joe Onorato86f67862010-11-05 18:57:34 -0700346 mFallbackEventHandler.setView(view);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700347 mWindowAttributes.copyFrom(attrs);
Mitsuru Oshima1ecf5d22009-07-06 17:20:38 -0700348 attrs = mWindowAttributes;
Romain Guye4d01122010-06-16 18:44:05 -0700349
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700350 if (view instanceof RootViewSurfaceTaker) {
351 mSurfaceHolderCallback =
352 ((RootViewSurfaceTaker)view).willYouTakeTheSurface();
353 if (mSurfaceHolderCallback != null) {
354 mSurfaceHolder = new TakenSurfaceHolder();
Dianne Hackborn289b9b62010-07-09 11:44:11 -0700355 mSurfaceHolder.setFormat(PixelFormat.UNKNOWN);
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700356 }
357 }
Romain Guy1aec9a22011-01-05 09:37:12 -0800358
359 // If the application owns the surface, don't enable hardware acceleration
360 if (mSurfaceHolder == null) {
361 enableHardwareAcceleration(attrs);
362 }
363
Mitsuru Oshima38ed7d772009-07-21 14:39:34 -0700364 Resources resources = mView.getContext().getResources();
365 CompatibilityInfo compatibilityInfo = resources.getCompatibilityInfo();
Mitsuru Oshima589cebe2009-07-22 20:38:58 -0700366 mTranslator = compatibilityInfo.getTranslator();
Mitsuru Oshima38ed7d772009-07-21 14:39:34 -0700367
368 if (mTranslator != null || !compatibilityInfo.supportsScreen()) {
Mitsuru Oshima240f8a72009-07-22 20:39:14 -0700369 mSurface.setCompatibleDisplayMetrics(resources.getDisplayMetrics(),
370 mTranslator);
Mitsuru Oshima38ed7d772009-07-21 14:39:34 -0700371 }
372
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -0700373 boolean restore = false;
Romain Guy35b38ce2009-10-07 13:38:55 -0700374 if (mTranslator != null) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -0700375 restore = true;
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700376 attrs.backup();
377 mTranslator.translateWindowLayout(attrs);
Mitsuru Oshima3d914922009-05-13 22:29:15 -0700378 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700379 if (DEBUG_LAYOUT) Log.d(TAG, "WindowLayout in setView:" + attrs);
380
Mitsuru Oshima1ecf5d22009-07-06 17:20:38 -0700381 if (!compatibilityInfo.supportsScreen()) {
382 attrs.flags |= WindowManager.LayoutParams.FLAG_COMPATIBLE_WINDOW;
383 }
384
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800385 mSoftInputMode = attrs.softInputMode;
386 mWindowAttributesChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800387 mAttachInfo.mRootView = view;
Romain Guy35b38ce2009-10-07 13:38:55 -0700388 mAttachInfo.mScalingRequired = mTranslator != null;
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700389 mAttachInfo.mApplicationScale =
390 mTranslator == null ? 1.0f : mTranslator.applicationScale;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800391 if (panelParentView != null) {
392 mAttachInfo.mPanelParentWindowToken
393 = panelParentView.getApplicationWindowToken();
394 }
395 mAdded = true;
396 int res; /* = WindowManagerImpl.ADD_OKAY; */
Romain Guy8506ab42009-06-11 17:35:47 -0700397
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800398 // Schedule the first layout -before- adding to the window
399 // manager, to make sure we do the relayout before receiving
400 // any other events from the system.
401 requestLayout();
Jeff Brown46b9ac02010-04-22 18:58:52 -0700402 mInputChannel = new InputChannel();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800403 try {
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700404 res = sWindowSession.add(mWindow, mWindowAttributes,
Jeff Brown46b9ac02010-04-22 18:58:52 -0700405 getHostVisibility(), mAttachInfo.mContentInsets,
406 mInputChannel);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800407 } catch (RemoteException e) {
408 mAdded = false;
409 mView = null;
410 mAttachInfo.mRootView = null;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700411 mInputChannel = null;
Joe Onorato86f67862010-11-05 18:57:34 -0700412 mFallbackEventHandler.setView(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800413 unscheduleTraversals();
414 throw new RuntimeException("Adding window failed", e);
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700415 } finally {
416 if (restore) {
417 attrs.restore();
418 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800419 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700420
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700421 if (mTranslator != null) {
422 mTranslator.translateRectInScreenToAppWindow(mAttachInfo.mContentInsets);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700423 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800424 mPendingContentInsets.set(mAttachInfo.mContentInsets);
425 mPendingVisibleInsets.set(0, 0, 0, 0);
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800426 if (DEBUG_LAYOUT) Log.v(TAG, "Added window " + mWindow);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800427 if (res < WindowManagerImpl.ADD_OKAY) {
428 mView = null;
429 mAttachInfo.mRootView = null;
430 mAdded = false;
Joe Onorato86f67862010-11-05 18:57:34 -0700431 mFallbackEventHandler.setView(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800432 unscheduleTraversals();
433 switch (res) {
434 case WindowManagerImpl.ADD_BAD_APP_TOKEN:
435 case WindowManagerImpl.ADD_BAD_SUBWINDOW_TOKEN:
436 throw new WindowManagerImpl.BadTokenException(
437 "Unable to add window -- token " + attrs.token
438 + " is not valid; is your activity running?");
439 case WindowManagerImpl.ADD_NOT_APP_TOKEN:
440 throw new WindowManagerImpl.BadTokenException(
441 "Unable to add window -- token " + attrs.token
442 + " is not for an application");
443 case WindowManagerImpl.ADD_APP_EXITING:
444 throw new WindowManagerImpl.BadTokenException(
445 "Unable to add window -- app for token " + attrs.token
446 + " is exiting");
447 case WindowManagerImpl.ADD_DUPLICATE_ADD:
448 throw new WindowManagerImpl.BadTokenException(
449 "Unable to add window -- window " + mWindow
450 + " has already been added");
451 case WindowManagerImpl.ADD_STARTING_NOT_NEEDED:
452 // Silently ignore -- we would have just removed it
453 // right away, anyway.
454 return;
455 case WindowManagerImpl.ADD_MULTIPLE_SINGLETON:
456 throw new WindowManagerImpl.BadTokenException(
457 "Unable to add window " + mWindow +
458 " -- another window of this type already exists");
459 case WindowManagerImpl.ADD_PERMISSION_DENIED:
460 throw new WindowManagerImpl.BadTokenException(
461 "Unable to add window " + mWindow +
462 " -- permission denied for this window type");
463 }
464 throw new RuntimeException(
465 "Unable to add window -- unknown error code " + res);
466 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700467
Jeff Brown00fa7bd2010-07-02 15:37:36 -0700468 if (view instanceof RootViewSurfaceTaker) {
469 mInputQueueCallback =
470 ((RootViewSurfaceTaker)view).willYouTakeTheInputQueue();
471 }
472 if (mInputQueueCallback != null) {
473 mInputQueue = new InputQueue(mInputChannel);
474 mInputQueueCallback.onInputQueueCreated(mInputQueue);
475 } else {
476 InputQueue.registerInputChannel(mInputChannel, mInputHandler,
477 Looper.myQueue());
Jeff Brown46b9ac02010-04-22 18:58:52 -0700478 }
479
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800480 view.assignParent(this);
481 mAddedTouchMode = (res&WindowManagerImpl.ADD_FLAG_IN_TOUCH_MODE) != 0;
482 mAppVisible = (res&WindowManagerImpl.ADD_FLAG_APP_VISIBLE) != 0;
483 }
484 }
485 }
486
Romain Guy529b60a2010-08-03 18:05:47 -0700487 private void enableHardwareAcceleration(WindowManager.LayoutParams attrs) {
Dianne Hackborn7eec10e2010-11-12 18:03:47 -0800488 mAttachInfo.mHardwareAccelerated = false;
489 mAttachInfo.mHardwareAccelerationRequested = false;
Romain Guy4f6aff32011-01-12 16:21:41 -0800490
Dianne Hackborn7eec10e2010-11-12 18:03:47 -0800491 // Try to enable hardware acceleration if requested
492 if (attrs != null &&
493 (attrs.flags & WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED) != 0) {
494 // Only enable hardware acceleration if we are not in the system process
495 // The window manager creates ViewRoots to display animated preview windows
496 // of launching apps and we don't want those to be hardware accelerated
497 if (!HardwareRenderer.sRendererDisabled) {
Romain Guyff26a0c2011-01-20 11:35:46 -0800498 // Don't enable hardware acceleration when we're not on the main thread
499 if (Looper.getMainLooper() != Looper.myLooper()) {
500 Log.w(HardwareRenderer.LOG_TAG, "Attempting to initialize hardware "
501 + "acceleration outside of the main thread, aborting");
502 return;
503 }
504
Romain Guye4d01122010-06-16 18:44:05 -0700505 final boolean translucent = attrs.format != PixelFormat.OPAQUE;
Romain Guyb051e892010-09-28 19:09:36 -0700506 if (mAttachInfo.mHardwareRenderer != null) {
507 mAttachInfo.mHardwareRenderer.destroy(true);
Romain Guy4caa4ed2010-08-25 14:46:24 -0700508 }
Romain Guyb051e892010-09-28 19:09:36 -0700509 mAttachInfo.mHardwareRenderer = HardwareRenderer.createGlRenderer(2, translucent);
Dianne Hackborn7eec10e2010-11-12 18:03:47 -0800510 mAttachInfo.mHardwareAccelerated = mAttachInfo.mHardwareAccelerationRequested
511 = mAttachInfo.mHardwareRenderer != null;
512 } else if (HardwareRenderer.isAvailable()) {
513 mAttachInfo.mHardwareAccelerationRequested = true;
Romain Guye4d01122010-06-16 18:44:05 -0700514 }
515 }
516 }
517
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800518 public View getView() {
519 return mView;
520 }
521
522 final WindowLeaked getLocation() {
523 return mLocation;
524 }
525
526 void setLayoutParams(WindowManager.LayoutParams attrs, boolean newView) {
527 synchronized (this) {
The Android Open Source Project10592532009-03-18 17:39:46 -0700528 int oldSoftInputMode = mWindowAttributes.softInputMode;
Mitsuru Oshima5a2b91d2009-07-16 16:30:02 -0700529 // preserve compatible window flag if exists.
530 int compatibleWindowFlag =
531 mWindowAttributes.flags & WindowManager.LayoutParams.FLAG_COMPATIBLE_WINDOW;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800532 mWindowAttributes.copyFrom(attrs);
Mitsuru Oshima5a2b91d2009-07-16 16:30:02 -0700533 mWindowAttributes.flags |= compatibleWindowFlag;
534
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800535 if (newView) {
536 mSoftInputMode = attrs.softInputMode;
537 requestLayout();
538 }
The Android Open Source Project10592532009-03-18 17:39:46 -0700539 // Don't lose the mode we last auto-computed.
540 if ((attrs.softInputMode&WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST)
541 == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED) {
542 mWindowAttributes.softInputMode = (mWindowAttributes.softInputMode
543 & ~WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST)
544 | (oldSoftInputMode
545 & WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST);
546 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800547 mWindowAttributesChanged = true;
548 scheduleTraversals();
549 }
550 }
551
552 void handleAppVisibility(boolean visible) {
553 if (mAppVisible != visible) {
554 mAppVisible = visible;
555 scheduleTraversals();
556 }
557 }
558
559 void handleGetNewSurface() {
560 mNewSurfaceNeeded = true;
561 mFullRedrawNeeded = true;
562 scheduleTraversals();
563 }
564
565 /**
566 * {@inheritDoc}
567 */
568 public void requestLayout() {
569 checkThread();
570 mLayoutRequested = true;
571 scheduleTraversals();
572 }
573
574 /**
575 * {@inheritDoc}
576 */
577 public boolean isLayoutRequested() {
578 return mLayoutRequested;
579 }
580
581 public void invalidateChild(View child, Rect dirty) {
582 checkThread();
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700583 if (DEBUG_DRAW) Log.v(TAG, "Invalidate child: " + dirty);
Chet Haase70d4ba12010-10-06 09:46:45 -0700584 if (dirty == null) {
585 // Fast invalidation for GL-enabled applications; GL must redraw everything
586 invalidate();
587 return;
588 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700589 if (mCurScrollY != 0 || mTranslator != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800590 mTempRect.set(dirty);
Romain Guy1e095972009-07-07 11:22:45 -0700591 dirty = mTempRect;
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700592 if (mCurScrollY != 0) {
Romain Guy1e095972009-07-07 11:22:45 -0700593 dirty.offset(0, -mCurScrollY);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700594 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700595 if (mTranslator != null) {
Romain Guy1e095972009-07-07 11:22:45 -0700596 mTranslator.translateRectInAppWindowToScreen(dirty);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700597 }
Romain Guy1e095972009-07-07 11:22:45 -0700598 if (mAttachInfo.mScalingRequired) {
599 dirty.inset(-1, -1);
600 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800601 }
Chet Haasedaf98e92011-01-10 14:10:36 -0800602 if (!mDirty.isEmpty() && !mDirty.contains(dirty)) {
Romain Guy7d695942010-12-01 17:22:29 -0800603 mAttachInfo.mIgnoreDirtyState = true;
604 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800605 mDirty.union(dirty);
606 if (!mWillDrawSoon) {
607 scheduleTraversals();
608 }
609 }
Romain Guy0d9275e2010-10-26 14:22:30 -0700610
611 void invalidate() {
612 mDirty.set(0, 0, mWidth, mHeight);
613 scheduleTraversals();
614 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800615
616 public ViewParent getParent() {
617 return null;
618 }
619
620 public ViewParent invalidateChildInParent(final int[] location, final Rect dirty) {
621 invalidateChild(null, dirty);
622 return null;
623 }
624
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700625 public boolean getChildVisibleRect(View child, Rect r, android.graphics.Point offset) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800626 if (child != mView) {
627 throw new RuntimeException("child is not mine, honest!");
628 }
629 // Note: don't apply scroll offset, because we want to know its
630 // visibility in the virtual canvas being given to the view hierarchy.
631 return r.intersect(0, 0, mWidth, mHeight);
632 }
633
634 public void bringChildToFront(View child) {
635 }
636
637 public void scheduleTraversals() {
638 if (!mTraversalScheduled) {
639 mTraversalScheduled = true;
640 sendEmptyMessage(DO_TRAVERSAL);
641 }
642 }
643
644 public void unscheduleTraversals() {
645 if (mTraversalScheduled) {
646 mTraversalScheduled = false;
647 removeMessages(DO_TRAVERSAL);
648 }
649 }
650
651 int getHostVisibility() {
652 return mAppVisible ? mView.getVisibility() : View.GONE;
653 }
Romain Guy8506ab42009-06-11 17:35:47 -0700654
Dianne Hackborn0f761d62010-11-30 22:06:10 -0800655 void disposeResizeBitmap() {
656 if (mResizeBitmap != null) {
657 mResizeBitmap.recycle();
658 mResizeBitmap = null;
659 }
660 }
661
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800662 private void performTraversals() {
663 // cache mView since it is used so much below...
664 final View host = mView;
665
666 if (DBG) {
667 System.out.println("======================================");
668 System.out.println("performTraversals");
669 host.debug();
670 }
671
672 if (host == null || !mAdded)
673 return;
674
675 mTraversalScheduled = false;
676 mWillDrawSoon = true;
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800677 boolean windowSizeMayChange = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800678 boolean fullRedrawNeeded = mFullRedrawNeeded;
679 boolean newSurface = false;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700680 boolean surfaceChanged = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800681 WindowManager.LayoutParams lp = mWindowAttributes;
682
683 int desiredWindowWidth;
684 int desiredWindowHeight;
685 int childWidthMeasureSpec;
686 int childHeightMeasureSpec;
687
688 final View.AttachInfo attachInfo = mAttachInfo;
689
690 final int viewVisibility = getHostVisibility();
691 boolean viewVisibilityChanged = mViewVisibility != viewVisibility
692 || mNewSurfaceNeeded;
693
694 WindowManager.LayoutParams params = null;
695 if (mWindowAttributesChanged) {
696 mWindowAttributesChanged = false;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700697 surfaceChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800698 params = lp;
699 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700700 Rect frame = mWinFrame;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800701 if (mFirst) {
702 fullRedrawNeeded = true;
703 mLayoutRequested = true;
704
Romain Guy8506ab42009-06-11 17:35:47 -0700705 DisplayMetrics packageMetrics =
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700706 mView.getContext().getResources().getDisplayMetrics();
707 desiredWindowWidth = packageMetrics.widthPixels;
708 desiredWindowHeight = packageMetrics.heightPixels;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800709
710 // For the very first time, tell the view hierarchy that it
711 // is attached to the window. Note that at this point the surface
712 // object is not initialized to its backing store, but soon it
713 // will be (assuming the window is visible).
714 attachInfo.mSurface = mSurface;
Romain Guyc5d55862011-01-21 19:01:46 -0800715 // We used to use the following condition to choose 32 bits drawing caches:
716 // PixelFormat.hasAlpha(lp.format) || lp.format == PixelFormat.RGBX_8888
717 // However, windows are now always 32 bits by default, so choose 32 bits
718 attachInfo.mUse32BitDrawingCache = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800719 attachInfo.mHasWindowFocus = false;
720 attachInfo.mWindowVisibility = viewVisibility;
721 attachInfo.mRecomputeGlobalAttributes = false;
722 attachInfo.mKeepScreenOn = false;
Joe Onorato664644d2011-01-23 17:53:23 -0800723 attachInfo.mSystemUiVisibility = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800724 viewVisibilityChanged = false;
Dianne Hackborn694f79b2010-03-17 19:44:59 -0700725 mLastConfiguration.setTo(host.getResources().getConfiguration());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800726 host.dispatchAttachedToWindow(attachInfo, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800727 //Log.i(TAG, "Screen on initialized: " + attachInfo.mKeepScreenOn);
svetoslavganov75986cf2009-05-14 22:28:01 -0700728
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800729 } else {
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700730 desiredWindowWidth = frame.width();
731 desiredWindowHeight = frame.height();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800732 if (desiredWindowWidth != mWidth || desiredWindowHeight != mHeight) {
Jeff Brownc5ed5912010-07-14 18:48:53 -0700733 if (DEBUG_ORIENTATION) Log.v(TAG,
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700734 "View " + host + " resized to: " + frame);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800735 fullRedrawNeeded = true;
736 mLayoutRequested = true;
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800737 windowSizeMayChange = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800738 }
739 }
740
741 if (viewVisibilityChanged) {
742 attachInfo.mWindowVisibility = viewVisibility;
743 host.dispatchWindowVisibilityChanged(viewVisibility);
744 if (viewVisibility != View.VISIBLE || mNewSurfaceNeeded) {
Romain Guyb051e892010-09-28 19:09:36 -0700745 if (mAttachInfo.mHardwareRenderer != null) {
746 mAttachInfo.mHardwareRenderer.destroy(false);
Romain Guy4caa4ed2010-08-25 14:46:24 -0700747 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800748 }
749 if (viewVisibility == View.GONE) {
750 // After making a window gone, we will count it as being
751 // shown for the first time the next time it gets focus.
752 mHasHadWindowFocus = false;
753 }
754 }
755
756 boolean insetsChanged = false;
Romain Guy8506ab42009-06-11 17:35:47 -0700757
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800758 if (mLayoutRequested) {
Romain Guy15df6702009-08-17 20:17:30 -0700759 // Execute enqueued actions on every layout in case a view that was detached
760 // enqueued an action after being detached
761 getRunQueue().executeActions(attachInfo.mHandler);
762
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800763 final Resources res = mView.getContext().getResources();
764
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800765 if (mFirst) {
766 host.fitSystemWindows(mAttachInfo.mContentInsets);
767 // make sure touch mode code executes by setting cached value
768 // to opposite of the added touch mode.
769 mAttachInfo.mInTouchMode = !mAddedTouchMode;
Romain Guy2d4cff62010-04-09 15:39:00 -0700770 ensureTouchModeLocally(mAddedTouchMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800771 } else {
772 if (!mAttachInfo.mContentInsets.equals(mPendingContentInsets)) {
Dianne Hackborn0f761d62010-11-30 22:06:10 -0800773 if (mWidth > 0 && mHeight > 0 &&
774 mSurface != null && mSurface.isValid() &&
Dianne Hackborn63042d62011-01-26 18:56:29 -0800775 !mAttachInfo.mTurnOffWindowResizeAnim &&
Dianne Hackborn0f761d62010-11-30 22:06:10 -0800776 mAttachInfo.mHardwareRenderer != null &&
777 mAttachInfo.mHardwareRenderer.isEnabled() &&
778 lp != null && !PixelFormat.formatHasAlpha(lp.format)) {
779
780 disposeResizeBitmap();
781
782 boolean completed = false;
783 try {
784 mResizeBitmap = Bitmap.createBitmap(mWidth, mHeight,
785 Bitmap.Config.ARGB_8888);
786 mResizeBitmap.setHasAlpha(false);
787 Canvas canvas = new Canvas(mResizeBitmap);
Romain Guyf90f8172011-01-25 22:53:24 -0800788 canvas.drawColor(0xff000000, PorterDuff.Mode.SRC);
Dianne Hackborn0f761d62010-11-30 22:06:10 -0800789 int yoff;
790 final boolean scrolling = mScroller != null
791 && mScroller.computeScrollOffset();
792 if (scrolling) {
793 yoff = mScroller.getCurrY();
794 mScroller.abortAnimation();
795 } else {
796 yoff = mScrollY;
797 }
798 canvas.translate(0, -yoff);
799 if (mTranslator != null) {
800 mTranslator.translateCanvas(canvas);
801 }
802 canvas.setScreenDensity(mAttachInfo.mScalingRequired
803 ? DisplayMetrics.DENSITY_DEVICE : 0);
804 mView.draw(canvas);
805 mResizeBitmapStartTime = SystemClock.uptimeMillis();
806 mResizeBitmapDuration = mView.getResources().getInteger(
807 com.android.internal.R.integer.config_mediumAnimTime);
808 completed = true;
809 } catch (OutOfMemoryError e) {
810 Log.w(TAG, "Not enough memory for content change anim buffer", e);
811 } finally {
812 if (!completed) {
813 mResizeBitmap = null;
814 }
815 }
816 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800817 mAttachInfo.mContentInsets.set(mPendingContentInsets);
818 host.fitSystemWindows(mAttachInfo.mContentInsets);
819 insetsChanged = true;
820 if (DEBUG_LAYOUT) Log.v(TAG, "Content insets changing to: "
821 + mAttachInfo.mContentInsets);
822 }
823 if (!mAttachInfo.mVisibleInsets.equals(mPendingVisibleInsets)) {
824 mAttachInfo.mVisibleInsets.set(mPendingVisibleInsets);
825 if (DEBUG_LAYOUT) Log.v(TAG, "Visible insets changing to: "
826 + mAttachInfo.mVisibleInsets);
827 }
828 if (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT
829 || lp.height == ViewGroup.LayoutParams.WRAP_CONTENT) {
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800830 windowSizeMayChange = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800831
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800832 DisplayMetrics packageMetrics = res.getDisplayMetrics();
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700833 desiredWindowWidth = packageMetrics.widthPixels;
834 desiredWindowHeight = packageMetrics.heightPixels;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800835 }
836 }
837
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800838 // Ask host how big it wants to be
Jeff Brownc5ed5912010-07-14 18:48:53 -0700839 if (DEBUG_ORIENTATION || DEBUG_LAYOUT) Log.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800840 "Measuring " + host + " in display " + desiredWindowWidth
841 + "x" + desiredWindowHeight + "...");
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800842
843 boolean goodMeasure = false;
844 if (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT
845 || lp.height == ViewGroup.LayoutParams.WRAP_CONTENT) {
846 // On large screens, we don't want to allow dialogs to just
847 // stretch to fill the entire width of the screen to display
848 // one line of text. First try doing the layout at a smaller
849 // size to see if it will fit.
850 final DisplayMetrics packageMetrics = res.getDisplayMetrics();
851 res.getValue(com.android.internal.R.dimen.config_prefDialogWidth, mTmpValue, true);
852 int baseSize = 0;
853 if (mTmpValue.type == TypedValue.TYPE_DIMENSION) {
854 baseSize = (int)mTmpValue.getDimension(packageMetrics);
855 }
856 if (DEBUG_DIALOG) Log.v(TAG, "Window " + mView + ": baseSize=" + baseSize);
Dianne Hackborn7d3a5bc2010-11-29 22:52:12 -0800857 if (baseSize != 0 && desiredWindowWidth > baseSize) {
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800858 childWidthMeasureSpec = getRootMeasureSpec(baseSize, lp.width);
859 childHeightMeasureSpec = getRootMeasureSpec(desiredWindowHeight, lp.height);
860 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
861 if (DEBUG_DIALOG) Log.v(TAG, "Window " + mView + ": measured ("
Dianne Hackborn189ee182010-12-02 21:48:53 -0800862 + host.getMeasuredWidth() + "," + host.getMeasuredHeight() + ")");
863 if ((host.getMeasuredWidthAndState()&View.MEASURED_STATE_TOO_SMALL) == 0) {
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800864 goodMeasure = true;
865 } else {
866 // Didn't fit in that size... try expanding a bit.
867 baseSize = (baseSize+desiredWindowWidth)/2;
868 if (DEBUG_DIALOG) Log.v(TAG, "Window " + mView + ": next baseSize="
869 + baseSize);
Dianne Hackborn189ee182010-12-02 21:48:53 -0800870 childWidthMeasureSpec = getRootMeasureSpec(baseSize, lp.width);
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800871 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
872 if (DEBUG_DIALOG) Log.v(TAG, "Window " + mView + ": measured ("
Dianne Hackborn189ee182010-12-02 21:48:53 -0800873 + host.getMeasuredWidth() + "," + host.getMeasuredHeight() + ")");
874 if ((host.getMeasuredWidthAndState()&View.MEASURED_STATE_TOO_SMALL) == 0) {
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800875 if (DEBUG_DIALOG) Log.v(TAG, "Good!");
876 goodMeasure = true;
877 }
878 }
879 }
880 }
881
882 if (!goodMeasure) {
883 childWidthMeasureSpec = getRootMeasureSpec(desiredWindowWidth, lp.width);
884 childHeightMeasureSpec = getRootMeasureSpec(desiredWindowHeight, lp.height);
885 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
Adam Powellaa0b92c2010-12-13 22:38:53 -0800886 if (mWidth != host.getMeasuredWidth() || mHeight != host.getMeasuredHeight()) {
887 windowSizeMayChange = true;
888 }
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800889 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800890
891 if (DBG) {
892 System.out.println("======================================");
893 System.out.println("performTraversals -- after measure");
894 host.debug();
895 }
896 }
897
Romain Guy6e81e572011-01-25 12:52:58 -0800898 if (attachInfo.mRecomputeGlobalAttributes && host.mAttachInfo != null) {
Joe Onorato664644d2011-01-23 17:53:23 -0800899 //Log.i(TAG, "Computing view hierarchy attributes!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800900 attachInfo.mRecomputeGlobalAttributes = false;
Joe Onorato664644d2011-01-23 17:53:23 -0800901 boolean oldScreenOn = attachInfo.mKeepScreenOn;
902 int oldVis = attachInfo.mSystemUiVisibility;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800903 attachInfo.mKeepScreenOn = false;
Joe Onorato664644d2011-01-23 17:53:23 -0800904 attachInfo.mSystemUiVisibility = 0;
905 attachInfo.mHasSystemUiListeners = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800906 host.dispatchCollectViewAttributes(0);
Joe Onorato14782f72011-01-25 19:53:17 -0800907 if (attachInfo.mKeepScreenOn != oldScreenOn
908 || attachInfo.mSystemUiVisibility != oldVis
909 || attachInfo.mHasSystemUiListeners) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800910 params = lp;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800911 }
912 }
913
914 if (mFirst || attachInfo.mViewVisibilityChanged) {
915 attachInfo.mViewVisibilityChanged = false;
916 int resizeMode = mSoftInputMode &
917 WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST;
918 // If we are in auto resize mode, then we need to determine
919 // what mode to use now.
920 if (resizeMode == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED) {
921 final int N = attachInfo.mScrollContainers.size();
922 for (int i=0; i<N; i++) {
923 if (attachInfo.mScrollContainers.get(i).isShown()) {
924 resizeMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE;
925 }
926 }
927 if (resizeMode == 0) {
928 resizeMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN;
929 }
930 if ((lp.softInputMode &
931 WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) != resizeMode) {
932 lp.softInputMode = (lp.softInputMode &
933 ~WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) |
934 resizeMode;
935 params = lp;
936 }
937 }
938 }
Romain Guy8506ab42009-06-11 17:35:47 -0700939
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800940 if (params != null && (host.mPrivateFlags & View.REQUEST_TRANSPARENT_REGIONS) != 0) {
941 if (!PixelFormat.formatHasAlpha(params.format)) {
942 params.format = PixelFormat.TRANSLUCENT;
943 }
944 }
945
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800946 boolean windowShouldResize = mLayoutRequested && windowSizeMayChange
Dianne Hackborn189ee182010-12-02 21:48:53 -0800947 && ((mWidth != host.getMeasuredWidth() || mHeight != host.getMeasuredHeight())
Romain Guy2e4f4262010-04-06 11:07:52 -0700948 || (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT &&
949 frame.width() < desiredWindowWidth && frame.width() != mWidth)
950 || (lp.height == ViewGroup.LayoutParams.WRAP_CONTENT &&
951 frame.height() < desiredWindowHeight && frame.height() != mHeight));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800952
953 final boolean computesInternalInsets =
954 attachInfo.mTreeObserver.hasComputeInternalInsetsListeners();
Romain Guy812ccbe2010-06-01 14:07:24 -0700955
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800956 boolean insetsPending = false;
957 int relayoutResult = 0;
Romain Guy812ccbe2010-06-01 14:07:24 -0700958
959 if (mFirst || windowShouldResize || insetsChanged ||
960 viewVisibilityChanged || params != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800961
962 if (viewVisibility == View.VISIBLE) {
963 // If this window is giving internal insets to the window
964 // manager, and it is being added or changing its visibility,
965 // then we want to first give the window manager "fake"
966 // insets to cause it to effectively ignore the content of
967 // the window during layout. This avoids it briefly causing
968 // other windows to resize/move based on the raw frame of the
969 // window, waiting until we can finish laying out this window
970 // and get back to the window manager with the ultimately
971 // computed insets.
Romain Guy812ccbe2010-06-01 14:07:24 -0700972 insetsPending = computesInternalInsets && (mFirst || viewVisibilityChanged);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800973 }
974
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700975 if (mSurfaceHolder != null) {
976 mSurfaceHolder.mSurfaceLock.lock();
977 mDrawingAllowed = true;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700978 }
Romain Guy812ccbe2010-06-01 14:07:24 -0700979
Romain Guyc361da82010-10-25 15:29:10 -0700980 boolean hwInitialized = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800981 boolean contentInsetsChanged = false;
Romain Guy13922e02009-05-12 17:56:14 -0700982 boolean visibleInsetsChanged;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700983 boolean hadSurface = mSurface.isValid();
Romain Guy812ccbe2010-06-01 14:07:24 -0700984
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800985 try {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800986 int fl = 0;
987 if (params != null) {
988 fl = params.flags;
989 if (attachInfo.mKeepScreenOn) {
990 params.flags |= WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
991 }
Joe Onorato14782f72011-01-25 19:53:17 -0800992 params.subtreeSystemUiVisibility = attachInfo.mSystemUiVisibility;
993 params.hasSystemUiListeners = attachInfo.mHasSystemUiListeners
994 || params.subtreeSystemUiVisibility != 0
995 || params.systemUiVisibility != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800996 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700997 if (DEBUG_LAYOUT) {
Dianne Hackborn189ee182010-12-02 21:48:53 -0800998 Log.i(TAG, "host=w:" + host.getMeasuredWidth() + ", h:" +
999 host.getMeasuredHeight() + ", params=" + params);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001000 }
Romain Guy2a83f002011-01-18 18:28:21 -08001001
1002 final int surfaceGenerationId = mSurface.getGenerationId();
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001003 relayoutResult = relayoutWindow(params, viewVisibility, insetsPending);
1004
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001005 if (params != null) {
1006 params.flags = fl;
1007 }
1008
1009 if (DEBUG_LAYOUT) Log.v(TAG, "relayout: frame=" + frame.toShortString()
1010 + " content=" + mPendingContentInsets.toShortString()
1011 + " visible=" + mPendingVisibleInsets.toShortString()
1012 + " surface=" + mSurface);
Romain Guy8506ab42009-06-11 17:35:47 -07001013
Dianne Hackborn694f79b2010-03-17 19:44:59 -07001014 if (mPendingConfiguration.seq != 0) {
1015 if (DEBUG_CONFIGURATION) Log.v(TAG, "Visible with new config: "
1016 + mPendingConfiguration);
1017 updateConfiguration(mPendingConfiguration, !mFirst);
1018 mPendingConfiguration.seq = 0;
1019 }
1020
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001021 contentInsetsChanged = !mPendingContentInsets.equals(
1022 mAttachInfo.mContentInsets);
1023 visibleInsetsChanged = !mPendingVisibleInsets.equals(
1024 mAttachInfo.mVisibleInsets);
1025 if (contentInsetsChanged) {
1026 mAttachInfo.mContentInsets.set(mPendingContentInsets);
1027 host.fitSystemWindows(mAttachInfo.mContentInsets);
1028 if (DEBUG_LAYOUT) Log.v(TAG, "Content insets changing to: "
1029 + mAttachInfo.mContentInsets);
1030 }
1031 if (visibleInsetsChanged) {
1032 mAttachInfo.mVisibleInsets.set(mPendingVisibleInsets);
1033 if (DEBUG_LAYOUT) Log.v(TAG, "Visible insets changing to: "
1034 + mAttachInfo.mVisibleInsets);
1035 }
1036
1037 if (!hadSurface) {
1038 if (mSurface.isValid()) {
1039 // If we are creating a new surface, then we need to
1040 // completely redraw it. Also, when we get to the
1041 // point of drawing it we will hold off and schedule
1042 // a new traversal instead. This is so we can tell the
1043 // window manager about all of the windows being displayed
1044 // before actually drawing them, so it can display then
1045 // all at once.
1046 newSurface = true;
1047 fullRedrawNeeded = true;
Jack Palevich61a6e682009-10-09 17:37:50 -07001048 mPreviousTransparentRegion.setEmpty();
Romain Guy8506ab42009-06-11 17:35:47 -07001049
Romain Guyb051e892010-09-28 19:09:36 -07001050 if (mAttachInfo.mHardwareRenderer != null) {
Romain Guyc361da82010-10-25 15:29:10 -07001051 hwInitialized = mAttachInfo.mHardwareRenderer.initialize(mHolder);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001052 }
1053 }
1054 } else if (!mSurface.isValid()) {
1055 // If the surface has been removed, then reset the scroll
1056 // positions.
1057 mLastScrolledFocus = null;
1058 mScrollY = mCurScrollY = 0;
1059 if (mScroller != null) {
1060 mScroller.abortAnimation();
1061 }
Dianne Hackborn0f761d62010-11-30 22:06:10 -08001062 disposeResizeBitmap();
Romain Guy2a83f002011-01-18 18:28:21 -08001063 } else if (surfaceGenerationId != mSurface.getGenerationId() &&
1064 mSurfaceHolder == null && mAttachInfo.mHardwareRenderer != null) {
Romain Guy7d7b5492011-01-24 16:33:45 -08001065 fullRedrawNeeded = true;
Romain Guy2a83f002011-01-18 18:28:21 -08001066 mAttachInfo.mHardwareRenderer.updateSurface(mHolder);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001067 }
1068 } catch (RemoteException e) {
1069 }
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001070
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001071 if (DEBUG_ORIENTATION) Log.v(
Jeff Brownc5ed5912010-07-14 18:48:53 -07001072 TAG, "Relayout returned: frame=" + frame + ", surface=" + mSurface);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001073
1074 attachInfo.mWindowLeft = frame.left;
1075 attachInfo.mWindowTop = frame.top;
1076
1077 // !!FIXME!! This next section handles the case where we did not get the
1078 // window size we asked for. We should avoid this by getting a maximum size from
1079 // the window session beforehand.
1080 mWidth = frame.width();
1081 mHeight = frame.height();
1082
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001083 if (mSurfaceHolder != null) {
1084 // The app owns the surface; tell it about what is going on.
1085 if (mSurface.isValid()) {
1086 // XXX .copyFrom() doesn't work!
1087 //mSurfaceHolder.mSurface.copyFrom(mSurface);
1088 mSurfaceHolder.mSurface = mSurface;
1089 }
Jeff Brown30bc34f2011-01-25 12:56:56 -08001090 mSurfaceHolder.setSurfaceFrameSize(mWidth, mHeight);
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001091 mSurfaceHolder.mSurfaceLock.unlock();
1092 if (mSurface.isValid()) {
1093 if (!hadSurface) {
1094 mSurfaceHolder.ungetCallbacks();
1095
1096 mIsCreating = true;
1097 mSurfaceHolderCallback.surfaceCreated(mSurfaceHolder);
1098 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
1099 if (callbacks != null) {
1100 for (SurfaceHolder.Callback c : callbacks) {
1101 c.surfaceCreated(mSurfaceHolder);
1102 }
1103 }
1104 surfaceChanged = true;
1105 }
1106 if (surfaceChanged) {
1107 mSurfaceHolderCallback.surfaceChanged(mSurfaceHolder,
1108 lp.format, mWidth, mHeight);
1109 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
1110 if (callbacks != null) {
1111 for (SurfaceHolder.Callback c : callbacks) {
1112 c.surfaceChanged(mSurfaceHolder, lp.format,
1113 mWidth, mHeight);
1114 }
1115 }
1116 }
1117 mIsCreating = false;
1118 } else if (hadSurface) {
1119 mSurfaceHolder.ungetCallbacks();
1120 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
1121 mSurfaceHolderCallback.surfaceDestroyed(mSurfaceHolder);
1122 if (callbacks != null) {
1123 for (SurfaceHolder.Callback c : callbacks) {
1124 c.surfaceDestroyed(mSurfaceHolder);
1125 }
1126 }
1127 mSurfaceHolder.mSurfaceLock.lock();
1128 // Make surface invalid.
1129 //mSurfaceHolder.mSurface.copyFrom(mSurface);
1130 mSurfaceHolder.mSurface = new Surface();
1131 mSurfaceHolder.mSurfaceLock.unlock();
1132 }
1133 }
Romain Guy53389bd2010-09-07 17:16:32 -07001134
Romain Guy6b5108b2011-01-04 16:11:10 -08001135 if (hwInitialized || ((windowShouldResize || params != null) &&
Romain Guydbf78bd2010-12-07 17:04:03 -08001136 mAttachInfo.mHardwareRenderer != null &&
1137 mAttachInfo.mHardwareRenderer.isEnabled())) {
Romain Guyb051e892010-09-28 19:09:36 -07001138 mAttachInfo.mHardwareRenderer.setup(mWidth, mHeight);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001139 }
1140
1141 boolean focusChangedDueToTouchMode = ensureTouchModeLocally(
Romain Guy2d4cff62010-04-09 15:39:00 -07001142 (relayoutResult&WindowManagerImpl.RELAYOUT_IN_TOUCH_MODE) != 0);
Dianne Hackborn189ee182010-12-02 21:48:53 -08001143 if (focusChangedDueToTouchMode || mWidth != host.getMeasuredWidth()
1144 || mHeight != host.getMeasuredHeight() || contentInsetsChanged) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001145 childWidthMeasureSpec = getRootMeasureSpec(mWidth, lp.width);
1146 childHeightMeasureSpec = getRootMeasureSpec(mHeight, lp.height);
1147
1148 if (DEBUG_LAYOUT) Log.v(TAG, "Ooops, something changed! mWidth="
Dianne Hackborn189ee182010-12-02 21:48:53 -08001149 + mWidth + " measuredWidth=" + host.getMeasuredWidth()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001150 + " mHeight=" + mHeight
Dianne Hackbornff801ec2011-01-22 18:05:38 -08001151 + " measuredHeight=" + host.getMeasuredHeight()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001152 + " coveredInsetsChanged=" + contentInsetsChanged);
Romain Guy8506ab42009-06-11 17:35:47 -07001153
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001154 // Ask host how big it wants to be
1155 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
1156
1157 // Implementation of weights from WindowManager.LayoutParams
1158 // We just grow the dimensions as needed and re-measure if
1159 // needs be
Dianne Hackborn189ee182010-12-02 21:48:53 -08001160 int width = host.getMeasuredWidth();
1161 int height = host.getMeasuredHeight();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001162 boolean measureAgain = false;
1163
1164 if (lp.horizontalWeight > 0.0f) {
1165 width += (int) ((mWidth - width) * lp.horizontalWeight);
1166 childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(width,
1167 MeasureSpec.EXACTLY);
1168 measureAgain = true;
1169 }
1170 if (lp.verticalWeight > 0.0f) {
1171 height += (int) ((mHeight - height) * lp.verticalWeight);
1172 childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(height,
1173 MeasureSpec.EXACTLY);
1174 measureAgain = true;
1175 }
1176
1177 if (measureAgain) {
1178 if (DEBUG_LAYOUT) Log.v(TAG,
1179 "And hey let's measure once more: width=" + width
1180 + " height=" + height);
1181 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
1182 }
1183
1184 mLayoutRequested = true;
1185 }
1186 }
1187
1188 final boolean didLayout = mLayoutRequested;
1189 boolean triggerGlobalLayoutListener = didLayout
1190 || attachInfo.mRecomputeGlobalAttributes;
1191 if (didLayout) {
1192 mLayoutRequested = false;
1193 mScrollMayChange = true;
1194 if (DEBUG_ORIENTATION || DEBUG_LAYOUT) Log.v(
Jeff Brownc5ed5912010-07-14 18:48:53 -07001195 TAG, "Laying out " + host + " to (" +
Dianne Hackborn189ee182010-12-02 21:48:53 -08001196 host.getMeasuredWidth() + ", " + host.getMeasuredHeight() + ")");
Romain Guy13922e02009-05-12 17:56:14 -07001197 long startTime = 0L;
Romain Guy5429e1d2010-09-07 12:38:00 -07001198 if (ViewDebug.DEBUG_PROFILE_LAYOUT) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001199 startTime = SystemClock.elapsedRealtime();
1200 }
Dianne Hackborn189ee182010-12-02 21:48:53 -08001201 host.layout(0, 0, host.getMeasuredWidth(), host.getMeasuredHeight());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001202
Romain Guy13922e02009-05-12 17:56:14 -07001203 if (Config.DEBUG && ViewDebug.consistencyCheckEnabled) {
1204 if (!host.dispatchConsistencyCheck(ViewDebug.CONSISTENCY_LAYOUT)) {
1205 throw new IllegalStateException("The view hierarchy is an inconsistent state,"
1206 + "please refer to the logs with the tag "
1207 + ViewDebug.CONSISTENCY_LOG_TAG + " for more infomation.");
1208 }
1209 }
1210
Romain Guy5429e1d2010-09-07 12:38:00 -07001211 if (ViewDebug.DEBUG_PROFILE_LAYOUT) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001212 EventLog.writeEvent(60001, SystemClock.elapsedRealtime() - startTime);
1213 }
1214
1215 // By this point all views have been sized and positionned
1216 // We can compute the transparent area
1217
1218 if ((host.mPrivateFlags & View.REQUEST_TRANSPARENT_REGIONS) != 0) {
1219 // start out transparent
1220 // TODO: AVOID THAT CALL BY CACHING THE RESULT?
1221 host.getLocationInWindow(mTmpLocation);
1222 mTransparentRegion.set(mTmpLocation[0], mTmpLocation[1],
1223 mTmpLocation[0] + host.mRight - host.mLeft,
1224 mTmpLocation[1] + host.mBottom - host.mTop);
1225
1226 host.gatherTransparentRegion(mTransparentRegion);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001227 if (mTranslator != null) {
1228 mTranslator.translateRegionInWindowToScreen(mTransparentRegion);
1229 }
1230
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001231 if (!mTransparentRegion.equals(mPreviousTransparentRegion)) {
1232 mPreviousTransparentRegion.set(mTransparentRegion);
1233 // reconfigure window manager
1234 try {
1235 sWindowSession.setTransparentRegion(mWindow, mTransparentRegion);
1236 } catch (RemoteException e) {
1237 }
1238 }
1239 }
1240
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001241 if (DBG) {
1242 System.out.println("======================================");
1243 System.out.println("performTraversals -- after setFrame");
1244 host.debug();
1245 }
1246 }
1247
1248 if (triggerGlobalLayoutListener) {
1249 attachInfo.mRecomputeGlobalAttributes = false;
1250 attachInfo.mTreeObserver.dispatchOnGlobalLayout();
1251 }
1252
1253 if (computesInternalInsets) {
Jeff Brownfbf09772011-01-16 14:06:57 -08001254 // Clear the original insets.
1255 final ViewTreeObserver.InternalInsetsInfo insets = attachInfo.mGivenInternalInsets;
1256 insets.reset();
1257
1258 // Compute new insets in place.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001259 attachInfo.mTreeObserver.dispatchOnComputeInternalInsets(insets);
Jeff Brownfbf09772011-01-16 14:06:57 -08001260
1261 // Tell the window manager.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001262 if (insetsPending || !mLastGivenInsets.equals(insets)) {
1263 mLastGivenInsets.set(insets);
Jeff Brownfbf09772011-01-16 14:06:57 -08001264
1265 // Translate insets to screen coordinates if needed.
1266 final Rect contentInsets;
1267 final Rect visibleInsets;
1268 final Region touchableRegion;
1269 if (mTranslator != null) {
1270 contentInsets = mTranslator.getTranslatedContentInsets(insets.contentInsets);
1271 visibleInsets = mTranslator.getTranslatedVisibleInsets(insets.visibleInsets);
1272 touchableRegion = mTranslator.getTranslatedTouchableArea(insets.touchableRegion);
1273 } else {
1274 contentInsets = insets.contentInsets;
1275 visibleInsets = insets.visibleInsets;
1276 touchableRegion = insets.touchableRegion;
1277 }
1278
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001279 try {
1280 sWindowSession.setInsets(mWindow, insets.mTouchableInsets,
Jeff Brownfbf09772011-01-16 14:06:57 -08001281 contentInsets, visibleInsets, touchableRegion);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001282 } catch (RemoteException e) {
1283 }
1284 }
1285 }
Romain Guy8506ab42009-06-11 17:35:47 -07001286
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001287 if (mFirst) {
1288 // handle first focus request
1289 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: mView.hasFocus()="
1290 + mView.hasFocus());
1291 if (mView != null) {
1292 if (!mView.hasFocus()) {
1293 mView.requestFocus(View.FOCUS_FORWARD);
1294 mFocusedView = mRealFocusedView = mView.findFocus();
1295 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: requested focused view="
1296 + mFocusedView);
1297 } else {
1298 mRealFocusedView = mView.findFocus();
1299 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: existing focused view="
1300 + mRealFocusedView);
1301 }
1302 }
1303 }
1304
1305 mFirst = false;
1306 mWillDrawSoon = false;
1307 mNewSurfaceNeeded = false;
1308 mViewVisibility = viewVisibility;
1309
1310 if (mAttachInfo.mHasWindowFocus) {
1311 final boolean imTarget = WindowManager.LayoutParams
1312 .mayUseInputMethod(mWindowAttributes.flags);
1313 if (imTarget != mLastWasImTarget) {
1314 mLastWasImTarget = imTarget;
1315 InputMethodManager imm = InputMethodManager.peekInstance();
1316 if (imm != null && imTarget) {
1317 imm.startGettingWindowFocus(mView);
1318 imm.onWindowFocus(mView, mView.findFocus(),
1319 mWindowAttributes.softInputMode,
1320 !mHasHadWindowFocus, mWindowAttributes.flags);
1321 }
1322 }
1323 }
Romain Guy8506ab42009-06-11 17:35:47 -07001324
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001325 boolean cancelDraw = attachInfo.mTreeObserver.dispatchOnPreDraw();
1326
1327 if (!cancelDraw && !newSurface) {
1328 mFullRedrawNeeded = false;
1329 draw(fullRedrawNeeded);
1330
1331 if ((relayoutResult&WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0
1332 || mReportNextDraw) {
1333 if (LOCAL_LOGV) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001334 Log.v(TAG, "FINISHED DRAWING: " + mWindowAttributes.getTitle());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001335 }
1336 mReportNextDraw = false;
Dianne Hackbornd76b67c2010-07-13 17:48:30 -07001337 if (mSurfaceHolder != null && mSurface.isValid()) {
1338 mSurfaceHolderCallback.surfaceRedrawNeeded(mSurfaceHolder);
1339 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
1340 if (callbacks != null) {
1341 for (SurfaceHolder.Callback c : callbacks) {
1342 if (c instanceof SurfaceHolder.Callback2) {
1343 ((SurfaceHolder.Callback2)c).surfaceRedrawNeeded(
1344 mSurfaceHolder);
1345 }
1346 }
1347 }
1348 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001349 try {
1350 sWindowSession.finishDrawing(mWindow);
1351 } catch (RemoteException e) {
1352 }
1353 }
1354 } else {
1355 // We were supposed to report when we are done drawing. Since we canceled the
1356 // draw, remember it here.
1357 if ((relayoutResult&WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0) {
1358 mReportNextDraw = true;
1359 }
1360 if (fullRedrawNeeded) {
1361 mFullRedrawNeeded = true;
1362 }
1363 // Try again
1364 scheduleTraversals();
1365 }
1366 }
1367
1368 public void requestTransparentRegion(View child) {
1369 // the test below should not fail unless someone is messing with us
1370 checkThread();
1371 if (mView == child) {
1372 mView.mPrivateFlags |= View.REQUEST_TRANSPARENT_REGIONS;
1373 // Need to make sure we re-evaluate the window attributes next
1374 // time around, to ensure the window has the correct format.
1375 mWindowAttributesChanged = true;
Mathias Agopian1bd80ad2010-11-04 17:13:39 -07001376 requestLayout();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001377 }
1378 }
1379
1380 /**
1381 * Figures out the measure spec for the root view in a window based on it's
1382 * layout params.
1383 *
1384 * @param windowSize
1385 * The available width or height of the window
1386 *
1387 * @param rootDimension
1388 * The layout params for one dimension (width or height) of the
1389 * window.
1390 *
1391 * @return The measure spec to use to measure the root view.
1392 */
1393 private int getRootMeasureSpec(int windowSize, int rootDimension) {
1394 int measureSpec;
1395 switch (rootDimension) {
1396
Romain Guy980a9382010-01-08 15:06:28 -08001397 case ViewGroup.LayoutParams.MATCH_PARENT:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001398 // Window can't resize. Force root view to be windowSize.
1399 measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.EXACTLY);
1400 break;
1401 case ViewGroup.LayoutParams.WRAP_CONTENT:
1402 // Window can resize. Set max size for root view.
1403 measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.AT_MOST);
1404 break;
1405 default:
1406 // Window wants to be an exact size. Force root view to be that size.
1407 measureSpec = MeasureSpec.makeMeasureSpec(rootDimension, MeasureSpec.EXACTLY);
1408 break;
1409 }
1410 return measureSpec;
1411 }
1412
Dianne Hackborn0f761d62010-11-30 22:06:10 -08001413 int mHardwareYOffset;
1414 int mResizeAlpha;
1415 final Paint mResizePaint = new Paint();
1416
1417 public void onHardwarePreDraw(Canvas canvas) {
1418 canvas.translate(0, -mHardwareYOffset);
1419 }
1420
1421 public void onHardwarePostDraw(Canvas canvas) {
1422 if (mResizeBitmap != null) {
1423 canvas.translate(0, mHardwareYOffset);
1424 mResizePaint.setAlpha(mResizeAlpha);
1425 canvas.drawBitmap(mResizeBitmap, 0, 0, mResizePaint);
1426 }
1427 }
1428
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001429 private void draw(boolean fullRedrawNeeded) {
1430 Surface surface = mSurface;
1431 if (surface == null || !surface.isValid()) {
1432 return;
1433 }
1434
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001435 if (!sFirstDrawComplete) {
1436 synchronized (sFirstDrawHandlers) {
1437 sFirstDrawComplete = true;
Romain Guy812ccbe2010-06-01 14:07:24 -07001438 final int count = sFirstDrawHandlers.size();
1439 for (int i = 0; i< count; i++) {
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001440 post(sFirstDrawHandlers.get(i));
1441 }
1442 }
1443 }
1444
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001445 scrollToRectOrFocus(null, false);
1446
1447 if (mAttachInfo.mViewScrollChanged) {
1448 mAttachInfo.mViewScrollChanged = false;
1449 mAttachInfo.mTreeObserver.dispatchOnScrollChanged();
1450 }
Romain Guy8506ab42009-06-11 17:35:47 -07001451
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001452 int yoff;
Dianne Hackborn0f761d62010-11-30 22:06:10 -08001453 boolean animating = mScroller != null && mScroller.computeScrollOffset();
1454 if (animating) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001455 yoff = mScroller.getCurrY();
1456 } else {
1457 yoff = mScrollY;
1458 }
1459 if (mCurScrollY != yoff) {
1460 mCurScrollY = yoff;
1461 fullRedrawNeeded = true;
1462 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001463 float appScale = mAttachInfo.mApplicationScale;
1464 boolean scalingRequired = mAttachInfo.mScalingRequired;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001465
Dianne Hackborn0f761d62010-11-30 22:06:10 -08001466 int resizeAlpha = 0;
1467 if (mResizeBitmap != null) {
1468 long deltaTime = SystemClock.uptimeMillis() - mResizeBitmapStartTime;
1469 if (deltaTime < mResizeBitmapDuration) {
1470 float amt = deltaTime/(float)mResizeBitmapDuration;
1471 amt = mResizeInterpolator.getInterpolation(amt);
1472 animating = true;
1473 resizeAlpha = 255 - (int)(amt*255);
1474 } else {
1475 disposeResizeBitmap();
1476 }
1477 }
1478
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001479 Rect dirty = mDirty;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001480 if (mSurfaceHolder != null) {
1481 // The app owns the surface, we won't draw.
1482 dirty.setEmpty();
Dianne Hackborn0f761d62010-11-30 22:06:10 -08001483 if (animating) {
1484 if (mScroller != null) {
1485 mScroller.abortAnimation();
1486 }
1487 disposeResizeBitmap();
1488 }
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001489 return;
1490 }
Romain Guy58ef7fb2010-09-13 12:52:37 -07001491
1492 if (fullRedrawNeeded) {
1493 mAttachInfo.mIgnoreDirtyState = true;
1494 dirty.union(0, 0, (int) (mWidth * appScale + 0.5f), (int) (mHeight * appScale + 0.5f));
1495 }
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001496
Romain Guyb051e892010-09-28 19:09:36 -07001497 if (mAttachInfo.mHardwareRenderer != null && mAttachInfo.mHardwareRenderer.isEnabled()) {
Romain Guyfd507262010-10-10 15:42:49 -07001498 if (!dirty.isEmpty() || mIsAnimating) {
Romain Guy101e2ae2010-10-11 12:41:21 -07001499 mIsAnimating = false;
Dianne Hackborn0f761d62010-11-30 22:06:10 -08001500 mHardwareYOffset = yoff;
1501 mResizeAlpha = resizeAlpha;
Romain Guy7d7b5492011-01-24 16:33:45 -08001502
1503 mCurrentDirty.set(dirty);
1504 mCurrentDirty.union(mPreviousDirty);
1505 mPreviousDirty.set(dirty);
1506 dirty.setEmpty();
1507
Romain Guyf90f8172011-01-25 22:53:24 -08001508 Rect currentDirty = mCurrentDirty;
1509 if (animating) {
1510 currentDirty = null;
1511 }
1512
1513 mAttachInfo.mHardwareRenderer.draw(mView, mAttachInfo, this, currentDirty);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001514 }
Romain Guy812ccbe2010-06-01 14:07:24 -07001515
Dianne Hackborn0f761d62010-11-30 22:06:10 -08001516 if (animating) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001517 mFullRedrawNeeded = true;
1518 scheduleTraversals();
1519 }
Romain Guy812ccbe2010-06-01 14:07:24 -07001520
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001521 return;
1522 }
1523
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001524 if (DEBUG_ORIENTATION || DEBUG_DRAW) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001525 Log.v(TAG, "Draw " + mView + "/"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001526 + mWindowAttributes.getTitle()
1527 + ": dirty={" + dirty.left + "," + dirty.top
1528 + "," + dirty.right + "," + dirty.bottom + "} surface="
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001529 + surface + " surface.isValid()=" + surface.isValid() + ", appScale:" +
1530 appScale + ", width=" + mWidth + ", height=" + mHeight);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001531 }
1532
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001533 if (!dirty.isEmpty() || mIsAnimating) {
1534 Canvas canvas;
1535 try {
1536 int left = dirty.left;
1537 int top = dirty.top;
1538 int right = dirty.right;
1539 int bottom = dirty.bottom;
Romain Guyfea12b82011-01-27 15:36:40 -08001540
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001541 canvas = surface.lockCanvas(dirty);
Romain Guy5bcdff42009-05-14 21:27:18 -07001542
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001543 if (left != dirty.left || top != dirty.top || right != dirty.right ||
1544 bottom != dirty.bottom) {
1545 mAttachInfo.mIgnoreDirtyState = true;
1546 }
1547
1548 // TODO: Do this in native
1549 canvas.setDensity(mDensity);
1550 } catch (Surface.OutOfResourcesException e) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001551 Log.e(TAG, "OutOfResourcesException locking surface", e);
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001552 // TODO: we should ask the window manager to do something!
1553 // for now we just do nothing
1554 return;
1555 } catch (IllegalArgumentException e) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001556 Log.e(TAG, "IllegalArgumentException locking surface", e);
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001557 // TODO: we should ask the window manager to do something!
1558 // for now we just do nothing
1559 return;
Romain Guy5bcdff42009-05-14 21:27:18 -07001560 }
1561
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001562 try {
1563 if (!dirty.isEmpty() || mIsAnimating) {
1564 long startTime = 0L;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001565
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001566 if (DEBUG_ORIENTATION || DEBUG_DRAW) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001567 Log.v(TAG, "Surface " + surface + " drawing to bitmap w="
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001568 + canvas.getWidth() + ", h=" + canvas.getHeight());
1569 //canvas.drawARGB(255, 255, 0, 0);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001570 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001571
Romain Guy5429e1d2010-09-07 12:38:00 -07001572 if (ViewDebug.DEBUG_PROFILE_DRAWING) {
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001573 startTime = SystemClock.elapsedRealtime();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001574 }
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001575
1576 // If this bitmap's format includes an alpha channel, we
1577 // need to clear it before drawing so that the child will
1578 // properly re-composite its drawing on a transparent
1579 // background. This automatically respects the clip/dirty region
1580 // or
1581 // If we are applying an offset, we need to clear the area
1582 // where the offset doesn't appear to avoid having garbage
1583 // left in the blank areas.
1584 if (!canvas.isOpaque() || yoff != 0) {
1585 canvas.drawColor(0, PorterDuff.Mode.CLEAR);
1586 }
1587
1588 dirty.setEmpty();
1589 mIsAnimating = false;
1590 mAttachInfo.mDrawingTime = SystemClock.uptimeMillis();
1591 mView.mPrivateFlags |= View.DRAWN;
1592
1593 if (DEBUG_DRAW) {
1594 Context cxt = mView.getContext();
1595 Log.i(TAG, "Drawing: package:" + cxt.getPackageName() +
1596 ", metrics=" + cxt.getResources().getDisplayMetrics() +
1597 ", compatibilityInfo=" + cxt.getResources().getCompatibilityInfo());
1598 }
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001599 try {
1600 canvas.translate(0, -yoff);
1601 if (mTranslator != null) {
1602 mTranslator.translateCanvas(canvas);
1603 }
1604 canvas.setScreenDensity(scalingRequired
1605 ? DisplayMetrics.DENSITY_DEVICE : 0);
1606 mView.draw(canvas);
1607 } finally {
1608 mAttachInfo.mIgnoreDirtyState = false;
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001609 }
1610
1611 if (Config.DEBUG && ViewDebug.consistencyCheckEnabled) {
1612 mView.dispatchConsistencyCheck(ViewDebug.CONSISTENCY_DRAWING);
1613 }
1614
Romain Guy5429e1d2010-09-07 12:38:00 -07001615 if (SHOW_FPS || ViewDebug.DEBUG_SHOW_FPS) {
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001616 int now = (int)SystemClock.elapsedRealtime();
1617 if (sDrawTime != 0) {
1618 nativeShowFPS(canvas, now - sDrawTime);
1619 }
1620 sDrawTime = now;
1621 }
1622
Romain Guy5429e1d2010-09-07 12:38:00 -07001623 if (ViewDebug.DEBUG_PROFILE_DRAWING) {
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001624 EventLog.writeEvent(60000, SystemClock.elapsedRealtime() - startTime);
1625 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001626 }
1627
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001628 } finally {
1629 surface.unlockCanvasAndPost(canvas);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001630 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001631 }
1632
1633 if (LOCAL_LOGV) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001634 Log.v(TAG, "Surface " + surface + " unlockCanvasAndPost");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001635 }
Romain Guy8506ab42009-06-11 17:35:47 -07001636
Dianne Hackborn0f761d62010-11-30 22:06:10 -08001637 if (animating) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001638 mFullRedrawNeeded = true;
1639 scheduleTraversals();
1640 }
1641 }
1642
1643 boolean scrollToRectOrFocus(Rect rectangle, boolean immediate) {
1644 final View.AttachInfo attachInfo = mAttachInfo;
1645 final Rect ci = attachInfo.mContentInsets;
1646 final Rect vi = attachInfo.mVisibleInsets;
1647 int scrollY = 0;
1648 boolean handled = false;
Romain Guy8506ab42009-06-11 17:35:47 -07001649
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001650 if (vi.left > ci.left || vi.top > ci.top
1651 || vi.right > ci.right || vi.bottom > ci.bottom) {
1652 // We'll assume that we aren't going to change the scroll
1653 // offset, since we want to avoid that unless it is actually
1654 // going to make the focus visible... otherwise we scroll
1655 // all over the place.
1656 scrollY = mScrollY;
1657 // We can be called for two different situations: during a draw,
1658 // to update the scroll position if the focus has changed (in which
1659 // case 'rectangle' is null), or in response to a
1660 // requestChildRectangleOnScreen() call (in which case 'rectangle'
1661 // is non-null and we just want to scroll to whatever that
1662 // rectangle is).
1663 View focus = mRealFocusedView;
Romain Guye8b16522009-07-14 13:06:42 -07001664
1665 // When in touch mode, focus points to the previously focused view,
1666 // which may have been removed from the view hierarchy. The following
Joe Onoratob71193b2009-11-24 18:34:42 -05001667 // line checks whether the view is still in our hierarchy.
1668 if (focus == null || focus.mAttachInfo != mAttachInfo) {
Romain Guye8b16522009-07-14 13:06:42 -07001669 mRealFocusedView = null;
1670 return false;
1671 }
1672
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001673 if (focus != mLastScrolledFocus) {
1674 // If the focus has changed, then ignore any requests to scroll
1675 // to a rectangle; first we want to make sure the entire focus
1676 // view is visible.
1677 rectangle = null;
1678 }
1679 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Eval scroll: focus=" + focus
1680 + " rectangle=" + rectangle + " ci=" + ci
1681 + " vi=" + vi);
1682 if (focus == mLastScrolledFocus && !mScrollMayChange
1683 && rectangle == null) {
1684 // Optimization: if the focus hasn't changed since last
1685 // time, and no layout has happened, then just leave things
1686 // as they are.
1687 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Keeping scroll y="
1688 + mScrollY + " vi=" + vi.toShortString());
1689 } else if (focus != null) {
1690 // We need to determine if the currently focused view is
1691 // within the visible part of the window and, if not, apply
1692 // a pan so it can be seen.
1693 mLastScrolledFocus = focus;
1694 mScrollMayChange = false;
1695 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Need to scroll?");
1696 // Try to find the rectangle from the focus view.
1697 if (focus.getGlobalVisibleRect(mVisRect, null)) {
1698 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Root w="
1699 + mView.getWidth() + " h=" + mView.getHeight()
1700 + " ci=" + ci.toShortString()
1701 + " vi=" + vi.toShortString());
1702 if (rectangle == null) {
1703 focus.getFocusedRect(mTempRect);
1704 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Focus " + focus
1705 + ": focusRect=" + mTempRect.toShortString());
Dianne Hackborn1c6a8942010-03-23 16:34:20 -07001706 if (mView instanceof ViewGroup) {
1707 ((ViewGroup) mView).offsetDescendantRectToMyCoords(
1708 focus, mTempRect);
1709 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001710 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1711 "Focus in window: focusRect="
1712 + mTempRect.toShortString()
1713 + " visRect=" + mVisRect.toShortString());
1714 } else {
1715 mTempRect.set(rectangle);
1716 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1717 "Request scroll to rect: "
1718 + mTempRect.toShortString()
1719 + " visRect=" + mVisRect.toShortString());
1720 }
1721 if (mTempRect.intersect(mVisRect)) {
1722 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1723 "Focus window visible rect: "
1724 + mTempRect.toShortString());
1725 if (mTempRect.height() >
1726 (mView.getHeight()-vi.top-vi.bottom)) {
1727 // If the focus simply is not going to fit, then
1728 // best is probably just to leave things as-is.
1729 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1730 "Too tall; leaving scrollY=" + scrollY);
1731 } else if ((mTempRect.top-scrollY) < vi.top) {
1732 scrollY -= vi.top - (mTempRect.top-scrollY);
1733 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1734 "Top covered; scrollY=" + scrollY);
1735 } else if ((mTempRect.bottom-scrollY)
1736 > (mView.getHeight()-vi.bottom)) {
1737 scrollY += (mTempRect.bottom-scrollY)
1738 - (mView.getHeight()-vi.bottom);
1739 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1740 "Bottom covered; scrollY=" + scrollY);
1741 }
1742 handled = true;
1743 }
1744 }
1745 }
1746 }
Romain Guy8506ab42009-06-11 17:35:47 -07001747
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001748 if (scrollY != mScrollY) {
1749 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Pan scroll changed: old="
1750 + mScrollY + " , new=" + scrollY);
Dianne Hackborn0f761d62010-11-30 22:06:10 -08001751 if (!immediate && mResizeBitmap == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001752 if (mScroller == null) {
1753 mScroller = new Scroller(mView.getContext());
1754 }
1755 mScroller.startScroll(0, mScrollY, 0, scrollY-mScrollY);
1756 } else if (mScroller != null) {
1757 mScroller.abortAnimation();
1758 }
1759 mScrollY = scrollY;
1760 }
Romain Guy8506ab42009-06-11 17:35:47 -07001761
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001762 return handled;
1763 }
Romain Guy8506ab42009-06-11 17:35:47 -07001764
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001765 public void requestChildFocus(View child, View focused) {
1766 checkThread();
1767 if (mFocusedView != focused) {
1768 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(mFocusedView, focused);
1769 scheduleTraversals();
1770 }
1771 mFocusedView = mRealFocusedView = focused;
1772 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Request child focus: focus now "
1773 + mFocusedView);
1774 }
1775
1776 public void clearChildFocus(View child) {
1777 checkThread();
1778
1779 View oldFocus = mFocusedView;
1780
1781 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Clearing child focus");
1782 mFocusedView = mRealFocusedView = null;
1783 if (mView != null && !mView.hasFocus()) {
1784 // If a view gets the focus, the listener will be invoked from requestChildFocus()
1785 if (!mView.requestFocus(View.FOCUS_FORWARD)) {
1786 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
1787 }
1788 } else if (oldFocus != null) {
1789 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
1790 }
1791 }
1792
1793
1794 public void focusableViewAvailable(View v) {
1795 checkThread();
1796
1797 if (mView != null && !mView.hasFocus()) {
1798 v.requestFocus();
1799 } else {
1800 // the one case where will transfer focus away from the current one
1801 // is if the current view is a view group that prefers to give focus
1802 // to its children first AND the view is a descendant of it.
1803 mFocusedView = mView.findFocus();
1804 boolean descendantsHaveDibsOnFocus =
1805 (mFocusedView instanceof ViewGroup) &&
1806 (((ViewGroup) mFocusedView).getDescendantFocusability() ==
1807 ViewGroup.FOCUS_AFTER_DESCENDANTS);
1808 if (descendantsHaveDibsOnFocus && isViewDescendantOf(v, mFocusedView)) {
1809 // If a view gets the focus, the listener will be invoked from requestChildFocus()
1810 v.requestFocus();
1811 }
1812 }
1813 }
1814
1815 public void recomputeViewAttributes(View child) {
1816 checkThread();
1817 if (mView == child) {
1818 mAttachInfo.mRecomputeGlobalAttributes = true;
1819 if (!mWillDrawSoon) {
1820 scheduleTraversals();
1821 }
1822 }
1823 }
1824
1825 void dispatchDetachedFromWindow() {
Romain Guy90fc03b2011-01-16 13:07:15 -08001826 if (mView != null && mView.mAttachInfo != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001827 mView.dispatchDetachedFromWindow();
1828 }
1829
1830 mView = null;
1831 mAttachInfo.mRootView = null;
Mathias Agopian5583dc62009-07-09 16:28:11 -07001832 mAttachInfo.mSurface = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001833
Romain Guy29d89972010-09-22 16:10:57 -07001834 destroyHardwareRenderer();
Romain Guy4caa4ed2010-08-25 14:46:24 -07001835
Dianne Hackborn0586a1b2009-09-06 21:08:27 -07001836 mSurface.release();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001837
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001838 if (mInputChannel != null) {
1839 if (mInputQueueCallback != null) {
1840 mInputQueueCallback.onInputQueueDestroyed(mInputQueue);
1841 mInputQueueCallback = null;
1842 } else {
1843 InputQueue.unregisterInputChannel(mInputChannel);
Jeff Brown46b9ac02010-04-22 18:58:52 -07001844 }
1845 }
1846
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001847 try {
1848 sWindowSession.remove(mWindow);
1849 } catch (RemoteException e) {
1850 }
Jeff Brown349703e2010-06-22 01:27:15 -07001851
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001852 // Dispose the input channel after removing the window so the Window Manager
1853 // doesn't interpret the input channel being closed as an abnormal termination.
1854 if (mInputChannel != null) {
1855 mInputChannel.dispose();
1856 mInputChannel = null;
Jeff Brown349703e2010-06-22 01:27:15 -07001857 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001858 }
Romain Guy8506ab42009-06-11 17:35:47 -07001859
Dianne Hackborn694f79b2010-03-17 19:44:59 -07001860 void updateConfiguration(Configuration config, boolean force) {
1861 if (DEBUG_CONFIGURATION) Log.v(TAG,
1862 "Applying new config to window "
1863 + mWindowAttributes.getTitle()
1864 + ": " + config);
1865 synchronized (sConfigCallbacks) {
1866 for (int i=sConfigCallbacks.size()-1; i>=0; i--) {
1867 sConfigCallbacks.get(i).onConfigurationChanged(config);
1868 }
1869 }
1870 if (mView != null) {
1871 // At this point the resources have been updated to
1872 // have the most recent config, whatever that is. Use
1873 // the on in them which may be newer.
1874 if (mView != null) {
1875 config = mView.getResources().getConfiguration();
1876 }
1877 if (force || mLastConfiguration.diff(config) != 0) {
1878 mLastConfiguration.setTo(config);
1879 mView.dispatchConfigurationChanged(config);
1880 }
1881 }
1882 }
1883
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001884 /**
1885 * Return true if child is an ancestor of parent, (or equal to the parent).
1886 */
1887 private static boolean isViewDescendantOf(View child, View parent) {
1888 if (child == parent) {
1889 return true;
1890 }
1891
1892 final ViewParent theParent = child.getParent();
1893 return (theParent instanceof ViewGroup) && isViewDescendantOf((View) theParent, parent);
1894 }
1895
Romain Guycdb86672010-03-18 18:54:50 -07001896 private static void forceLayout(View view) {
1897 view.forceLayout();
1898 if (view instanceof ViewGroup) {
1899 ViewGroup group = (ViewGroup) view;
1900 final int count = group.getChildCount();
1901 for (int i = 0; i < count; i++) {
1902 forceLayout(group.getChildAt(i));
1903 }
1904 }
1905 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001906
1907 public final static int DO_TRAVERSAL = 1000;
1908 public final static int DIE = 1001;
1909 public final static int RESIZED = 1002;
1910 public final static int RESIZED_REPORT = 1003;
1911 public final static int WINDOW_FOCUS_CHANGED = 1004;
1912 public final static int DISPATCH_KEY = 1005;
1913 public final static int DISPATCH_POINTER = 1006;
1914 public final static int DISPATCH_TRACKBALL = 1007;
1915 public final static int DISPATCH_APP_VISIBILITY = 1008;
1916 public final static int DISPATCH_GET_NEW_SURFACE = 1009;
1917 public final static int FINISHED_EVENT = 1010;
1918 public final static int DISPATCH_KEY_FROM_IME = 1011;
1919 public final static int FINISH_INPUT_CONNECTION = 1012;
1920 public final static int CHECK_FOCUS = 1013;
Dianne Hackbornffa42482009-09-23 22:20:11 -07001921 public final static int CLOSE_SYSTEM_DIALOGS = 1014;
Christopher Tatea53146c2010-09-07 11:57:52 -07001922 public final static int DISPATCH_DRAG_EVENT = 1015;
Chris Tate91e9bb32010-10-12 12:58:43 -07001923 public final static int DISPATCH_DRAG_LOCATION_EVENT = 1016;
Joe Onorato664644d2011-01-23 17:53:23 -08001924 public final static int DISPATCH_SYSTEM_UI_VISIBILITY = 1017;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001925
1926 @Override
1927 public void handleMessage(Message msg) {
1928 switch (msg.what) {
1929 case View.AttachInfo.INVALIDATE_MSG:
1930 ((View) msg.obj).invalidate();
1931 break;
1932 case View.AttachInfo.INVALIDATE_RECT_MSG:
1933 final View.AttachInfo.InvalidateInfo info = (View.AttachInfo.InvalidateInfo) msg.obj;
1934 info.target.invalidate(info.left, info.top, info.right, info.bottom);
1935 info.release();
1936 break;
1937 case DO_TRAVERSAL:
1938 if (mProfile) {
1939 Debug.startMethodTracing("ViewRoot");
1940 }
1941
1942 performTraversals();
1943
1944 if (mProfile) {
1945 Debug.stopMethodTracing();
1946 mProfile = false;
1947 }
1948 break;
1949 case FINISHED_EVENT:
1950 handleFinishedEvent(msg.arg1, msg.arg2 != 0);
1951 break;
1952 case DISPATCH_KEY:
Jeff Brown92ff1dd2010-08-11 16:16:06 -07001953 deliverKeyEvent((KeyEvent)msg.obj, msg.arg1 != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001954 break;
Jeff Brown3915bb82010-11-05 15:02:16 -07001955 case DISPATCH_POINTER:
1956 deliverPointerEvent((MotionEvent) msg.obj, msg.arg1 != 0);
1957 break;
1958 case DISPATCH_TRACKBALL:
1959 deliverTrackballEvent((MotionEvent) msg.obj, msg.arg1 != 0);
1960 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001961 case DISPATCH_APP_VISIBILITY:
1962 handleAppVisibility(msg.arg1 != 0);
1963 break;
1964 case DISPATCH_GET_NEW_SURFACE:
1965 handleGetNewSurface();
1966 break;
1967 case RESIZED:
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001968 ResizedInfo ri = (ResizedInfo)msg.obj;
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001969
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001970 if (mWinFrame.width() == msg.arg1 && mWinFrame.height() == msg.arg2
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001971 && mPendingContentInsets.equals(ri.coveredInsets)
Dianne Hackbornd49258f2010-03-26 00:44:29 -07001972 && mPendingVisibleInsets.equals(ri.visibleInsets)
1973 && ((ResizedInfo)msg.obj).newConfig == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001974 break;
1975 }
1976 // fall through...
1977 case RESIZED_REPORT:
1978 if (mAdded) {
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001979 Configuration config = ((ResizedInfo)msg.obj).newConfig;
1980 if (config != null) {
Dianne Hackborn694f79b2010-03-17 19:44:59 -07001981 updateConfiguration(config, false);
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001982 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001983 mWinFrame.left = 0;
1984 mWinFrame.right = msg.arg1;
1985 mWinFrame.top = 0;
1986 mWinFrame.bottom = msg.arg2;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001987 mPendingContentInsets.set(((ResizedInfo)msg.obj).coveredInsets);
1988 mPendingVisibleInsets.set(((ResizedInfo)msg.obj).visibleInsets);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001989 if (msg.what == RESIZED_REPORT) {
1990 mReportNextDraw = true;
1991 }
Romain Guycdb86672010-03-18 18:54:50 -07001992
1993 if (mView != null) {
1994 forceLayout(mView);
1995 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001996 requestLayout();
1997 }
1998 break;
1999 case WINDOW_FOCUS_CHANGED: {
2000 if (mAdded) {
2001 boolean hasWindowFocus = msg.arg1 != 0;
2002 mAttachInfo.mHasWindowFocus = hasWindowFocus;
2003 if (hasWindowFocus) {
2004 boolean inTouchMode = msg.arg2 != 0;
Romain Guy2d4cff62010-04-09 15:39:00 -07002005 ensureTouchModeLocally(inTouchMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002006
Romain Guyc361da82010-10-25 15:29:10 -07002007 if (mAttachInfo.mHardwareRenderer != null &&
2008 mSurface != null && mSurface.isValid()) {
Romain Guy7d7b5492011-01-24 16:33:45 -08002009 mFullRedrawNeeded = true;
Romain Guyb051e892010-09-28 19:09:36 -07002010 mAttachInfo.mHardwareRenderer.initializeIfNeeded(mWidth, mHeight,
2011 mAttachInfo, mHolder);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002012 }
2013 }
Romain Guy8506ab42009-06-11 17:35:47 -07002014
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002015 mLastWasImTarget = WindowManager.LayoutParams
2016 .mayUseInputMethod(mWindowAttributes.flags);
Romain Guy8506ab42009-06-11 17:35:47 -07002017
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002018 InputMethodManager imm = InputMethodManager.peekInstance();
2019 if (mView != null) {
2020 if (hasWindowFocus && imm != null && mLastWasImTarget) {
2021 imm.startGettingWindowFocus(mView);
2022 }
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07002023 mAttachInfo.mKeyDispatchState.reset();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002024 mView.dispatchWindowFocusChanged(hasWindowFocus);
2025 }
svetoslavganov75986cf2009-05-14 22:28:01 -07002026
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002027 // Note: must be done after the focus change callbacks,
2028 // so all of the view state is set up correctly.
2029 if (hasWindowFocus) {
2030 if (imm != null && mLastWasImTarget) {
2031 imm.onWindowFocus(mView, mView.findFocus(),
2032 mWindowAttributes.softInputMode,
2033 !mHasHadWindowFocus, mWindowAttributes.flags);
2034 }
2035 // Clear the forward bit. We can just do this directly, since
2036 // the window manager doesn't care about it.
2037 mWindowAttributes.softInputMode &=
2038 ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
2039 ((WindowManager.LayoutParams)mView.getLayoutParams())
2040 .softInputMode &=
2041 ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
2042 mHasHadWindowFocus = true;
2043 }
svetoslavganov75986cf2009-05-14 22:28:01 -07002044
2045 if (hasWindowFocus && mView != null) {
2046 sendAccessibilityEvents();
2047 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002048 }
2049 } break;
2050 case DIE:
Dianne Hackborn94d69142009-09-28 22:14:42 -07002051 doDie();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002052 break;
The Android Open Source Project10592532009-03-18 17:39:46 -07002053 case DISPATCH_KEY_FROM_IME: {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002054 if (LOCAL_LOGV) Log.v(
Jeff Brownc5ed5912010-07-14 18:48:53 -07002055 TAG, "Dispatching key "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002056 + msg.obj + " from IME to " + mView);
The Android Open Source Project10592532009-03-18 17:39:46 -07002057 KeyEvent event = (KeyEvent)msg.obj;
2058 if ((event.getFlags()&KeyEvent.FLAG_FROM_SYSTEM) != 0) {
2059 // The IME is trying to say this event is from the
2060 // system! Bad bad bad!
Romain Guy812ccbe2010-06-01 14:07:24 -07002061 event = KeyEvent.changeFlags(event, event.getFlags() & ~KeyEvent.FLAG_FROM_SYSTEM);
The Android Open Source Project10592532009-03-18 17:39:46 -07002062 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002063 deliverKeyEventPostIme((KeyEvent)msg.obj, false);
The Android Open Source Project10592532009-03-18 17:39:46 -07002064 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002065 case FINISH_INPUT_CONNECTION: {
2066 InputMethodManager imm = InputMethodManager.peekInstance();
2067 if (imm != null) {
2068 imm.reportFinishInputConnection((InputConnection)msg.obj);
2069 }
2070 } break;
2071 case CHECK_FOCUS: {
2072 InputMethodManager imm = InputMethodManager.peekInstance();
2073 if (imm != null) {
2074 imm.checkFocus();
2075 }
2076 } break;
Dianne Hackbornffa42482009-09-23 22:20:11 -07002077 case CLOSE_SYSTEM_DIALOGS: {
2078 if (mView != null) {
2079 mView.onCloseSystemDialogs((String)msg.obj);
2080 }
2081 } break;
Chris Tate91e9bb32010-10-12 12:58:43 -07002082 case DISPATCH_DRAG_EVENT:
2083 case DISPATCH_DRAG_LOCATION_EVENT: {
Christopher Tate7fb8b562011-01-20 13:46:41 -08002084 DragEvent event = (DragEvent)msg.obj;
2085 event.mLocalState = mLocalDragState; // only present when this app called startDrag()
2086 handleDragEvent(event);
Christopher Tatea53146c2010-09-07 11:57:52 -07002087 } break;
Joe Onorato664644d2011-01-23 17:53:23 -08002088 case DISPATCH_SYSTEM_UI_VISIBILITY: {
2089 handleDispatchSystemUiVisibilityChanged(msg.arg1);
2090 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002091 }
2092 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002093
Jeff Brown3915bb82010-11-05 15:02:16 -07002094 private void startInputEvent(InputQueue.FinishedCallback finishedCallback) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07002095 if (mFinishedCallback != null) {
2096 Slog.w(TAG, "Received a new input event from the input queue but there is "
2097 + "already an unfinished input event in progress.");
2098 }
2099
2100 mFinishedCallback = finishedCallback;
2101 }
2102
Jeff Brown3915bb82010-11-05 15:02:16 -07002103 private void finishInputEvent(boolean handled) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07002104 if (LOCAL_LOGV) Log.v(TAG, "Telling window manager input event is finished");
Jeff Brown92ff1dd2010-08-11 16:16:06 -07002105
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002106 if (mFinishedCallback != null) {
Jeff Brown3915bb82010-11-05 15:02:16 -07002107 mFinishedCallback.finished(handled);
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002108 mFinishedCallback = null;
Jeff Brown92ff1dd2010-08-11 16:16:06 -07002109 } else {
Jeff Brown93ed4e32010-09-23 13:51:48 -07002110 Slog.w(TAG, "Attempted to tell the input queue that the current input event "
2111 + "is finished but there is no input event actually in progress.");
Jeff Brown46b9ac02010-04-22 18:58:52 -07002112 }
2113 }
2114
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002115 /**
2116 * Something in the current window tells us we need to change the touch mode. For
2117 * example, we are not in touch mode, and the user touches the screen.
2118 *
2119 * If the touch mode has changed, tell the window manager, and handle it locally.
2120 *
2121 * @param inTouchMode Whether we want to be in touch mode.
2122 * @return True if the touch mode changed and focus changed was changed as a result
2123 */
2124 boolean ensureTouchMode(boolean inTouchMode) {
2125 if (DBG) Log.d("touchmode", "ensureTouchMode(" + inTouchMode + "), current "
2126 + "touch mode is " + mAttachInfo.mInTouchMode);
2127 if (mAttachInfo.mInTouchMode == inTouchMode) return false;
2128
2129 // tell the window manager
2130 try {
2131 sWindowSession.setInTouchMode(inTouchMode);
2132 } catch (RemoteException e) {
2133 throw new RuntimeException(e);
2134 }
2135
2136 // handle the change
Romain Guy2d4cff62010-04-09 15:39:00 -07002137 return ensureTouchModeLocally(inTouchMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002138 }
2139
2140 /**
2141 * Ensure that the touch mode for this window is set, and if it is changing,
2142 * take the appropriate action.
2143 * @param inTouchMode Whether we want to be in touch mode.
2144 * @return True if the touch mode changed and focus changed was changed as a result
2145 */
Romain Guy2d4cff62010-04-09 15:39:00 -07002146 private boolean ensureTouchModeLocally(boolean inTouchMode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002147 if (DBG) Log.d("touchmode", "ensureTouchModeLocally(" + inTouchMode + "), current "
2148 + "touch mode is " + mAttachInfo.mInTouchMode);
2149
2150 if (mAttachInfo.mInTouchMode == inTouchMode) return false;
2151
2152 mAttachInfo.mInTouchMode = inTouchMode;
2153 mAttachInfo.mTreeObserver.dispatchOnTouchModeChanged(inTouchMode);
2154
Romain Guy2d4cff62010-04-09 15:39:00 -07002155 return (inTouchMode) ? enterTouchMode() : leaveTouchMode();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002156 }
2157
2158 private boolean enterTouchMode() {
2159 if (mView != null) {
2160 if (mView.hasFocus()) {
2161 // note: not relying on mFocusedView here because this could
2162 // be when the window is first being added, and mFocused isn't
2163 // set yet.
2164 final View focused = mView.findFocus();
2165 if (focused != null && !focused.isFocusableInTouchMode()) {
2166
2167 final ViewGroup ancestorToTakeFocus =
2168 findAncestorToTakeFocusInTouchMode(focused);
2169 if (ancestorToTakeFocus != null) {
2170 // there is an ancestor that wants focus after its descendants that
2171 // is focusable in touch mode.. give it focus
2172 return ancestorToTakeFocus.requestFocus();
2173 } else {
2174 // nothing appropriate to have focus in touch mode, clear it out
2175 mView.unFocus();
2176 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(focused, null);
2177 mFocusedView = null;
2178 return true;
2179 }
2180 }
2181 }
2182 }
2183 return false;
2184 }
2185
2186
2187 /**
2188 * Find an ancestor of focused that wants focus after its descendants and is
2189 * focusable in touch mode.
2190 * @param focused The currently focused view.
2191 * @return An appropriate view, or null if no such view exists.
2192 */
2193 private ViewGroup findAncestorToTakeFocusInTouchMode(View focused) {
2194 ViewParent parent = focused.getParent();
2195 while (parent instanceof ViewGroup) {
2196 final ViewGroup vgParent = (ViewGroup) parent;
2197 if (vgParent.getDescendantFocusability() == ViewGroup.FOCUS_AFTER_DESCENDANTS
2198 && vgParent.isFocusableInTouchMode()) {
2199 return vgParent;
2200 }
2201 if (vgParent.isRootNamespace()) {
2202 return null;
2203 } else {
2204 parent = vgParent.getParent();
2205 }
2206 }
2207 return null;
2208 }
2209
2210 private boolean leaveTouchMode() {
2211 if (mView != null) {
2212 if (mView.hasFocus()) {
2213 // i learned the hard way to not trust mFocusedView :)
2214 mFocusedView = mView.findFocus();
2215 if (!(mFocusedView instanceof ViewGroup)) {
2216 // some view has focus, let it keep it
2217 return false;
2218 } else if (((ViewGroup)mFocusedView).getDescendantFocusability() !=
2219 ViewGroup.FOCUS_AFTER_DESCENDANTS) {
2220 // some view group has focus, and doesn't prefer its children
2221 // over itself for focus, so let them keep it.
2222 return false;
2223 }
2224 }
2225
2226 // find the best view to give focus to in this brave new non-touch-mode
2227 // world
2228 final View focused = focusSearch(null, View.FOCUS_DOWN);
2229 if (focused != null) {
2230 return focused.requestFocus(View.FOCUS_DOWN);
2231 }
2232 }
2233 return false;
2234 }
2235
Jeff Brown3915bb82010-11-05 15:02:16 -07002236 private void deliverPointerEvent(MotionEvent event, boolean sendDone) {
2237 // If there is no view, then the event will not be handled.
2238 if (mView == null || !mAdded) {
2239 finishPointerEvent(event, sendDone, false);
2240 return;
2241 }
2242
2243 // Translate the pointer event for compatibility, if needed.
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002244 if (mTranslator != null) {
2245 mTranslator.translateEventInScreenToAppWindow(event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002246 }
2247
Jeff Brown3915bb82010-11-05 15:02:16 -07002248 // Enter touch mode on the down.
2249 boolean isDown = event.getAction() == MotionEvent.ACTION_DOWN;
2250 if (isDown) {
2251 ensureTouchMode(true);
2252 }
2253 if(Config.LOGV) {
2254 captureMotionLog("captureDispatchPointer", event);
2255 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002256
Jeff Brown3915bb82010-11-05 15:02:16 -07002257 // Offset the scroll position.
2258 if (mCurScrollY != 0) {
2259 event.offsetLocation(0, mCurScrollY);
2260 }
2261 if (MEASURE_LATENCY) {
2262 lt.sample("A Dispatching TouchEvents", System.nanoTime() - event.getEventTimeNano());
2263 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002264
Jeff Brown3915bb82010-11-05 15:02:16 -07002265 // Remember the touch position for possible drag-initiation.
2266 mLastTouchPoint.x = event.getRawX();
2267 mLastTouchPoint.y = event.getRawY();
2268
2269 // Dispatch touch to view hierarchy.
2270 boolean handled = mView.dispatchTouchEvent(event);
2271 if (MEASURE_LATENCY) {
2272 lt.sample("B Dispatched TouchEvents ", System.nanoTime() - event.getEventTimeNano());
2273 }
2274 if (handled) {
2275 finishPointerEvent(event, sendDone, true);
2276 return;
2277 }
2278
2279 // Apply edge slop and try again, if appropriate.
2280 final int edgeFlags = event.getEdgeFlags();
2281 if (edgeFlags != 0 && mView instanceof ViewGroup) {
2282 final int edgeSlop = mViewConfiguration.getScaledEdgeSlop();
2283 int direction = View.FOCUS_UP;
2284 int x = (int)event.getX();
2285 int y = (int)event.getY();
2286 final int[] deltas = new int[2];
2287
2288 if ((edgeFlags & MotionEvent.EDGE_TOP) != 0) {
2289 direction = View.FOCUS_DOWN;
2290 if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
2291 deltas[0] = edgeSlop;
2292 x += edgeSlop;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002293 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
Jeff Brown3915bb82010-11-05 15:02:16 -07002294 deltas[0] = -edgeSlop;
2295 x -= edgeSlop;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002296 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002297 } else if ((edgeFlags & MotionEvent.EDGE_BOTTOM) != 0) {
2298 direction = View.FOCUS_UP;
2299 if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
2300 deltas[0] = edgeSlop;
2301 x += edgeSlop;
2302 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
2303 deltas[0] = -edgeSlop;
2304 x -= edgeSlop;
2305 }
2306 } else if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
2307 direction = View.FOCUS_RIGHT;
2308 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
2309 direction = View.FOCUS_LEFT;
2310 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002311
Jeff Brown3915bb82010-11-05 15:02:16 -07002312 View nearest = FocusFinder.getInstance().findNearestTouchable(
2313 ((ViewGroup) mView), x, y, direction, deltas);
2314 if (nearest != null) {
2315 event.offsetLocation(deltas[0], deltas[1]);
2316 event.setEdgeFlags(0);
2317 if (mView.dispatchTouchEvent(event)) {
2318 finishPointerEvent(event, sendDone, true);
2319 return;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002320 }
2321 }
2322 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002323
2324 // Pointer event was unhandled.
2325 finishPointerEvent(event, sendDone, false);
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002326 }
2327
Jeff Brown3915bb82010-11-05 15:02:16 -07002328 private void finishPointerEvent(MotionEvent event, boolean sendDone, boolean handled) {
2329 event.recycle();
2330 if (sendDone) {
2331 finishInputEvent(handled);
2332 }
2333 if (LOCAL_LOGV || WATCH_POINTER) Log.i(TAG, "Done dispatching!");
2334 }
2335
2336 private void deliverTrackballEvent(MotionEvent event, boolean sendDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002337 if (DEBUG_TRACKBALL) Log.v(TAG, "Motion event:" + event);
2338
Jeff Brown3915bb82010-11-05 15:02:16 -07002339 // If there is no view, then the event will not be handled.
2340 if (mView == null || !mAdded) {
2341 finishTrackballEvent(event, sendDone, false);
2342 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002343 }
2344
Jeff Brown3915bb82010-11-05 15:02:16 -07002345 // Deliver the trackball event to the view.
2346 if (mView.dispatchTrackballEvent(event)) {
2347 // If we reach this, we delivered a trackball event to mView and
2348 // mView consumed it. Because we will not translate the trackball
2349 // event into a key event, touch mode will not exit, so we exit
2350 // touch mode here.
2351 ensureTouchMode(false);
2352
2353 finishTrackballEvent(event, sendDone, true);
2354 mLastTrackballTime = Integer.MIN_VALUE;
2355 return;
2356 }
2357
2358 // Translate the trackball event into DPAD keys and try to deliver those.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002359 final TrackballAxis x = mTrackballAxisX;
2360 final TrackballAxis y = mTrackballAxisY;
2361
2362 long curTime = SystemClock.uptimeMillis();
Jeff Brown3915bb82010-11-05 15:02:16 -07002363 if ((mLastTrackballTime + MAX_TRACKBALL_DELAY) < curTime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002364 // It has been too long since the last movement,
2365 // so restart at the beginning.
2366 x.reset(0);
2367 y.reset(0);
2368 mLastTrackballTime = curTime;
2369 }
2370
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002371 final int action = event.getAction();
Jeff Brown49ed71d2010-12-06 17:13:33 -08002372 final int metaState = event.getMetaState();
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002373 switch (action) {
2374 case MotionEvent.ACTION_DOWN:
2375 x.reset(2);
2376 y.reset(2);
2377 deliverKeyEvent(new KeyEvent(curTime, curTime,
Jeff Brown49ed71d2010-12-06 17:13:33 -08002378 KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_CENTER, 0, metaState,
2379 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
2380 InputDevice.SOURCE_KEYBOARD), false);
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002381 break;
2382 case MotionEvent.ACTION_UP:
2383 x.reset(2);
2384 y.reset(2);
2385 deliverKeyEvent(new KeyEvent(curTime, curTime,
Jeff Brown49ed71d2010-12-06 17:13:33 -08002386 KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_CENTER, 0, metaState,
2387 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
2388 InputDevice.SOURCE_KEYBOARD), false);
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002389 break;
2390 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002391
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002392 if (DEBUG_TRACKBALL) Log.v(TAG, "TB X=" + x.position + " step="
2393 + x.step + " dir=" + x.dir + " acc=" + x.acceleration
2394 + " move=" + event.getX()
2395 + " / Y=" + y.position + " step="
2396 + y.step + " dir=" + y.dir + " acc=" + y.acceleration
2397 + " move=" + event.getY());
2398 final float xOff = x.collect(event.getX(), event.getEventTime(), "X");
2399 final float yOff = y.collect(event.getY(), event.getEventTime(), "Y");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002400
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002401 // Generate DPAD events based on the trackball movement.
2402 // We pick the axis that has moved the most as the direction of
2403 // the DPAD. When we generate DPAD events for one axis, then the
2404 // other axis is reset -- we don't want to perform DPAD jumps due
2405 // to slight movements in the trackball when making major movements
2406 // along the other axis.
2407 int keycode = 0;
2408 int movement = 0;
2409 float accel = 1;
2410 if (xOff > yOff) {
2411 movement = x.generate((2/event.getXPrecision()));
2412 if (movement != 0) {
2413 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_RIGHT
2414 : KeyEvent.KEYCODE_DPAD_LEFT;
2415 accel = x.acceleration;
2416 y.reset(2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002417 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002418 } else if (yOff > 0) {
2419 movement = y.generate((2/event.getYPrecision()));
2420 if (movement != 0) {
2421 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_DOWN
2422 : KeyEvent.KEYCODE_DPAD_UP;
2423 accel = y.acceleration;
2424 x.reset(2);
2425 }
2426 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002427
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002428 if (keycode != 0) {
2429 if (movement < 0) movement = -movement;
2430 int accelMovement = (int)(movement * accel);
2431 if (DEBUG_TRACKBALL) Log.v(TAG, "Move: movement=" + movement
2432 + " accelMovement=" + accelMovement
2433 + " accel=" + accel);
2434 if (accelMovement > movement) {
2435 if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: "
2436 + keycode);
2437 movement--;
Jeff Brown49ed71d2010-12-06 17:13:33 -08002438 int repeatCount = accelMovement - movement;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002439 deliverKeyEvent(new KeyEvent(curTime, curTime,
Jeff Brown49ed71d2010-12-06 17:13:33 -08002440 KeyEvent.ACTION_MULTIPLE, keycode, repeatCount, metaState,
2441 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
2442 InputDevice.SOURCE_KEYBOARD), false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002443 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002444 while (movement > 0) {
2445 if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: "
2446 + keycode);
2447 movement--;
2448 curTime = SystemClock.uptimeMillis();
2449 deliverKeyEvent(new KeyEvent(curTime, curTime,
Jeff Brown49ed71d2010-12-06 17:13:33 -08002450 KeyEvent.ACTION_DOWN, keycode, 0, metaState,
2451 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
2452 InputDevice.SOURCE_KEYBOARD), false);
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002453 deliverKeyEvent(new KeyEvent(curTime, curTime,
Jeff Brown49ed71d2010-12-06 17:13:33 -08002454 KeyEvent.ACTION_UP, keycode, 0, metaState,
2455 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
2456 InputDevice.SOURCE_KEYBOARD), false);
2457 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002458 mLastTrackballTime = curTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002459 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002460
2461 // Unfortunately we can't tell whether the application consumed the keys, so
2462 // we always consider the trackball event handled.
2463 finishTrackballEvent(event, sendDone, true);
2464 }
2465
2466 private void finishTrackballEvent(MotionEvent event, boolean sendDone, boolean handled) {
2467 event.recycle();
2468 if (sendDone) {
2469 finishInputEvent(handled);
2470 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002471 }
2472
2473 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08002474 * Returns true if the key is used for keyboard navigation.
2475 * @param keyEvent The key event.
2476 * @return True if the key is used for keyboard navigation.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002477 */
Jeff Brown4e6319b2010-12-13 10:36:51 -08002478 private static boolean isNavigationKey(KeyEvent keyEvent) {
2479 switch (keyEvent.getKeyCode()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002480 case KeyEvent.KEYCODE_DPAD_LEFT:
2481 case KeyEvent.KEYCODE_DPAD_RIGHT:
2482 case KeyEvent.KEYCODE_DPAD_UP:
2483 case KeyEvent.KEYCODE_DPAD_DOWN:
Jeff Brown4e6319b2010-12-13 10:36:51 -08002484 case KeyEvent.KEYCODE_DPAD_CENTER:
2485 case KeyEvent.KEYCODE_PAGE_UP:
2486 case KeyEvent.KEYCODE_PAGE_DOWN:
2487 case KeyEvent.KEYCODE_MOVE_HOME:
2488 case KeyEvent.KEYCODE_MOVE_END:
2489 case KeyEvent.KEYCODE_TAB:
2490 case KeyEvent.KEYCODE_SPACE:
2491 case KeyEvent.KEYCODE_ENTER:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002492 return true;
2493 }
2494 return false;
2495 }
2496
2497 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08002498 * Returns true if the key is used for typing.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002499 * @param keyEvent The key event.
Jeff Brown4e6319b2010-12-13 10:36:51 -08002500 * @return True if the key is used for typing.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002501 */
Jeff Brown4e6319b2010-12-13 10:36:51 -08002502 private static boolean isTypingKey(KeyEvent keyEvent) {
2503 return keyEvent.getUnicodeChar() > 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002504 }
2505
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002506 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08002507 * 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 -08002508 * @param event The key event.
2509 * @return Whether this key event should be consumed (meaning the act of
2510 * leaving touch mode alone is considered the event).
2511 */
2512 private boolean checkForLeavingTouchModeAndConsume(KeyEvent event) {
Jeff Brown4e6319b2010-12-13 10:36:51 -08002513 // Only relevant in touch mode.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002514 if (!mAttachInfo.mInTouchMode) {
2515 return false;
2516 }
2517
Jeff Brown4e6319b2010-12-13 10:36:51 -08002518 // Only consider leaving touch mode on DOWN or MULTIPLE actions, never on UP.
2519 final int action = event.getAction();
2520 if (action != KeyEvent.ACTION_DOWN && action != KeyEvent.ACTION_MULTIPLE) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002521 return false;
2522 }
2523
Jeff Brown4e6319b2010-12-13 10:36:51 -08002524 // Don't leave touch mode if the IME told us not to.
2525 if ((event.getFlags() & KeyEvent.FLAG_KEEP_TOUCH_MODE) != 0) {
2526 return false;
2527 }
2528
2529 // If the key can be used for keyboard navigation then leave touch mode
2530 // and select a focused view if needed (in ensureTouchMode).
2531 // When a new focused view is selected, we consume the navigation key because
2532 // navigation doesn't make much sense unless a view already has focus so
2533 // the key's purpose is to set focus.
2534 if (isNavigationKey(event)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002535 return ensureTouchMode(false);
2536 }
Jeff Brown4e6319b2010-12-13 10:36:51 -08002537
2538 // If the key can be used for typing then leave touch mode
2539 // and select a focused view if needed (in ensureTouchMode).
2540 // Always allow the view to process the typing key.
2541 if (isTypingKey(event)) {
2542 ensureTouchMode(false);
2543 return false;
2544 }
2545
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002546 return false;
2547 }
2548
2549 /**
Romain Guy8506ab42009-06-11 17:35:47 -07002550 * log motion events
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002551 */
2552 private static void captureMotionLog(String subTag, MotionEvent ev) {
Romain Guy8506ab42009-06-11 17:35:47 -07002553 //check dynamic switch
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002554 if (ev == null ||
2555 SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_EVENT, 0) == 0) {
2556 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002557 }
Romain Guy8506ab42009-06-11 17:35:47 -07002558
2559 StringBuilder sb = new StringBuilder(subTag + ": ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002560 sb.append(ev.getDownTime()).append(',');
2561 sb.append(ev.getEventTime()).append(',');
2562 sb.append(ev.getAction()).append(',');
Romain Guy8506ab42009-06-11 17:35:47 -07002563 sb.append(ev.getX()).append(',');
2564 sb.append(ev.getY()).append(',');
2565 sb.append(ev.getPressure()).append(',');
2566 sb.append(ev.getSize()).append(',');
2567 sb.append(ev.getMetaState()).append(',');
2568 sb.append(ev.getXPrecision()).append(',');
2569 sb.append(ev.getYPrecision()).append(',');
2570 sb.append(ev.getDeviceId()).append(',');
2571 sb.append(ev.getEdgeFlags());
2572 Log.d(TAG, sb.toString());
2573 }
2574 /**
2575 * log motion events
2576 */
2577 private static void captureKeyLog(String subTag, KeyEvent ev) {
2578 //check dynamic switch
2579 if (ev == null ||
2580 SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_EVENT, 0) == 0) {
2581 return;
2582 }
2583 StringBuilder sb = new StringBuilder(subTag + ": ");
2584 sb.append(ev.getDownTime()).append(',');
2585 sb.append(ev.getEventTime()).append(',');
2586 sb.append(ev.getAction()).append(',');
2587 sb.append(ev.getKeyCode()).append(',');
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002588 sb.append(ev.getRepeatCount()).append(',');
2589 sb.append(ev.getMetaState()).append(',');
2590 sb.append(ev.getDeviceId()).append(',');
2591 sb.append(ev.getScanCode());
Romain Guy8506ab42009-06-11 17:35:47 -07002592 Log.d(TAG, sb.toString());
2593 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002594
2595 int enqueuePendingEvent(Object event, boolean sendDone) {
2596 int seq = mPendingEventSeq+1;
2597 if (seq < 0) seq = 0;
2598 mPendingEventSeq = seq;
2599 mPendingEvents.put(seq, event);
2600 return sendDone ? seq : -seq;
2601 }
2602
2603 Object retrievePendingEvent(int seq) {
2604 if (seq < 0) seq = -seq;
2605 Object event = mPendingEvents.get(seq);
2606 if (event != null) {
2607 mPendingEvents.remove(seq);
2608 }
2609 return event;
2610 }
Romain Guy8506ab42009-06-11 17:35:47 -07002611
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002612 private void deliverKeyEvent(KeyEvent event, boolean sendDone) {
Jeff Brown3915bb82010-11-05 15:02:16 -07002613 // If there is no view, then the event will not be handled.
2614 if (mView == null || !mAdded) {
2615 finishKeyEvent(event, sendDone, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002616 return;
2617 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002618
2619 if (LOCAL_LOGV) Log.v(TAG, "Dispatching key " + event + " to " + mView);
2620
2621 // Perform predispatching before the IME.
2622 if (mView.dispatchKeyEventPreIme(event)) {
2623 finishKeyEvent(event, sendDone, true);
2624 return;
2625 }
2626
2627 // Dispatch to the IME before propagating down the view hierarchy.
2628 // The IME will eventually call back into handleFinishedEvent.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002629 if (mLastWasImTarget) {
2630 InputMethodManager imm = InputMethodManager.peekInstance();
Jeff Brown3915bb82010-11-05 15:02:16 -07002631 if (imm != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002632 int seq = enqueuePendingEvent(event, sendDone);
2633 if (DEBUG_IMF) Log.v(TAG, "Sending key event to IME: seq="
2634 + seq + " event=" + event);
Jeff Brown3915bb82010-11-05 15:02:16 -07002635 imm.dispatchKeyEvent(mView.getContext(), seq, event, mInputMethodCallback);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002636 return;
2637 }
2638 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002639
2640 // Not dispatching to IME, continue with post IME actions.
2641 deliverKeyEventPostIme(event, sendDone);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002642 }
2643
Jeff Brown3915bb82010-11-05 15:02:16 -07002644 private void handleFinishedEvent(int seq, boolean handled) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002645 final KeyEvent event = (KeyEvent)retrievePendingEvent(seq);
2646 if (DEBUG_IMF) Log.v(TAG, "IME finished event: seq=" + seq
2647 + " handled=" + handled + " event=" + event);
2648 if (event != null) {
2649 final boolean sendDone = seq >= 0;
Jeff Brown3915bb82010-11-05 15:02:16 -07002650 if (handled) {
2651 finishKeyEvent(event, sendDone, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002652 } else {
Jeff Brown3915bb82010-11-05 15:02:16 -07002653 deliverKeyEventPostIme(event, sendDone);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002654 }
2655 }
2656 }
Romain Guy8506ab42009-06-11 17:35:47 -07002657
Jeff Brown3915bb82010-11-05 15:02:16 -07002658 private void deliverKeyEventPostIme(KeyEvent event, boolean sendDone) {
2659 // If the view went away, then the event will not be handled.
2660 if (mView == null || !mAdded) {
2661 finishKeyEvent(event, sendDone, false);
2662 return;
2663 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002664
Jeff Brown3915bb82010-11-05 15:02:16 -07002665 // If the key's purpose is to exit touch mode then we consume it and consider it handled.
2666 if (checkForLeavingTouchModeAndConsume(event)) {
2667 finishKeyEvent(event, sendDone, true);
2668 return;
2669 }
Romain Guy8506ab42009-06-11 17:35:47 -07002670
Jeff Brown3915bb82010-11-05 15:02:16 -07002671 if (Config.LOGV) {
2672 captureKeyLog("captureDispatchKeyEvent", event);
2673 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002674
Jeff Brown90655042010-12-02 13:50:46 -08002675 // Make sure the fallback event policy sees all keys that will be delivered to the
2676 // view hierarchy.
2677 mFallbackEventHandler.preDispatchKeyEvent(event);
2678
Jeff Brown3915bb82010-11-05 15:02:16 -07002679 // Deliver the key to the view hierarchy.
2680 if (mView.dispatchKeyEvent(event)) {
2681 finishKeyEvent(event, sendDone, true);
2682 return;
2683 }
Joe Onorato86f67862010-11-05 18:57:34 -07002684
Jeff Brownc1df9072010-12-21 16:38:50 -08002685 // If the Control modifier is held, try to interpret the key as a shortcut.
2686 if (event.getAction() == KeyEvent.ACTION_UP
2687 && event.isCtrlPressed()
2688 && !KeyEvent.isModifierKey(event.getKeyCode())) {
2689 if (mView.dispatchKeyShortcutEvent(event)) {
2690 finishKeyEvent(event, sendDone, true);
2691 return;
2692 }
2693 }
2694
Jeff Brown3915bb82010-11-05 15:02:16 -07002695 // Apply the fallback event policy.
2696 if (mFallbackEventHandler.dispatchKeyEvent(event)) {
2697 finishKeyEvent(event, sendDone, true);
2698 return;
2699 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002700
Jeff Brown3915bb82010-11-05 15:02:16 -07002701 // Handle automatic focus changes.
2702 if (event.getAction() == KeyEvent.ACTION_DOWN) {
2703 int direction = 0;
2704 switch (event.getKeyCode()) {
2705 case KeyEvent.KEYCODE_DPAD_LEFT:
Jeff Brown4e6319b2010-12-13 10:36:51 -08002706 if (event.hasNoModifiers()) {
2707 direction = View.FOCUS_LEFT;
2708 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002709 break;
2710 case KeyEvent.KEYCODE_DPAD_RIGHT:
Jeff Brown4e6319b2010-12-13 10:36:51 -08002711 if (event.hasNoModifiers()) {
2712 direction = View.FOCUS_RIGHT;
2713 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002714 break;
2715 case KeyEvent.KEYCODE_DPAD_UP:
Jeff Brown4e6319b2010-12-13 10:36:51 -08002716 if (event.hasNoModifiers()) {
2717 direction = View.FOCUS_UP;
2718 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002719 break;
2720 case KeyEvent.KEYCODE_DPAD_DOWN:
Jeff Brown4e6319b2010-12-13 10:36:51 -08002721 if (event.hasNoModifiers()) {
2722 direction = View.FOCUS_DOWN;
2723 }
2724 break;
2725 case KeyEvent.KEYCODE_TAB:
2726 if (event.hasNoModifiers()) {
2727 direction = View.FOCUS_FORWARD;
2728 } else if (event.hasModifiers(KeyEvent.META_SHIFT_ON)) {
2729 direction = View.FOCUS_BACKWARD;
2730 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002731 break;
2732 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002733
Jeff Brown3915bb82010-11-05 15:02:16 -07002734 if (direction != 0) {
2735 View focused = mView != null ? mView.findFocus() : null;
2736 if (focused != null) {
2737 View v = focused.focusSearch(direction);
2738 if (v != null && v != focused) {
2739 // do the math the get the interesting rect
2740 // of previous focused into the coord system of
2741 // newly focused view
2742 focused.getFocusedRect(mTempRect);
2743 if (mView instanceof ViewGroup) {
2744 ((ViewGroup) mView).offsetDescendantRectToMyCoords(
2745 focused, mTempRect);
2746 ((ViewGroup) mView).offsetRectIntoDescendantCoords(
2747 v, mTempRect);
2748 }
2749 if (v.requestFocus(direction, mTempRect)) {
2750 playSoundEffect(
2751 SoundEffectConstants.getContantForFocusDirection(direction));
2752 finishKeyEvent(event, sendDone, true);
2753 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002754 }
2755 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002756
2757 // Give the focused view a last chance to handle the dpad key.
2758 if (mView.dispatchUnhandledMove(focused, direction)) {
2759 finishKeyEvent(event, sendDone, true);
2760 return;
2761 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002762 }
2763 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002764 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002765
Jeff Brown3915bb82010-11-05 15:02:16 -07002766 // Key was unhandled.
2767 finishKeyEvent(event, sendDone, false);
2768 }
2769
2770 private void finishKeyEvent(KeyEvent event, boolean sendDone, boolean handled) {
2771 if (sendDone) {
2772 finishInputEvent(handled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002773 }
2774 }
2775
Christopher Tatea53146c2010-09-07 11:57:52 -07002776 /* drag/drop */
Christopher Tate407b4e92010-11-30 17:14:08 -08002777 void setLocalDragState(Object obj) {
2778 mLocalDragState = obj;
2779 }
2780
Christopher Tatea53146c2010-09-07 11:57:52 -07002781 private void handleDragEvent(DragEvent event) {
2782 // From the root, only drag start/end/location are dispatched. entered/exited
2783 // are determined and dispatched by the viewgroup hierarchy, who then report
2784 // that back here for ultimate reporting back to the framework.
2785 if (mView != null && mAdded) {
2786 final int what = event.mAction;
2787
2788 if (what == DragEvent.ACTION_DRAG_EXITED) {
2789 // A direct EXITED event means that the window manager knows we've just crossed
2790 // a window boundary, so the current drag target within this one must have
2791 // just been exited. Send it the usual notifications and then we're done
2792 // for now.
Chris Tate9d1ab882010-11-02 15:55:39 -07002793 mView.dispatchDragEvent(event);
Christopher Tatea53146c2010-09-07 11:57:52 -07002794 } else {
2795 // Cache the drag description when the operation starts, then fill it in
2796 // on subsequent calls as a convenience
2797 if (what == DragEvent.ACTION_DRAG_STARTED) {
Chris Tate9d1ab882010-11-02 15:55:39 -07002798 mCurrentDragView = null; // Start the current-recipient tracking
Christopher Tatea53146c2010-09-07 11:57:52 -07002799 mDragDescription = event.mClipDescription;
2800 } else {
2801 event.mClipDescription = mDragDescription;
2802 }
2803
2804 // For events with a [screen] location, translate into window coordinates
2805 if ((what == DragEvent.ACTION_DRAG_LOCATION) || (what == DragEvent.ACTION_DROP)) {
2806 mDragPoint.set(event.mX, event.mY);
2807 if (mTranslator != null) {
2808 mTranslator.translatePointInScreenToAppWindow(mDragPoint);
2809 }
2810
2811 if (mCurScrollY != 0) {
2812 mDragPoint.offset(0, mCurScrollY);
2813 }
2814
2815 event.mX = mDragPoint.x;
2816 event.mY = mDragPoint.y;
2817 }
2818
2819 // Remember who the current drag target is pre-dispatch
2820 final View prevDragView = mCurrentDragView;
2821
2822 // Now dispatch the drag/drop event
Chris Tated4533f12010-10-19 15:15:08 -07002823 boolean result = mView.dispatchDragEvent(event);
Christopher Tatea53146c2010-09-07 11:57:52 -07002824
2825 // If we changed apparent drag target, tell the OS about it
2826 if (prevDragView != mCurrentDragView) {
2827 try {
2828 if (prevDragView != null) {
2829 sWindowSession.dragRecipientExited(mWindow);
2830 }
2831 if (mCurrentDragView != null) {
2832 sWindowSession.dragRecipientEntered(mWindow);
2833 }
2834 } catch (RemoteException e) {
2835 Slog.e(TAG, "Unable to note drag target change");
2836 }
Christopher Tatea53146c2010-09-07 11:57:52 -07002837 }
Chris Tated4533f12010-10-19 15:15:08 -07002838
Christopher Tate407b4e92010-11-30 17:14:08 -08002839 // Report the drop result when we're done
Chris Tated4533f12010-10-19 15:15:08 -07002840 if (what == DragEvent.ACTION_DROP) {
Christopher Tate1fc014f2011-01-19 12:56:26 -08002841 mDragDescription = null;
Chris Tated4533f12010-10-19 15:15:08 -07002842 try {
2843 Log.i(TAG, "Reporting drop result: " + result);
2844 sWindowSession.reportDropResult(mWindow, result);
2845 } catch (RemoteException e) {
2846 Log.e(TAG, "Unable to report drop result");
2847 }
2848 }
Christopher Tate407b4e92010-11-30 17:14:08 -08002849
2850 // When the drag operation ends, release any local state object
2851 // that may have been in use
2852 if (what == DragEvent.ACTION_DRAG_ENDED) {
2853 setLocalDragState(null);
2854 }
Christopher Tatea53146c2010-09-07 11:57:52 -07002855 }
2856 }
2857 event.recycle();
2858 }
2859
Joe Onorato664644d2011-01-23 17:53:23 -08002860 public void handleDispatchSystemUiVisibilityChanged(int visibility) {
2861 if (mView == null) return;
Joe Onorato14782f72011-01-25 19:53:17 -08002862 if (mAttachInfo != null) {
2863 mAttachInfo.mSystemUiVisibility = visibility;
2864 }
Joe Onorato664644d2011-01-23 17:53:23 -08002865 mView.dispatchSystemUiVisibilityChanged(visibility);
2866 }
2867
Christopher Tate2c095f32010-10-04 14:13:40 -07002868 public void getLastTouchPoint(Point outLocation) {
2869 outLocation.x = (int) mLastTouchPoint.x;
2870 outLocation.y = (int) mLastTouchPoint.y;
2871 }
2872
Chris Tate9d1ab882010-11-02 15:55:39 -07002873 public void setDragFocus(View newDragTarget) {
Christopher Tatea53146c2010-09-07 11:57:52 -07002874 if (mCurrentDragView != newDragTarget) {
Chris Tate048691c2010-10-12 17:39:18 -07002875 mCurrentDragView = newDragTarget;
Christopher Tatea53146c2010-09-07 11:57:52 -07002876 }
Christopher Tatea53146c2010-09-07 11:57:52 -07002877 }
2878
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002879 private AudioManager getAudioManager() {
2880 if (mView == null) {
2881 throw new IllegalStateException("getAudioManager called when there is no mView");
2882 }
2883 if (mAudioManager == null) {
2884 mAudioManager = (AudioManager) mView.getContext().getSystemService(Context.AUDIO_SERVICE);
2885 }
2886 return mAudioManager;
2887 }
2888
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002889 private int relayoutWindow(WindowManager.LayoutParams params, int viewVisibility,
2890 boolean insetsPending) throws RemoteException {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002891
2892 float appScale = mAttachInfo.mApplicationScale;
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002893 boolean restore = false;
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002894 if (params != null && mTranslator != null) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07002895 restore = true;
2896 params.backup();
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002897 mTranslator.translateWindowLayout(params);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002898 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002899 if (params != null) {
2900 if (DBG) Log.d(TAG, "WindowLayout in layoutWindow:" + params);
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002901 }
Dianne Hackborn694f79b2010-03-17 19:44:59 -07002902 mPendingConfiguration.seq = 0;
Dianne Hackbornf123e492010-09-24 11:16:23 -07002903 //Log.d(TAG, ">>>>>> CALLING relayout");
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002904 int relayoutResult = sWindowSession.relayout(
2905 mWindow, params,
Dianne Hackborn189ee182010-12-02 21:48:53 -08002906 (int) (mView.getMeasuredWidth() * appScale + 0.5f),
2907 (int) (mView.getMeasuredHeight() * appScale + 0.5f),
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002908 viewVisibility, insetsPending, mWinFrame,
Dianne Hackborn694f79b2010-03-17 19:44:59 -07002909 mPendingContentInsets, mPendingVisibleInsets,
2910 mPendingConfiguration, mSurface);
Dianne Hackbornf123e492010-09-24 11:16:23 -07002911 //Log.d(TAG, "<<<<<< BACK FROM relayout");
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002912 if (restore) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07002913 params.restore();
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002914 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002915
2916 if (mTranslator != null) {
2917 mTranslator.translateRectInScreenToAppWinFrame(mWinFrame);
2918 mTranslator.translateRectInScreenToAppWindow(mPendingContentInsets);
2919 mTranslator.translateRectInScreenToAppWindow(mPendingVisibleInsets);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002920 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002921 return relayoutResult;
2922 }
Romain Guy8506ab42009-06-11 17:35:47 -07002923
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002924 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002925 * {@inheritDoc}
2926 */
2927 public void playSoundEffect(int effectId) {
2928 checkThread();
2929
Jean-Michel Trivi13b18fd2010-05-05 09:18:15 -07002930 try {
2931 final AudioManager audioManager = getAudioManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002932
Jean-Michel Trivi13b18fd2010-05-05 09:18:15 -07002933 switch (effectId) {
2934 case SoundEffectConstants.CLICK:
2935 audioManager.playSoundEffect(AudioManager.FX_KEY_CLICK);
2936 return;
2937 case SoundEffectConstants.NAVIGATION_DOWN:
2938 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_DOWN);
2939 return;
2940 case SoundEffectConstants.NAVIGATION_LEFT:
2941 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_LEFT);
2942 return;
2943 case SoundEffectConstants.NAVIGATION_RIGHT:
2944 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_RIGHT);
2945 return;
2946 case SoundEffectConstants.NAVIGATION_UP:
2947 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_UP);
2948 return;
2949 default:
2950 throw new IllegalArgumentException("unknown effect id " + effectId +
2951 " not defined in " + SoundEffectConstants.class.getCanonicalName());
2952 }
2953 } catch (IllegalStateException e) {
2954 // Exception thrown by getAudioManager() when mView is null
2955 Log.e(TAG, "FATAL EXCEPTION when attempting to play sound effect: " + e);
2956 e.printStackTrace();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002957 }
2958 }
2959
2960 /**
2961 * {@inheritDoc}
2962 */
2963 public boolean performHapticFeedback(int effectId, boolean always) {
2964 try {
2965 return sWindowSession.performHapticFeedback(mWindow, effectId, always);
2966 } catch (RemoteException e) {
2967 return false;
2968 }
2969 }
2970
2971 /**
2972 * {@inheritDoc}
2973 */
2974 public View focusSearch(View focused, int direction) {
2975 checkThread();
2976 if (!(mView instanceof ViewGroup)) {
2977 return null;
2978 }
2979 return FocusFinder.getInstance().findNextFocus((ViewGroup) mView, focused, direction);
2980 }
2981
2982 public void debug() {
2983 mView.debug();
2984 }
2985
2986 public void die(boolean immediate) {
Dianne Hackborn94d69142009-09-28 22:14:42 -07002987 if (immediate) {
2988 doDie();
2989 } else {
2990 sendEmptyMessage(DIE);
2991 }
2992 }
2993
2994 void doDie() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002995 checkThread();
Jeff Brownb75fa302010-07-15 23:47:29 -07002996 if (LOCAL_LOGV) Log.v(TAG, "DIE in " + this + " of " + mSurface);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002997 synchronized (this) {
2998 if (mAdded && !mFirst) {
Romain Guy29d89972010-09-22 16:10:57 -07002999 destroyHardwareRenderer();
3000
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003001 int viewVisibility = mView.getVisibility();
3002 boolean viewVisibilityChanged = mViewVisibility != viewVisibility;
3003 if (mWindowAttributesChanged || viewVisibilityChanged) {
3004 // If layout params have been changed, first give them
3005 // to the window manager to make sure it has the correct
3006 // animation info.
3007 try {
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07003008 if ((relayoutWindow(mWindowAttributes, viewVisibility, false)
3009 & WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003010 sWindowSession.finishDrawing(mWindow);
3011 }
3012 } catch (RemoteException e) {
3013 }
3014 }
3015
Dianne Hackborn0586a1b2009-09-06 21:08:27 -07003016 mSurface.release();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003017 }
3018 if (mAdded) {
3019 mAdded = false;
Dianne Hackborn94d69142009-09-28 22:14:42 -07003020 dispatchDetachedFromWindow();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003021 }
3022 }
3023 }
3024
Romain Guy29d89972010-09-22 16:10:57 -07003025 private void destroyHardwareRenderer() {
Romain Guyb051e892010-09-28 19:09:36 -07003026 if (mAttachInfo.mHardwareRenderer != null) {
3027 mAttachInfo.mHardwareRenderer.destroy(true);
3028 mAttachInfo.mHardwareRenderer = null;
Romain Guy29d89972010-09-22 16:10:57 -07003029 mAttachInfo.mHardwareAccelerated = false;
3030 }
3031 }
3032
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003033 public void dispatchFinishedEvent(int seq, boolean handled) {
3034 Message msg = obtainMessage(FINISHED_EVENT);
3035 msg.arg1 = seq;
3036 msg.arg2 = handled ? 1 : 0;
3037 sendMessage(msg);
3038 }
Mitsuru Oshima3d914922009-05-13 22:29:15 -07003039
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003040 public void dispatchResized(int w, int h, Rect coveredInsets,
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003041 Rect visibleInsets, boolean reportDraw, Configuration newConfig) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003042 if (DEBUG_LAYOUT) Log.v(TAG, "Resizing " + this + ": w=" + w
3043 + " h=" + h + " coveredInsets=" + coveredInsets.toShortString()
3044 + " visibleInsets=" + visibleInsets.toShortString()
3045 + " reportDraw=" + reportDraw);
3046 Message msg = obtainMessage(reportDraw ? RESIZED_REPORT :RESIZED);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07003047 if (mTranslator != null) {
3048 mTranslator.translateRectInScreenToAppWindow(coveredInsets);
3049 mTranslator.translateRectInScreenToAppWindow(visibleInsets);
3050 w *= mTranslator.applicationInvertedScale;
3051 h *= mTranslator.applicationInvertedScale;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07003052 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07003053 msg.arg1 = w;
3054 msg.arg2 = h;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003055 ResizedInfo ri = new ResizedInfo();
3056 ri.coveredInsets = new Rect(coveredInsets);
3057 ri.visibleInsets = new Rect(visibleInsets);
3058 ri.newConfig = newConfig;
3059 msg.obj = ri;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003060 sendMessage(msg);
3061 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07003062
Jeff Brown3915bb82010-11-05 15:02:16 -07003063 private InputQueue.FinishedCallback mFinishedCallback;
Jeff Brown46b9ac02010-04-22 18:58:52 -07003064
3065 private final InputHandler mInputHandler = new InputHandler() {
Jeff Brown3915bb82010-11-05 15:02:16 -07003066 public void handleKey(KeyEvent event, InputQueue.FinishedCallback finishedCallback) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07003067 startInputEvent(finishedCallback);
Jeff Brown92ff1dd2010-08-11 16:16:06 -07003068 dispatchKey(event, true);
Jeff Brown46b9ac02010-04-22 18:58:52 -07003069 }
3070
Jeff Brown3915bb82010-11-05 15:02:16 -07003071 public void handleMotion(MotionEvent event, InputQueue.FinishedCallback finishedCallback) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07003072 startInputEvent(finishedCallback);
3073 dispatchMotion(event, true);
Jeff Brown46b9ac02010-04-22 18:58:52 -07003074 }
3075 };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003076
3077 public void dispatchKey(KeyEvent event) {
Jeff Brown92ff1dd2010-08-11 16:16:06 -07003078 dispatchKey(event, false);
3079 }
3080
3081 private void dispatchKey(KeyEvent event, boolean sendDone) {
3082 //noinspection ConstantConditions
3083 if (false && event.getAction() == KeyEvent.ACTION_DOWN) {
3084 if (event.getKeyCode() == KeyEvent.KEYCODE_CAMERA) {
Romain Guy812ccbe2010-06-01 14:07:24 -07003085 if (DBG) Log.d("keydisp", "===================================================");
3086 if (DBG) Log.d("keydisp", "Focused view Hierarchy is:");
3087
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003088 debug();
3089
Romain Guy812ccbe2010-06-01 14:07:24 -07003090 if (DBG) Log.d("keydisp", "===================================================");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003091 }
3092 }
3093
3094 Message msg = obtainMessage(DISPATCH_KEY);
3095 msg.obj = event;
Jeff Brown92ff1dd2010-08-11 16:16:06 -07003096 msg.arg1 = sendDone ? 1 : 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003097
3098 if (LOCAL_LOGV) Log.v(
Jeff Brownc5ed5912010-07-14 18:48:53 -07003099 TAG, "sending key " + event + " to " + mView);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003100
3101 sendMessageAtTime(msg, event.getEventTime());
3102 }
Jeff Brownc5ed5912010-07-14 18:48:53 -07003103
3104 public void dispatchMotion(MotionEvent event) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07003105 dispatchMotion(event, false);
3106 }
3107
3108 private void dispatchMotion(MotionEvent event, boolean sendDone) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07003109 int source = event.getSource();
3110 if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07003111 dispatchPointer(event, sendDone);
Jeff Brownc5ed5912010-07-14 18:48:53 -07003112 } else if ((source & InputDevice.SOURCE_CLASS_TRACKBALL) != 0) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07003113 dispatchTrackball(event, sendDone);
Jeff Brownc5ed5912010-07-14 18:48:53 -07003114 } else {
3115 // TODO
3116 Log.v(TAG, "Dropping unsupported motion event (unimplemented): " + event);
Jeff Brown93ed4e32010-09-23 13:51:48 -07003117 if (sendDone) {
Jeff Brown3915bb82010-11-05 15:02:16 -07003118 finishInputEvent(false);
Jeff Brown93ed4e32010-09-23 13:51:48 -07003119 }
Jeff Brownc5ed5912010-07-14 18:48:53 -07003120 }
3121 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003122
Jeff Brown00fa7bd2010-07-02 15:37:36 -07003123 public void dispatchPointer(MotionEvent event) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07003124 dispatchPointer(event, false);
3125 }
3126
3127 private void dispatchPointer(MotionEvent event, boolean sendDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003128 Message msg = obtainMessage(DISPATCH_POINTER);
3129 msg.obj = event;
Jeff Brown93ed4e32010-09-23 13:51:48 -07003130 msg.arg1 = sendDone ? 1 : 0;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07003131 sendMessageAtTime(msg, event.getEventTime());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003132 }
3133
Jeff Brown00fa7bd2010-07-02 15:37:36 -07003134 public void dispatchTrackball(MotionEvent event) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07003135 dispatchTrackball(event, false);
3136 }
3137
3138 private void dispatchTrackball(MotionEvent event, boolean sendDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003139 Message msg = obtainMessage(DISPATCH_TRACKBALL);
3140 msg.obj = event;
Jeff Brown93ed4e32010-09-23 13:51:48 -07003141 msg.arg1 = sendDone ? 1 : 0;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07003142 sendMessageAtTime(msg, event.getEventTime());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003143 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07003144
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003145 public void dispatchAppVisibility(boolean visible) {
3146 Message msg = obtainMessage(DISPATCH_APP_VISIBILITY);
3147 msg.arg1 = visible ? 1 : 0;
3148 sendMessage(msg);
3149 }
3150
3151 public void dispatchGetNewSurface() {
3152 Message msg = obtainMessage(DISPATCH_GET_NEW_SURFACE);
3153 sendMessage(msg);
3154 }
3155
3156 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
3157 Message msg = Message.obtain();
3158 msg.what = WINDOW_FOCUS_CHANGED;
3159 msg.arg1 = hasFocus ? 1 : 0;
3160 msg.arg2 = inTouchMode ? 1 : 0;
3161 sendMessage(msg);
3162 }
3163
Dianne Hackbornffa42482009-09-23 22:20:11 -07003164 public void dispatchCloseSystemDialogs(String reason) {
3165 Message msg = Message.obtain();
3166 msg.what = CLOSE_SYSTEM_DIALOGS;
3167 msg.obj = reason;
3168 sendMessage(msg);
3169 }
Christopher Tatea53146c2010-09-07 11:57:52 -07003170
3171 public void dispatchDragEvent(DragEvent event) {
Chris Tate91e9bb32010-10-12 12:58:43 -07003172 final int what;
3173 if (event.getAction() == DragEvent.ACTION_DRAG_LOCATION) {
3174 what = DISPATCH_DRAG_LOCATION_EVENT;
3175 removeMessages(what);
3176 } else {
3177 what = DISPATCH_DRAG_EVENT;
3178 }
3179 Message msg = obtainMessage(what, event);
Christopher Tatea53146c2010-09-07 11:57:52 -07003180 sendMessage(msg);
3181 }
3182
Joe Onorato664644d2011-01-23 17:53:23 -08003183 public void dispatchSystemUiVisibilityChanged(int visibility) {
3184 sendMessage(obtainMessage(DISPATCH_SYSTEM_UI_VISIBILITY, visibility, 0));
3185 }
3186
svetoslavganov75986cf2009-05-14 22:28:01 -07003187 /**
3188 * The window is getting focus so if there is anything focused/selected
3189 * send an {@link AccessibilityEvent} to announce that.
3190 */
3191 private void sendAccessibilityEvents() {
3192 if (!AccessibilityManager.getInstance(mView.getContext()).isEnabled()) {
3193 return;
3194 }
3195 mView.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
3196 View focusedView = mView.findFocus();
3197 if (focusedView != null && focusedView != mView) {
3198 focusedView.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
3199 }
3200 }
3201
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003202 public boolean showContextMenuForChild(View originalView) {
3203 return false;
3204 }
3205
Adam Powell6e346362010-07-23 10:18:23 -07003206 public ActionMode startActionModeForChild(View originalView, ActionMode.Callback callback) {
3207 return null;
3208 }
3209
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003210 public void createContextMenu(ContextMenu menu) {
3211 }
3212
3213 public void childDrawableStateChanged(View child) {
3214 }
3215
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003216 void checkThread() {
3217 if (mThread != Thread.currentThread()) {
3218 throw new CalledFromWrongThreadException(
3219 "Only the original thread that created a view hierarchy can touch its views.");
3220 }
3221 }
3222
3223 public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
3224 // ViewRoot never intercepts touch event, so this can be a no-op
3225 }
3226
3227 public boolean requestChildRectangleOnScreen(View child, Rect rectangle,
3228 boolean immediate) {
3229 return scrollToRectOrFocus(rectangle, immediate);
3230 }
Romain Guy8506ab42009-06-11 17:35:47 -07003231
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07003232 class TakenSurfaceHolder extends BaseSurfaceHolder {
3233 @Override
3234 public boolean onAllowLockCanvas() {
3235 return mDrawingAllowed;
3236 }
3237
3238 @Override
3239 public void onRelayoutContainer() {
3240 // Not currently interesting -- from changing between fixed and layout size.
3241 }
3242
3243 public void setFormat(int format) {
3244 ((RootViewSurfaceTaker)mView).setSurfaceFormat(format);
3245 }
3246
3247 public void setType(int type) {
3248 ((RootViewSurfaceTaker)mView).setSurfaceType(type);
3249 }
3250
3251 @Override
3252 public void onUpdateSurface() {
3253 // We take care of format and type changes on our own.
3254 throw new IllegalStateException("Shouldn't be here");
3255 }
3256
3257 public boolean isCreating() {
3258 return mIsCreating;
3259 }
3260
3261 @Override
3262 public void setFixedSize(int width, int height) {
3263 throw new UnsupportedOperationException(
3264 "Currently only support sizing from layout");
3265 }
3266
3267 public void setKeepScreenOn(boolean screenOn) {
3268 ((RootViewSurfaceTaker)mView).setSurfaceKeepScreenOn(screenOn);
3269 }
3270 }
3271
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003272 static class InputMethodCallback extends IInputMethodCallback.Stub {
3273 private WeakReference<ViewRoot> mViewRoot;
3274
3275 public InputMethodCallback(ViewRoot viewRoot) {
3276 mViewRoot = new WeakReference<ViewRoot>(viewRoot);
3277 }
Romain Guy8506ab42009-06-11 17:35:47 -07003278
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003279 public void finishedEvent(int seq, boolean handled) {
3280 final ViewRoot viewRoot = mViewRoot.get();
3281 if (viewRoot != null) {
3282 viewRoot.dispatchFinishedEvent(seq, handled);
3283 }
3284 }
3285
3286 public void sessionCreated(IInputMethodSession session) throws RemoteException {
3287 // Stub -- not for use in the client.
3288 }
3289 }
Romain Guy8506ab42009-06-11 17:35:47 -07003290
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003291 static class W extends IWindow.Stub {
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07003292 private final WeakReference<ViewRoot> mViewRoot;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003293
Romain Guyfb8b7632010-08-23 21:05:08 -07003294 W(ViewRoot viewRoot) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003295 mViewRoot = new WeakReference<ViewRoot>(viewRoot);
3296 }
3297
Romain Guyfb8b7632010-08-23 21:05:08 -07003298 public void resized(int w, int h, Rect coveredInsets, Rect visibleInsets,
3299 boolean reportDraw, Configuration newConfig) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003300 final ViewRoot viewRoot = mViewRoot.get();
3301 if (viewRoot != null) {
Romain Guyfb8b7632010-08-23 21:05:08 -07003302 viewRoot.dispatchResized(w, h, coveredInsets, visibleInsets, reportDraw, newConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003303 }
3304 }
3305
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003306 public void dispatchAppVisibility(boolean visible) {
3307 final ViewRoot viewRoot = mViewRoot.get();
3308 if (viewRoot != null) {
3309 viewRoot.dispatchAppVisibility(visible);
3310 }
3311 }
3312
3313 public void dispatchGetNewSurface() {
3314 final ViewRoot viewRoot = mViewRoot.get();
3315 if (viewRoot != null) {
3316 viewRoot.dispatchGetNewSurface();
3317 }
3318 }
3319
3320 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
3321 final ViewRoot viewRoot = mViewRoot.get();
3322 if (viewRoot != null) {
3323 viewRoot.windowFocusChanged(hasFocus, inTouchMode);
3324 }
3325 }
3326
3327 private static int checkCallingPermission(String permission) {
3328 if (!Process.supportsProcesses()) {
3329 return PackageManager.PERMISSION_GRANTED;
3330 }
3331
3332 try {
3333 return ActivityManagerNative.getDefault().checkPermission(
3334 permission, Binder.getCallingPid(), Binder.getCallingUid());
3335 } catch (RemoteException e) {
3336 return PackageManager.PERMISSION_DENIED;
3337 }
3338 }
3339
3340 public void executeCommand(String command, String parameters, ParcelFileDescriptor out) {
3341 final ViewRoot viewRoot = mViewRoot.get();
3342 if (viewRoot != null) {
3343 final View view = viewRoot.mView;
3344 if (view != null) {
3345 if (checkCallingPermission(Manifest.permission.DUMP) !=
3346 PackageManager.PERMISSION_GRANTED) {
3347 throw new SecurityException("Insufficient permissions to invoke"
3348 + " executeCommand() from pid=" + Binder.getCallingPid()
3349 + ", uid=" + Binder.getCallingUid());
3350 }
3351
3352 OutputStream clientStream = null;
3353 try {
3354 clientStream = new ParcelFileDescriptor.AutoCloseOutputStream(out);
3355 ViewDebug.dispatchCommand(view, command, parameters, clientStream);
3356 } catch (IOException e) {
3357 e.printStackTrace();
3358 } finally {
3359 if (clientStream != null) {
3360 try {
3361 clientStream.close();
3362 } catch (IOException e) {
3363 e.printStackTrace();
3364 }
3365 }
3366 }
3367 }
3368 }
3369 }
Dianne Hackborn72c82ab2009-08-11 21:13:54 -07003370
Dianne Hackbornffa42482009-09-23 22:20:11 -07003371 public void closeSystemDialogs(String reason) {
3372 final ViewRoot viewRoot = mViewRoot.get();
3373 if (viewRoot != null) {
3374 viewRoot.dispatchCloseSystemDialogs(reason);
3375 }
3376 }
3377
Marco Nelissenbf6956b2009-11-09 15:21:13 -08003378 public void dispatchWallpaperOffsets(float x, float y, float xStep, float yStep,
3379 boolean sync) {
Dianne Hackborn19382ac2009-09-11 21:13:37 -07003380 if (sync) {
3381 try {
3382 sWindowSession.wallpaperOffsetsComplete(asBinder());
3383 } catch (RemoteException e) {
3384 }
3385 }
Dianne Hackborn72c82ab2009-08-11 21:13:54 -07003386 }
Dianne Hackborn75804932009-10-20 20:15:20 -07003387
3388 public void dispatchWallpaperCommand(String action, int x, int y,
3389 int z, Bundle extras, boolean sync) {
3390 if (sync) {
3391 try {
3392 sWindowSession.wallpaperCommandComplete(asBinder(), null);
3393 } catch (RemoteException e) {
3394 }
3395 }
3396 }
Christopher Tatea53146c2010-09-07 11:57:52 -07003397
3398 /* Drag/drop */
3399 public void dispatchDragEvent(DragEvent event) {
3400 final ViewRoot viewRoot = mViewRoot.get();
3401 if (viewRoot != null) {
3402 viewRoot.dispatchDragEvent(event);
3403 }
3404 }
Joe Onorato664644d2011-01-23 17:53:23 -08003405
3406 @Override
3407 public void dispatchSystemUiVisibilityChanged(int visibility) {
3408 final ViewRoot viewRoot = mViewRoot.get();
3409 if (viewRoot != null) {
3410 viewRoot.dispatchSystemUiVisibilityChanged(visibility);
3411 }
3412 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003413 }
3414
3415 /**
3416 * Maintains state information for a single trackball axis, generating
3417 * discrete (DPAD) movements based on raw trackball motion.
3418 */
3419 static final class TrackballAxis {
3420 /**
3421 * The maximum amount of acceleration we will apply.
3422 */
3423 static final float MAX_ACCELERATION = 20;
Romain Guy8506ab42009-06-11 17:35:47 -07003424
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003425 /**
3426 * The maximum amount of time (in milliseconds) between events in order
3427 * for us to consider the user to be doing fast trackball movements,
3428 * and thus apply an acceleration.
3429 */
3430 static final long FAST_MOVE_TIME = 150;
Romain Guy8506ab42009-06-11 17:35:47 -07003431
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003432 /**
3433 * Scaling factor to the time (in milliseconds) between events to how
3434 * much to multiple/divide the current acceleration. When movement
3435 * is < FAST_MOVE_TIME this multiplies the acceleration; when >
3436 * FAST_MOVE_TIME it divides it.
3437 */
3438 static final float ACCEL_MOVE_SCALING_FACTOR = (1.0f/40);
Romain Guy8506ab42009-06-11 17:35:47 -07003439
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003440 float position;
3441 float absPosition;
3442 float acceleration = 1;
3443 long lastMoveTime = 0;
3444 int step;
3445 int dir;
3446 int nonAccelMovement;
3447
3448 void reset(int _step) {
3449 position = 0;
3450 acceleration = 1;
3451 lastMoveTime = 0;
3452 step = _step;
3453 dir = 0;
3454 }
3455
3456 /**
3457 * Add trackball movement into the state. If the direction of movement
3458 * has been reversed, the state is reset before adding the
3459 * movement (so that you don't have to compensate for any previously
3460 * collected movement before see the result of the movement in the
3461 * new direction).
3462 *
3463 * @return Returns the absolute value of the amount of movement
3464 * collected so far.
3465 */
3466 float collect(float off, long time, String axis) {
3467 long normTime;
3468 if (off > 0) {
3469 normTime = (long)(off * FAST_MOVE_TIME);
3470 if (dir < 0) {
3471 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to positive!");
3472 position = 0;
3473 step = 0;
3474 acceleration = 1;
3475 lastMoveTime = 0;
3476 }
3477 dir = 1;
3478 } else if (off < 0) {
3479 normTime = (long)((-off) * FAST_MOVE_TIME);
3480 if (dir > 0) {
3481 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to negative!");
3482 position = 0;
3483 step = 0;
3484 acceleration = 1;
3485 lastMoveTime = 0;
3486 }
3487 dir = -1;
3488 } else {
3489 normTime = 0;
3490 }
Romain Guy8506ab42009-06-11 17:35:47 -07003491
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003492 // The number of milliseconds between each movement that is
3493 // considered "normal" and will not result in any acceleration
3494 // or deceleration, scaled by the offset we have here.
3495 if (normTime > 0) {
3496 long delta = time - lastMoveTime;
3497 lastMoveTime = time;
3498 float acc = acceleration;
3499 if (delta < normTime) {
3500 // The user is scrolling rapidly, so increase acceleration.
3501 float scale = (normTime-delta) * ACCEL_MOVE_SCALING_FACTOR;
3502 if (scale > 1) acc *= scale;
3503 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " accelerate: off="
3504 + off + " normTime=" + normTime + " delta=" + delta
3505 + " scale=" + scale + " acc=" + acc);
3506 acceleration = acc < MAX_ACCELERATION ? acc : MAX_ACCELERATION;
3507 } else {
3508 // The user is scrolling slowly, so decrease acceleration.
3509 float scale = (delta-normTime) * ACCEL_MOVE_SCALING_FACTOR;
3510 if (scale > 1) acc /= scale;
3511 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " deccelerate: off="
3512 + off + " normTime=" + normTime + " delta=" + delta
3513 + " scale=" + scale + " acc=" + acc);
3514 acceleration = acc > 1 ? acc : 1;
3515 }
3516 }
3517 position += off;
3518 return (absPosition = Math.abs(position));
3519 }
3520
3521 /**
3522 * Generate the number of discrete movement events appropriate for
3523 * the currently collected trackball movement.
3524 *
3525 * @param precision The minimum movement required to generate the
3526 * first discrete movement.
3527 *
3528 * @return Returns the number of discrete movements, either positive
3529 * or negative, or 0 if there is not enough trackball movement yet
3530 * for a discrete movement.
3531 */
3532 int generate(float precision) {
3533 int movement = 0;
3534 nonAccelMovement = 0;
3535 do {
3536 final int dir = position >= 0 ? 1 : -1;
3537 switch (step) {
3538 // If we are going to execute the first step, then we want
3539 // to do this as soon as possible instead of waiting for
3540 // a full movement, in order to make things look responsive.
3541 case 0:
3542 if (absPosition < precision) {
3543 return movement;
3544 }
3545 movement += dir;
3546 nonAccelMovement += dir;
3547 step = 1;
3548 break;
3549 // If we have generated the first movement, then we need
3550 // to wait for the second complete trackball motion before
3551 // generating the second discrete movement.
3552 case 1:
3553 if (absPosition < 2) {
3554 return movement;
3555 }
3556 movement += dir;
3557 nonAccelMovement += dir;
3558 position += dir > 0 ? -2 : 2;
3559 absPosition = Math.abs(position);
3560 step = 2;
3561 break;
3562 // After the first two, we generate discrete movements
3563 // consistently with the trackball, applying an acceleration
3564 // if the trackball is moving quickly. This is a simple
3565 // acceleration on top of what we already compute based
3566 // on how quickly the wheel is being turned, to apply
3567 // a longer increasing acceleration to continuous movement
3568 // in one direction.
3569 default:
3570 if (absPosition < 1) {
3571 return movement;
3572 }
3573 movement += dir;
3574 position += dir >= 0 ? -1 : 1;
3575 absPosition = Math.abs(position);
3576 float acc = acceleration;
3577 acc *= 1.1f;
3578 acceleration = acc < MAX_ACCELERATION ? acc : acceleration;
3579 break;
3580 }
3581 } while (true);
3582 }
3583 }
3584
3585 public static final class CalledFromWrongThreadException extends AndroidRuntimeException {
3586 public CalledFromWrongThreadException(String msg) {
3587 super(msg);
3588 }
3589 }
3590
3591 private SurfaceHolder mHolder = new SurfaceHolder() {
3592 // we only need a SurfaceHolder for opengl. it would be nice
3593 // to implement everything else though, especially the callback
3594 // support (opengl doesn't make use of it right now, but eventually
3595 // will).
3596 public Surface getSurface() {
3597 return mSurface;
3598 }
3599
3600 public boolean isCreating() {
3601 return false;
3602 }
3603
3604 public void addCallback(Callback callback) {
3605 }
3606
3607 public void removeCallback(Callback callback) {
3608 }
3609
3610 public void setFixedSize(int width, int height) {
3611 }
3612
3613 public void setSizeFromLayout() {
3614 }
3615
3616 public void setFormat(int format) {
3617 }
3618
3619 public void setType(int type) {
3620 }
3621
3622 public void setKeepScreenOn(boolean screenOn) {
3623 }
3624
3625 public Canvas lockCanvas() {
3626 return null;
3627 }
3628
3629 public Canvas lockCanvas(Rect dirty) {
3630 return null;
3631 }
3632
3633 public void unlockCanvasAndPost(Canvas canvas) {
3634 }
3635 public Rect getSurfaceFrame() {
3636 return null;
3637 }
3638 };
3639
3640 static RunQueue getRunQueue() {
3641 RunQueue rq = sRunQueues.get();
3642 if (rq != null) {
3643 return rq;
3644 }
3645 rq = new RunQueue();
3646 sRunQueues.set(rq);
3647 return rq;
3648 }
Romain Guy8506ab42009-06-11 17:35:47 -07003649
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003650 /**
3651 * @hide
3652 */
3653 static final class RunQueue {
3654 private final ArrayList<HandlerAction> mActions = new ArrayList<HandlerAction>();
3655
3656 void post(Runnable action) {
3657 postDelayed(action, 0);
3658 }
3659
3660 void postDelayed(Runnable action, long delayMillis) {
3661 HandlerAction handlerAction = new HandlerAction();
3662 handlerAction.action = action;
3663 handlerAction.delay = delayMillis;
3664
3665 synchronized (mActions) {
3666 mActions.add(handlerAction);
3667 }
3668 }
3669
3670 void removeCallbacks(Runnable action) {
3671 final HandlerAction handlerAction = new HandlerAction();
3672 handlerAction.action = action;
3673
3674 synchronized (mActions) {
3675 final ArrayList<HandlerAction> actions = mActions;
3676
3677 while (actions.remove(handlerAction)) {
3678 // Keep going
3679 }
3680 }
3681 }
3682
3683 void executeActions(Handler handler) {
3684 synchronized (mActions) {
3685 final ArrayList<HandlerAction> actions = mActions;
3686 final int count = actions.size();
3687
3688 for (int i = 0; i < count; i++) {
3689 final HandlerAction handlerAction = actions.get(i);
3690 handler.postDelayed(handlerAction.action, handlerAction.delay);
3691 }
3692
Romain Guy15df6702009-08-17 20:17:30 -07003693 actions.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003694 }
3695 }
3696
3697 private static class HandlerAction {
3698 Runnable action;
3699 long delay;
3700
3701 @Override
3702 public boolean equals(Object o) {
3703 if (this == o) return true;
3704 if (o == null || getClass() != o.getClass()) return false;
3705
3706 HandlerAction that = (HandlerAction) o;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003707 return !(action != null ? !action.equals(that.action) : that.action != null);
3708
3709 }
3710
3711 @Override
3712 public int hashCode() {
3713 int result = action != null ? action.hashCode() : 0;
3714 result = 31 * result + (int) (delay ^ (delay >>> 32));
3715 return result;
3716 }
3717 }
3718 }
3719
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003720 private static native void nativeShowFPS(Canvas canvas, int durationMillis);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003721}