blob: 26600929103eff575d32fae62e2810a2655e1b39 [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 Onorato664644d2011-01-23 17:53:23 -0800907 if (attachInfo.mKeepScreenOn != oldScreenOn ||
908 attachInfo.mSystemUiVisibility != oldVis) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800909 params = lp;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800910 }
911 }
912
913 if (mFirst || attachInfo.mViewVisibilityChanged) {
914 attachInfo.mViewVisibilityChanged = false;
915 int resizeMode = mSoftInputMode &
916 WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST;
917 // If we are in auto resize mode, then we need to determine
918 // what mode to use now.
919 if (resizeMode == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED) {
920 final int N = attachInfo.mScrollContainers.size();
921 for (int i=0; i<N; i++) {
922 if (attachInfo.mScrollContainers.get(i).isShown()) {
923 resizeMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE;
924 }
925 }
926 if (resizeMode == 0) {
927 resizeMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN;
928 }
929 if ((lp.softInputMode &
930 WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) != resizeMode) {
931 lp.softInputMode = (lp.softInputMode &
932 ~WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) |
933 resizeMode;
934 params = lp;
935 }
936 }
937 }
Romain Guy8506ab42009-06-11 17:35:47 -0700938
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800939 if (params != null && (host.mPrivateFlags & View.REQUEST_TRANSPARENT_REGIONS) != 0) {
940 if (!PixelFormat.formatHasAlpha(params.format)) {
941 params.format = PixelFormat.TRANSLUCENT;
942 }
943 }
944
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800945 boolean windowShouldResize = mLayoutRequested && windowSizeMayChange
Dianne Hackborn189ee182010-12-02 21:48:53 -0800946 && ((mWidth != host.getMeasuredWidth() || mHeight != host.getMeasuredHeight())
Romain Guy2e4f4262010-04-06 11:07:52 -0700947 || (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT &&
948 frame.width() < desiredWindowWidth && frame.width() != mWidth)
949 || (lp.height == ViewGroup.LayoutParams.WRAP_CONTENT &&
950 frame.height() < desiredWindowHeight && frame.height() != mHeight));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800951
952 final boolean computesInternalInsets =
953 attachInfo.mTreeObserver.hasComputeInternalInsetsListeners();
Romain Guy812ccbe2010-06-01 14:07:24 -0700954
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800955 boolean insetsPending = false;
956 int relayoutResult = 0;
Romain Guy812ccbe2010-06-01 14:07:24 -0700957
958 if (mFirst || windowShouldResize || insetsChanged ||
959 viewVisibilityChanged || params != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800960
961 if (viewVisibility == View.VISIBLE) {
962 // If this window is giving internal insets to the window
963 // manager, and it is being added or changing its visibility,
964 // then we want to first give the window manager "fake"
965 // insets to cause it to effectively ignore the content of
966 // the window during layout. This avoids it briefly causing
967 // other windows to resize/move based on the raw frame of the
968 // window, waiting until we can finish laying out this window
969 // and get back to the window manager with the ultimately
970 // computed insets.
Romain Guy812ccbe2010-06-01 14:07:24 -0700971 insetsPending = computesInternalInsets && (mFirst || viewVisibilityChanged);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800972 }
973
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700974 if (mSurfaceHolder != null) {
975 mSurfaceHolder.mSurfaceLock.lock();
976 mDrawingAllowed = true;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700977 }
Romain Guy812ccbe2010-06-01 14:07:24 -0700978
Romain Guyc361da82010-10-25 15:29:10 -0700979 boolean hwInitialized = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800980 boolean contentInsetsChanged = false;
Romain Guy13922e02009-05-12 17:56:14 -0700981 boolean visibleInsetsChanged;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700982 boolean hadSurface = mSurface.isValid();
Romain Guy812ccbe2010-06-01 14:07:24 -0700983
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800984 try {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800985 int fl = 0;
986 if (params != null) {
987 fl = params.flags;
988 if (attachInfo.mKeepScreenOn) {
989 params.flags |= WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
990 }
Joe Onorato664644d2011-01-23 17:53:23 -0800991 params.systemUiVisibility = attachInfo.mSystemUiVisibility;
992 params.hasSystemUiListeners = attachInfo.mHasSystemUiListeners;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800993 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700994 if (DEBUG_LAYOUT) {
Dianne Hackborn189ee182010-12-02 21:48:53 -0800995 Log.i(TAG, "host=w:" + host.getMeasuredWidth() + ", h:" +
996 host.getMeasuredHeight() + ", params=" + params);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700997 }
Romain Guy2a83f002011-01-18 18:28:21 -0800998
999 final int surfaceGenerationId = mSurface.getGenerationId();
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001000 relayoutResult = relayoutWindow(params, viewVisibility, insetsPending);
1001
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001002 if (params != null) {
1003 params.flags = fl;
1004 }
1005
1006 if (DEBUG_LAYOUT) Log.v(TAG, "relayout: frame=" + frame.toShortString()
1007 + " content=" + mPendingContentInsets.toShortString()
1008 + " visible=" + mPendingVisibleInsets.toShortString()
1009 + " surface=" + mSurface);
Romain Guy8506ab42009-06-11 17:35:47 -07001010
Dianne Hackborn694f79b2010-03-17 19:44:59 -07001011 if (mPendingConfiguration.seq != 0) {
1012 if (DEBUG_CONFIGURATION) Log.v(TAG, "Visible with new config: "
1013 + mPendingConfiguration);
1014 updateConfiguration(mPendingConfiguration, !mFirst);
1015 mPendingConfiguration.seq = 0;
1016 }
1017
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001018 contentInsetsChanged = !mPendingContentInsets.equals(
1019 mAttachInfo.mContentInsets);
1020 visibleInsetsChanged = !mPendingVisibleInsets.equals(
1021 mAttachInfo.mVisibleInsets);
1022 if (contentInsetsChanged) {
1023 mAttachInfo.mContentInsets.set(mPendingContentInsets);
1024 host.fitSystemWindows(mAttachInfo.mContentInsets);
1025 if (DEBUG_LAYOUT) Log.v(TAG, "Content insets changing to: "
1026 + mAttachInfo.mContentInsets);
1027 }
1028 if (visibleInsetsChanged) {
1029 mAttachInfo.mVisibleInsets.set(mPendingVisibleInsets);
1030 if (DEBUG_LAYOUT) Log.v(TAG, "Visible insets changing to: "
1031 + mAttachInfo.mVisibleInsets);
1032 }
1033
1034 if (!hadSurface) {
1035 if (mSurface.isValid()) {
1036 // If we are creating a new surface, then we need to
1037 // completely redraw it. Also, when we get to the
1038 // point of drawing it we will hold off and schedule
1039 // a new traversal instead. This is so we can tell the
1040 // window manager about all of the windows being displayed
1041 // before actually drawing them, so it can display then
1042 // all at once.
1043 newSurface = true;
1044 fullRedrawNeeded = true;
Jack Palevich61a6e682009-10-09 17:37:50 -07001045 mPreviousTransparentRegion.setEmpty();
Romain Guy8506ab42009-06-11 17:35:47 -07001046
Romain Guyb051e892010-09-28 19:09:36 -07001047 if (mAttachInfo.mHardwareRenderer != null) {
Romain Guyc361da82010-10-25 15:29:10 -07001048 hwInitialized = mAttachInfo.mHardwareRenderer.initialize(mHolder);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001049 }
1050 }
1051 } else if (!mSurface.isValid()) {
1052 // If the surface has been removed, then reset the scroll
1053 // positions.
1054 mLastScrolledFocus = null;
1055 mScrollY = mCurScrollY = 0;
1056 if (mScroller != null) {
1057 mScroller.abortAnimation();
1058 }
Dianne Hackborn0f761d62010-11-30 22:06:10 -08001059 disposeResizeBitmap();
Romain Guy2a83f002011-01-18 18:28:21 -08001060 } else if (surfaceGenerationId != mSurface.getGenerationId() &&
1061 mSurfaceHolder == null && mAttachInfo.mHardwareRenderer != null) {
Romain Guy7d7b5492011-01-24 16:33:45 -08001062 fullRedrawNeeded = true;
Romain Guy2a83f002011-01-18 18:28:21 -08001063 mAttachInfo.mHardwareRenderer.updateSurface(mHolder);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001064 }
1065 } catch (RemoteException e) {
1066 }
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001067
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001068 if (DEBUG_ORIENTATION) Log.v(
Jeff Brownc5ed5912010-07-14 18:48:53 -07001069 TAG, "Relayout returned: frame=" + frame + ", surface=" + mSurface);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001070
1071 attachInfo.mWindowLeft = frame.left;
1072 attachInfo.mWindowTop = frame.top;
1073
1074 // !!FIXME!! This next section handles the case where we did not get the
1075 // window size we asked for. We should avoid this by getting a maximum size from
1076 // the window session beforehand.
1077 mWidth = frame.width();
1078 mHeight = frame.height();
1079
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001080 if (mSurfaceHolder != null) {
1081 // The app owns the surface; tell it about what is going on.
1082 if (mSurface.isValid()) {
1083 // XXX .copyFrom() doesn't work!
1084 //mSurfaceHolder.mSurface.copyFrom(mSurface);
1085 mSurfaceHolder.mSurface = mSurface;
1086 }
Jeff Brown30bc34f2011-01-25 12:56:56 -08001087 mSurfaceHolder.setSurfaceFrameSize(mWidth, mHeight);
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001088 mSurfaceHolder.mSurfaceLock.unlock();
1089 if (mSurface.isValid()) {
1090 if (!hadSurface) {
1091 mSurfaceHolder.ungetCallbacks();
1092
1093 mIsCreating = true;
1094 mSurfaceHolderCallback.surfaceCreated(mSurfaceHolder);
1095 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
1096 if (callbacks != null) {
1097 for (SurfaceHolder.Callback c : callbacks) {
1098 c.surfaceCreated(mSurfaceHolder);
1099 }
1100 }
1101 surfaceChanged = true;
1102 }
1103 if (surfaceChanged) {
1104 mSurfaceHolderCallback.surfaceChanged(mSurfaceHolder,
1105 lp.format, mWidth, mHeight);
1106 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
1107 if (callbacks != null) {
1108 for (SurfaceHolder.Callback c : callbacks) {
1109 c.surfaceChanged(mSurfaceHolder, lp.format,
1110 mWidth, mHeight);
1111 }
1112 }
1113 }
1114 mIsCreating = false;
1115 } else if (hadSurface) {
1116 mSurfaceHolder.ungetCallbacks();
1117 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
1118 mSurfaceHolderCallback.surfaceDestroyed(mSurfaceHolder);
1119 if (callbacks != null) {
1120 for (SurfaceHolder.Callback c : callbacks) {
1121 c.surfaceDestroyed(mSurfaceHolder);
1122 }
1123 }
1124 mSurfaceHolder.mSurfaceLock.lock();
1125 // Make surface invalid.
1126 //mSurfaceHolder.mSurface.copyFrom(mSurface);
1127 mSurfaceHolder.mSurface = new Surface();
1128 mSurfaceHolder.mSurfaceLock.unlock();
1129 }
1130 }
Romain Guy53389bd2010-09-07 17:16:32 -07001131
Romain Guy6b5108b2011-01-04 16:11:10 -08001132 if (hwInitialized || ((windowShouldResize || params != null) &&
Romain Guydbf78bd2010-12-07 17:04:03 -08001133 mAttachInfo.mHardwareRenderer != null &&
1134 mAttachInfo.mHardwareRenderer.isEnabled())) {
Romain Guyb051e892010-09-28 19:09:36 -07001135 mAttachInfo.mHardwareRenderer.setup(mWidth, mHeight);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001136 }
1137
1138 boolean focusChangedDueToTouchMode = ensureTouchModeLocally(
Romain Guy2d4cff62010-04-09 15:39:00 -07001139 (relayoutResult&WindowManagerImpl.RELAYOUT_IN_TOUCH_MODE) != 0);
Dianne Hackborn189ee182010-12-02 21:48:53 -08001140 if (focusChangedDueToTouchMode || mWidth != host.getMeasuredWidth()
1141 || mHeight != host.getMeasuredHeight() || contentInsetsChanged) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001142 childWidthMeasureSpec = getRootMeasureSpec(mWidth, lp.width);
1143 childHeightMeasureSpec = getRootMeasureSpec(mHeight, lp.height);
1144
1145 if (DEBUG_LAYOUT) Log.v(TAG, "Ooops, something changed! mWidth="
Dianne Hackborn189ee182010-12-02 21:48:53 -08001146 + mWidth + " measuredWidth=" + host.getMeasuredWidth()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001147 + " mHeight=" + mHeight
Dianne Hackbornff801ec2011-01-22 18:05:38 -08001148 + " measuredHeight=" + host.getMeasuredHeight()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001149 + " coveredInsetsChanged=" + contentInsetsChanged);
Romain Guy8506ab42009-06-11 17:35:47 -07001150
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001151 // Ask host how big it wants to be
1152 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
1153
1154 // Implementation of weights from WindowManager.LayoutParams
1155 // We just grow the dimensions as needed and re-measure if
1156 // needs be
Dianne Hackborn189ee182010-12-02 21:48:53 -08001157 int width = host.getMeasuredWidth();
1158 int height = host.getMeasuredHeight();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001159 boolean measureAgain = false;
1160
1161 if (lp.horizontalWeight > 0.0f) {
1162 width += (int) ((mWidth - width) * lp.horizontalWeight);
1163 childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(width,
1164 MeasureSpec.EXACTLY);
1165 measureAgain = true;
1166 }
1167 if (lp.verticalWeight > 0.0f) {
1168 height += (int) ((mHeight - height) * lp.verticalWeight);
1169 childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(height,
1170 MeasureSpec.EXACTLY);
1171 measureAgain = true;
1172 }
1173
1174 if (measureAgain) {
1175 if (DEBUG_LAYOUT) Log.v(TAG,
1176 "And hey let's measure once more: width=" + width
1177 + " height=" + height);
1178 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
1179 }
1180
1181 mLayoutRequested = true;
1182 }
1183 }
1184
1185 final boolean didLayout = mLayoutRequested;
1186 boolean triggerGlobalLayoutListener = didLayout
1187 || attachInfo.mRecomputeGlobalAttributes;
1188 if (didLayout) {
1189 mLayoutRequested = false;
1190 mScrollMayChange = true;
1191 if (DEBUG_ORIENTATION || DEBUG_LAYOUT) Log.v(
Jeff Brownc5ed5912010-07-14 18:48:53 -07001192 TAG, "Laying out " + host + " to (" +
Dianne Hackborn189ee182010-12-02 21:48:53 -08001193 host.getMeasuredWidth() + ", " + host.getMeasuredHeight() + ")");
Romain Guy13922e02009-05-12 17:56:14 -07001194 long startTime = 0L;
Romain Guy5429e1d2010-09-07 12:38:00 -07001195 if (ViewDebug.DEBUG_PROFILE_LAYOUT) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001196 startTime = SystemClock.elapsedRealtime();
1197 }
Dianne Hackborn189ee182010-12-02 21:48:53 -08001198 host.layout(0, 0, host.getMeasuredWidth(), host.getMeasuredHeight());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001199
Romain Guy13922e02009-05-12 17:56:14 -07001200 if (Config.DEBUG && ViewDebug.consistencyCheckEnabled) {
1201 if (!host.dispatchConsistencyCheck(ViewDebug.CONSISTENCY_LAYOUT)) {
1202 throw new IllegalStateException("The view hierarchy is an inconsistent state,"
1203 + "please refer to the logs with the tag "
1204 + ViewDebug.CONSISTENCY_LOG_TAG + " for more infomation.");
1205 }
1206 }
1207
Romain Guy5429e1d2010-09-07 12:38:00 -07001208 if (ViewDebug.DEBUG_PROFILE_LAYOUT) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001209 EventLog.writeEvent(60001, SystemClock.elapsedRealtime() - startTime);
1210 }
1211
1212 // By this point all views have been sized and positionned
1213 // We can compute the transparent area
1214
1215 if ((host.mPrivateFlags & View.REQUEST_TRANSPARENT_REGIONS) != 0) {
1216 // start out transparent
1217 // TODO: AVOID THAT CALL BY CACHING THE RESULT?
1218 host.getLocationInWindow(mTmpLocation);
1219 mTransparentRegion.set(mTmpLocation[0], mTmpLocation[1],
1220 mTmpLocation[0] + host.mRight - host.mLeft,
1221 mTmpLocation[1] + host.mBottom - host.mTop);
1222
1223 host.gatherTransparentRegion(mTransparentRegion);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001224 if (mTranslator != null) {
1225 mTranslator.translateRegionInWindowToScreen(mTransparentRegion);
1226 }
1227
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001228 if (!mTransparentRegion.equals(mPreviousTransparentRegion)) {
1229 mPreviousTransparentRegion.set(mTransparentRegion);
1230 // reconfigure window manager
1231 try {
1232 sWindowSession.setTransparentRegion(mWindow, mTransparentRegion);
1233 } catch (RemoteException e) {
1234 }
1235 }
1236 }
1237
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001238 if (DBG) {
1239 System.out.println("======================================");
1240 System.out.println("performTraversals -- after setFrame");
1241 host.debug();
1242 }
1243 }
1244
1245 if (triggerGlobalLayoutListener) {
1246 attachInfo.mRecomputeGlobalAttributes = false;
1247 attachInfo.mTreeObserver.dispatchOnGlobalLayout();
1248 }
1249
1250 if (computesInternalInsets) {
Jeff Brownfbf09772011-01-16 14:06:57 -08001251 // Clear the original insets.
1252 final ViewTreeObserver.InternalInsetsInfo insets = attachInfo.mGivenInternalInsets;
1253 insets.reset();
1254
1255 // Compute new insets in place.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001256 attachInfo.mTreeObserver.dispatchOnComputeInternalInsets(insets);
Jeff Brownfbf09772011-01-16 14:06:57 -08001257
1258 // Tell the window manager.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001259 if (insetsPending || !mLastGivenInsets.equals(insets)) {
1260 mLastGivenInsets.set(insets);
Jeff Brownfbf09772011-01-16 14:06:57 -08001261
1262 // Translate insets to screen coordinates if needed.
1263 final Rect contentInsets;
1264 final Rect visibleInsets;
1265 final Region touchableRegion;
1266 if (mTranslator != null) {
1267 contentInsets = mTranslator.getTranslatedContentInsets(insets.contentInsets);
1268 visibleInsets = mTranslator.getTranslatedVisibleInsets(insets.visibleInsets);
1269 touchableRegion = mTranslator.getTranslatedTouchableArea(insets.touchableRegion);
1270 } else {
1271 contentInsets = insets.contentInsets;
1272 visibleInsets = insets.visibleInsets;
1273 touchableRegion = insets.touchableRegion;
1274 }
1275
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001276 try {
1277 sWindowSession.setInsets(mWindow, insets.mTouchableInsets,
Jeff Brownfbf09772011-01-16 14:06:57 -08001278 contentInsets, visibleInsets, touchableRegion);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001279 } catch (RemoteException e) {
1280 }
1281 }
1282 }
Romain Guy8506ab42009-06-11 17:35:47 -07001283
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001284 if (mFirst) {
1285 // handle first focus request
1286 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: mView.hasFocus()="
1287 + mView.hasFocus());
1288 if (mView != null) {
1289 if (!mView.hasFocus()) {
1290 mView.requestFocus(View.FOCUS_FORWARD);
1291 mFocusedView = mRealFocusedView = mView.findFocus();
1292 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: requested focused view="
1293 + mFocusedView);
1294 } else {
1295 mRealFocusedView = mView.findFocus();
1296 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: existing focused view="
1297 + mRealFocusedView);
1298 }
1299 }
1300 }
1301
1302 mFirst = false;
1303 mWillDrawSoon = false;
1304 mNewSurfaceNeeded = false;
1305 mViewVisibility = viewVisibility;
1306
1307 if (mAttachInfo.mHasWindowFocus) {
1308 final boolean imTarget = WindowManager.LayoutParams
1309 .mayUseInputMethod(mWindowAttributes.flags);
1310 if (imTarget != mLastWasImTarget) {
1311 mLastWasImTarget = imTarget;
1312 InputMethodManager imm = InputMethodManager.peekInstance();
1313 if (imm != null && imTarget) {
1314 imm.startGettingWindowFocus(mView);
1315 imm.onWindowFocus(mView, mView.findFocus(),
1316 mWindowAttributes.softInputMode,
1317 !mHasHadWindowFocus, mWindowAttributes.flags);
1318 }
1319 }
1320 }
Romain Guy8506ab42009-06-11 17:35:47 -07001321
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001322 boolean cancelDraw = attachInfo.mTreeObserver.dispatchOnPreDraw();
1323
1324 if (!cancelDraw && !newSurface) {
1325 mFullRedrawNeeded = false;
1326 draw(fullRedrawNeeded);
1327
1328 if ((relayoutResult&WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0
1329 || mReportNextDraw) {
1330 if (LOCAL_LOGV) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001331 Log.v(TAG, "FINISHED DRAWING: " + mWindowAttributes.getTitle());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001332 }
1333 mReportNextDraw = false;
Dianne Hackbornd76b67c2010-07-13 17:48:30 -07001334 if (mSurfaceHolder != null && mSurface.isValid()) {
1335 mSurfaceHolderCallback.surfaceRedrawNeeded(mSurfaceHolder);
1336 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
1337 if (callbacks != null) {
1338 for (SurfaceHolder.Callback c : callbacks) {
1339 if (c instanceof SurfaceHolder.Callback2) {
1340 ((SurfaceHolder.Callback2)c).surfaceRedrawNeeded(
1341 mSurfaceHolder);
1342 }
1343 }
1344 }
1345 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001346 try {
1347 sWindowSession.finishDrawing(mWindow);
1348 } catch (RemoteException e) {
1349 }
1350 }
1351 } else {
1352 // We were supposed to report when we are done drawing. Since we canceled the
1353 // draw, remember it here.
1354 if ((relayoutResult&WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0) {
1355 mReportNextDraw = true;
1356 }
1357 if (fullRedrawNeeded) {
1358 mFullRedrawNeeded = true;
1359 }
1360 // Try again
1361 scheduleTraversals();
1362 }
1363 }
1364
1365 public void requestTransparentRegion(View child) {
1366 // the test below should not fail unless someone is messing with us
1367 checkThread();
1368 if (mView == child) {
1369 mView.mPrivateFlags |= View.REQUEST_TRANSPARENT_REGIONS;
1370 // Need to make sure we re-evaluate the window attributes next
1371 // time around, to ensure the window has the correct format.
1372 mWindowAttributesChanged = true;
Mathias Agopian1bd80ad2010-11-04 17:13:39 -07001373 requestLayout();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001374 }
1375 }
1376
1377 /**
1378 * Figures out the measure spec for the root view in a window based on it's
1379 * layout params.
1380 *
1381 * @param windowSize
1382 * The available width or height of the window
1383 *
1384 * @param rootDimension
1385 * The layout params for one dimension (width or height) of the
1386 * window.
1387 *
1388 * @return The measure spec to use to measure the root view.
1389 */
1390 private int getRootMeasureSpec(int windowSize, int rootDimension) {
1391 int measureSpec;
1392 switch (rootDimension) {
1393
Romain Guy980a9382010-01-08 15:06:28 -08001394 case ViewGroup.LayoutParams.MATCH_PARENT:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001395 // Window can't resize. Force root view to be windowSize.
1396 measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.EXACTLY);
1397 break;
1398 case ViewGroup.LayoutParams.WRAP_CONTENT:
1399 // Window can resize. Set max size for root view.
1400 measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.AT_MOST);
1401 break;
1402 default:
1403 // Window wants to be an exact size. Force root view to be that size.
1404 measureSpec = MeasureSpec.makeMeasureSpec(rootDimension, MeasureSpec.EXACTLY);
1405 break;
1406 }
1407 return measureSpec;
1408 }
1409
Dianne Hackborn0f761d62010-11-30 22:06:10 -08001410 int mHardwareYOffset;
1411 int mResizeAlpha;
1412 final Paint mResizePaint = new Paint();
1413
1414 public void onHardwarePreDraw(Canvas canvas) {
1415 canvas.translate(0, -mHardwareYOffset);
1416 }
1417
1418 public void onHardwarePostDraw(Canvas canvas) {
1419 if (mResizeBitmap != null) {
1420 canvas.translate(0, mHardwareYOffset);
1421 mResizePaint.setAlpha(mResizeAlpha);
1422 canvas.drawBitmap(mResizeBitmap, 0, 0, mResizePaint);
1423 }
1424 }
1425
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001426 private void draw(boolean fullRedrawNeeded) {
1427 Surface surface = mSurface;
1428 if (surface == null || !surface.isValid()) {
1429 return;
1430 }
1431
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001432 if (!sFirstDrawComplete) {
1433 synchronized (sFirstDrawHandlers) {
1434 sFirstDrawComplete = true;
Romain Guy812ccbe2010-06-01 14:07:24 -07001435 final int count = sFirstDrawHandlers.size();
1436 for (int i = 0; i< count; i++) {
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001437 post(sFirstDrawHandlers.get(i));
1438 }
1439 }
1440 }
1441
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001442 scrollToRectOrFocus(null, false);
1443
1444 if (mAttachInfo.mViewScrollChanged) {
1445 mAttachInfo.mViewScrollChanged = false;
1446 mAttachInfo.mTreeObserver.dispatchOnScrollChanged();
1447 }
Romain Guy8506ab42009-06-11 17:35:47 -07001448
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001449 int yoff;
Dianne Hackborn0f761d62010-11-30 22:06:10 -08001450 boolean animating = mScroller != null && mScroller.computeScrollOffset();
1451 if (animating) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001452 yoff = mScroller.getCurrY();
1453 } else {
1454 yoff = mScrollY;
1455 }
1456 if (mCurScrollY != yoff) {
1457 mCurScrollY = yoff;
1458 fullRedrawNeeded = true;
1459 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001460 float appScale = mAttachInfo.mApplicationScale;
1461 boolean scalingRequired = mAttachInfo.mScalingRequired;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001462
Dianne Hackborn0f761d62010-11-30 22:06:10 -08001463 int resizeAlpha = 0;
1464 if (mResizeBitmap != null) {
1465 long deltaTime = SystemClock.uptimeMillis() - mResizeBitmapStartTime;
1466 if (deltaTime < mResizeBitmapDuration) {
1467 float amt = deltaTime/(float)mResizeBitmapDuration;
1468 amt = mResizeInterpolator.getInterpolation(amt);
1469 animating = true;
1470 resizeAlpha = 255 - (int)(amt*255);
1471 } else {
1472 disposeResizeBitmap();
1473 }
1474 }
1475
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001476 Rect dirty = mDirty;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001477 if (mSurfaceHolder != null) {
1478 // The app owns the surface, we won't draw.
1479 dirty.setEmpty();
Dianne Hackborn0f761d62010-11-30 22:06:10 -08001480 if (animating) {
1481 if (mScroller != null) {
1482 mScroller.abortAnimation();
1483 }
1484 disposeResizeBitmap();
1485 }
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001486 return;
1487 }
Romain Guy58ef7fb2010-09-13 12:52:37 -07001488
1489 if (fullRedrawNeeded) {
1490 mAttachInfo.mIgnoreDirtyState = true;
1491 dirty.union(0, 0, (int) (mWidth * appScale + 0.5f), (int) (mHeight * appScale + 0.5f));
1492 }
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001493
Romain Guyb051e892010-09-28 19:09:36 -07001494 if (mAttachInfo.mHardwareRenderer != null && mAttachInfo.mHardwareRenderer.isEnabled()) {
Romain Guyfd507262010-10-10 15:42:49 -07001495 if (!dirty.isEmpty() || mIsAnimating) {
Romain Guy101e2ae2010-10-11 12:41:21 -07001496 mIsAnimating = false;
Dianne Hackborn0f761d62010-11-30 22:06:10 -08001497 mHardwareYOffset = yoff;
1498 mResizeAlpha = resizeAlpha;
Romain Guy7d7b5492011-01-24 16:33:45 -08001499
1500 mCurrentDirty.set(dirty);
1501 mCurrentDirty.union(mPreviousDirty);
1502 mPreviousDirty.set(dirty);
1503 dirty.setEmpty();
1504
Romain Guyf90f8172011-01-25 22:53:24 -08001505 Rect currentDirty = mCurrentDirty;
1506 if (animating) {
1507 currentDirty = null;
1508 }
1509
1510 mAttachInfo.mHardwareRenderer.draw(mView, mAttachInfo, this, currentDirty);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001511 }
Romain Guy812ccbe2010-06-01 14:07:24 -07001512
Dianne Hackborn0f761d62010-11-30 22:06:10 -08001513 if (animating) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001514 mFullRedrawNeeded = true;
1515 scheduleTraversals();
1516 }
Romain Guy812ccbe2010-06-01 14:07:24 -07001517
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001518 return;
1519 }
1520
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001521 if (DEBUG_ORIENTATION || DEBUG_DRAW) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001522 Log.v(TAG, "Draw " + mView + "/"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001523 + mWindowAttributes.getTitle()
1524 + ": dirty={" + dirty.left + "," + dirty.top
1525 + "," + dirty.right + "," + dirty.bottom + "} surface="
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001526 + surface + " surface.isValid()=" + surface.isValid() + ", appScale:" +
1527 appScale + ", width=" + mWidth + ", height=" + mHeight);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001528 }
1529
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001530 if (!dirty.isEmpty() || mIsAnimating) {
1531 Canvas canvas;
1532 try {
1533 int left = dirty.left;
1534 int top = dirty.top;
1535 int right = dirty.right;
1536 int bottom = dirty.bottom;
1537 canvas = surface.lockCanvas(dirty);
Romain Guy5bcdff42009-05-14 21:27:18 -07001538
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001539 if (left != dirty.left || top != dirty.top || right != dirty.right ||
1540 bottom != dirty.bottom) {
1541 mAttachInfo.mIgnoreDirtyState = true;
1542 }
1543
1544 // TODO: Do this in native
1545 canvas.setDensity(mDensity);
1546 } catch (Surface.OutOfResourcesException e) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001547 Log.e(TAG, "OutOfResourcesException locking surface", e);
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001548 // TODO: we should ask the window manager to do something!
1549 // for now we just do nothing
1550 return;
1551 } catch (IllegalArgumentException e) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001552 Log.e(TAG, "IllegalArgumentException locking surface", e);
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001553 // TODO: we should ask the window manager to do something!
1554 // for now we just do nothing
1555 return;
Romain Guy5bcdff42009-05-14 21:27:18 -07001556 }
1557
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001558 try {
1559 if (!dirty.isEmpty() || mIsAnimating) {
1560 long startTime = 0L;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001561
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001562 if (DEBUG_ORIENTATION || DEBUG_DRAW) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001563 Log.v(TAG, "Surface " + surface + " drawing to bitmap w="
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001564 + canvas.getWidth() + ", h=" + canvas.getHeight());
1565 //canvas.drawARGB(255, 255, 0, 0);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001566 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001567
Romain Guy5429e1d2010-09-07 12:38:00 -07001568 if (ViewDebug.DEBUG_PROFILE_DRAWING) {
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001569 startTime = SystemClock.elapsedRealtime();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001570 }
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001571
1572 // If this bitmap's format includes an alpha channel, we
1573 // need to clear it before drawing so that the child will
1574 // properly re-composite its drawing on a transparent
1575 // background. This automatically respects the clip/dirty region
1576 // or
1577 // If we are applying an offset, we need to clear the area
1578 // where the offset doesn't appear to avoid having garbage
1579 // left in the blank areas.
1580 if (!canvas.isOpaque() || yoff != 0) {
1581 canvas.drawColor(0, PorterDuff.Mode.CLEAR);
1582 }
1583
1584 dirty.setEmpty();
1585 mIsAnimating = false;
1586 mAttachInfo.mDrawingTime = SystemClock.uptimeMillis();
1587 mView.mPrivateFlags |= View.DRAWN;
1588
1589 if (DEBUG_DRAW) {
1590 Context cxt = mView.getContext();
1591 Log.i(TAG, "Drawing: package:" + cxt.getPackageName() +
1592 ", metrics=" + cxt.getResources().getDisplayMetrics() +
1593 ", compatibilityInfo=" + cxt.getResources().getCompatibilityInfo());
1594 }
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001595 try {
1596 canvas.translate(0, -yoff);
1597 if (mTranslator != null) {
1598 mTranslator.translateCanvas(canvas);
1599 }
1600 canvas.setScreenDensity(scalingRequired
1601 ? DisplayMetrics.DENSITY_DEVICE : 0);
1602 mView.draw(canvas);
1603 } finally {
1604 mAttachInfo.mIgnoreDirtyState = false;
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001605 }
1606
1607 if (Config.DEBUG && ViewDebug.consistencyCheckEnabled) {
1608 mView.dispatchConsistencyCheck(ViewDebug.CONSISTENCY_DRAWING);
1609 }
1610
Romain Guy5429e1d2010-09-07 12:38:00 -07001611 if (SHOW_FPS || ViewDebug.DEBUG_SHOW_FPS) {
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001612 int now = (int)SystemClock.elapsedRealtime();
1613 if (sDrawTime != 0) {
1614 nativeShowFPS(canvas, now - sDrawTime);
1615 }
1616 sDrawTime = now;
1617 }
1618
Romain Guy5429e1d2010-09-07 12:38:00 -07001619 if (ViewDebug.DEBUG_PROFILE_DRAWING) {
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001620 EventLog.writeEvent(60000, SystemClock.elapsedRealtime() - startTime);
1621 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001622 }
1623
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001624 } finally {
1625 surface.unlockCanvasAndPost(canvas);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001626 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001627 }
1628
1629 if (LOCAL_LOGV) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001630 Log.v(TAG, "Surface " + surface + " unlockCanvasAndPost");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001631 }
Romain Guy8506ab42009-06-11 17:35:47 -07001632
Dianne Hackborn0f761d62010-11-30 22:06:10 -08001633 if (animating) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001634 mFullRedrawNeeded = true;
1635 scheduleTraversals();
1636 }
1637 }
1638
1639 boolean scrollToRectOrFocus(Rect rectangle, boolean immediate) {
1640 final View.AttachInfo attachInfo = mAttachInfo;
1641 final Rect ci = attachInfo.mContentInsets;
1642 final Rect vi = attachInfo.mVisibleInsets;
1643 int scrollY = 0;
1644 boolean handled = false;
Romain Guy8506ab42009-06-11 17:35:47 -07001645
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001646 if (vi.left > ci.left || vi.top > ci.top
1647 || vi.right > ci.right || vi.bottom > ci.bottom) {
1648 // We'll assume that we aren't going to change the scroll
1649 // offset, since we want to avoid that unless it is actually
1650 // going to make the focus visible... otherwise we scroll
1651 // all over the place.
1652 scrollY = mScrollY;
1653 // We can be called for two different situations: during a draw,
1654 // to update the scroll position if the focus has changed (in which
1655 // case 'rectangle' is null), or in response to a
1656 // requestChildRectangleOnScreen() call (in which case 'rectangle'
1657 // is non-null and we just want to scroll to whatever that
1658 // rectangle is).
1659 View focus = mRealFocusedView;
Romain Guye8b16522009-07-14 13:06:42 -07001660
1661 // When in touch mode, focus points to the previously focused view,
1662 // which may have been removed from the view hierarchy. The following
Joe Onoratob71193b2009-11-24 18:34:42 -05001663 // line checks whether the view is still in our hierarchy.
1664 if (focus == null || focus.mAttachInfo != mAttachInfo) {
Romain Guye8b16522009-07-14 13:06:42 -07001665 mRealFocusedView = null;
1666 return false;
1667 }
1668
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001669 if (focus != mLastScrolledFocus) {
1670 // If the focus has changed, then ignore any requests to scroll
1671 // to a rectangle; first we want to make sure the entire focus
1672 // view is visible.
1673 rectangle = null;
1674 }
1675 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Eval scroll: focus=" + focus
1676 + " rectangle=" + rectangle + " ci=" + ci
1677 + " vi=" + vi);
1678 if (focus == mLastScrolledFocus && !mScrollMayChange
1679 && rectangle == null) {
1680 // Optimization: if the focus hasn't changed since last
1681 // time, and no layout has happened, then just leave things
1682 // as they are.
1683 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Keeping scroll y="
1684 + mScrollY + " vi=" + vi.toShortString());
1685 } else if (focus != null) {
1686 // We need to determine if the currently focused view is
1687 // within the visible part of the window and, if not, apply
1688 // a pan so it can be seen.
1689 mLastScrolledFocus = focus;
1690 mScrollMayChange = false;
1691 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Need to scroll?");
1692 // Try to find the rectangle from the focus view.
1693 if (focus.getGlobalVisibleRect(mVisRect, null)) {
1694 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Root w="
1695 + mView.getWidth() + " h=" + mView.getHeight()
1696 + " ci=" + ci.toShortString()
1697 + " vi=" + vi.toShortString());
1698 if (rectangle == null) {
1699 focus.getFocusedRect(mTempRect);
1700 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Focus " + focus
1701 + ": focusRect=" + mTempRect.toShortString());
Dianne Hackborn1c6a8942010-03-23 16:34:20 -07001702 if (mView instanceof ViewGroup) {
1703 ((ViewGroup) mView).offsetDescendantRectToMyCoords(
1704 focus, mTempRect);
1705 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001706 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1707 "Focus in window: focusRect="
1708 + mTempRect.toShortString()
1709 + " visRect=" + mVisRect.toShortString());
1710 } else {
1711 mTempRect.set(rectangle);
1712 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1713 "Request scroll to rect: "
1714 + mTempRect.toShortString()
1715 + " visRect=" + mVisRect.toShortString());
1716 }
1717 if (mTempRect.intersect(mVisRect)) {
1718 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1719 "Focus window visible rect: "
1720 + mTempRect.toShortString());
1721 if (mTempRect.height() >
1722 (mView.getHeight()-vi.top-vi.bottom)) {
1723 // If the focus simply is not going to fit, then
1724 // best is probably just to leave things as-is.
1725 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1726 "Too tall; leaving scrollY=" + scrollY);
1727 } else if ((mTempRect.top-scrollY) < vi.top) {
1728 scrollY -= vi.top - (mTempRect.top-scrollY);
1729 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1730 "Top covered; scrollY=" + scrollY);
1731 } else if ((mTempRect.bottom-scrollY)
1732 > (mView.getHeight()-vi.bottom)) {
1733 scrollY += (mTempRect.bottom-scrollY)
1734 - (mView.getHeight()-vi.bottom);
1735 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1736 "Bottom covered; scrollY=" + scrollY);
1737 }
1738 handled = true;
1739 }
1740 }
1741 }
1742 }
Romain Guy8506ab42009-06-11 17:35:47 -07001743
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001744 if (scrollY != mScrollY) {
1745 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Pan scroll changed: old="
1746 + mScrollY + " , new=" + scrollY);
Dianne Hackborn0f761d62010-11-30 22:06:10 -08001747 if (!immediate && mResizeBitmap == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001748 if (mScroller == null) {
1749 mScroller = new Scroller(mView.getContext());
1750 }
1751 mScroller.startScroll(0, mScrollY, 0, scrollY-mScrollY);
1752 } else if (mScroller != null) {
1753 mScroller.abortAnimation();
1754 }
1755 mScrollY = scrollY;
1756 }
Romain Guy8506ab42009-06-11 17:35:47 -07001757
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001758 return handled;
1759 }
Romain Guy8506ab42009-06-11 17:35:47 -07001760
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001761 public void requestChildFocus(View child, View focused) {
1762 checkThread();
1763 if (mFocusedView != focused) {
1764 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(mFocusedView, focused);
1765 scheduleTraversals();
1766 }
1767 mFocusedView = mRealFocusedView = focused;
1768 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Request child focus: focus now "
1769 + mFocusedView);
1770 }
1771
1772 public void clearChildFocus(View child) {
1773 checkThread();
1774
1775 View oldFocus = mFocusedView;
1776
1777 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Clearing child focus");
1778 mFocusedView = mRealFocusedView = null;
1779 if (mView != null && !mView.hasFocus()) {
1780 // If a view gets the focus, the listener will be invoked from requestChildFocus()
1781 if (!mView.requestFocus(View.FOCUS_FORWARD)) {
1782 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
1783 }
1784 } else if (oldFocus != null) {
1785 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
1786 }
1787 }
1788
1789
1790 public void focusableViewAvailable(View v) {
1791 checkThread();
1792
1793 if (mView != null && !mView.hasFocus()) {
1794 v.requestFocus();
1795 } else {
1796 // the one case where will transfer focus away from the current one
1797 // is if the current view is a view group that prefers to give focus
1798 // to its children first AND the view is a descendant of it.
1799 mFocusedView = mView.findFocus();
1800 boolean descendantsHaveDibsOnFocus =
1801 (mFocusedView instanceof ViewGroup) &&
1802 (((ViewGroup) mFocusedView).getDescendantFocusability() ==
1803 ViewGroup.FOCUS_AFTER_DESCENDANTS);
1804 if (descendantsHaveDibsOnFocus && isViewDescendantOf(v, mFocusedView)) {
1805 // If a view gets the focus, the listener will be invoked from requestChildFocus()
1806 v.requestFocus();
1807 }
1808 }
1809 }
1810
1811 public void recomputeViewAttributes(View child) {
1812 checkThread();
1813 if (mView == child) {
1814 mAttachInfo.mRecomputeGlobalAttributes = true;
1815 if (!mWillDrawSoon) {
1816 scheduleTraversals();
1817 }
1818 }
1819 }
1820
1821 void dispatchDetachedFromWindow() {
Romain Guy90fc03b2011-01-16 13:07:15 -08001822 if (mView != null && mView.mAttachInfo != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001823 mView.dispatchDetachedFromWindow();
1824 }
1825
1826 mView = null;
1827 mAttachInfo.mRootView = null;
Mathias Agopian5583dc62009-07-09 16:28:11 -07001828 mAttachInfo.mSurface = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001829
Romain Guy29d89972010-09-22 16:10:57 -07001830 destroyHardwareRenderer();
Romain Guy4caa4ed2010-08-25 14:46:24 -07001831
Dianne Hackborn0586a1b2009-09-06 21:08:27 -07001832 mSurface.release();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001833
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001834 if (mInputChannel != null) {
1835 if (mInputQueueCallback != null) {
1836 mInputQueueCallback.onInputQueueDestroyed(mInputQueue);
1837 mInputQueueCallback = null;
1838 } else {
1839 InputQueue.unregisterInputChannel(mInputChannel);
Jeff Brown46b9ac02010-04-22 18:58:52 -07001840 }
1841 }
1842
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001843 try {
1844 sWindowSession.remove(mWindow);
1845 } catch (RemoteException e) {
1846 }
Jeff Brown349703e2010-06-22 01:27:15 -07001847
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001848 // Dispose the input channel after removing the window so the Window Manager
1849 // doesn't interpret the input channel being closed as an abnormal termination.
1850 if (mInputChannel != null) {
1851 mInputChannel.dispose();
1852 mInputChannel = null;
Jeff Brown349703e2010-06-22 01:27:15 -07001853 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001854 }
Romain Guy8506ab42009-06-11 17:35:47 -07001855
Dianne Hackborn694f79b2010-03-17 19:44:59 -07001856 void updateConfiguration(Configuration config, boolean force) {
1857 if (DEBUG_CONFIGURATION) Log.v(TAG,
1858 "Applying new config to window "
1859 + mWindowAttributes.getTitle()
1860 + ": " + config);
1861 synchronized (sConfigCallbacks) {
1862 for (int i=sConfigCallbacks.size()-1; i>=0; i--) {
1863 sConfigCallbacks.get(i).onConfigurationChanged(config);
1864 }
1865 }
1866 if (mView != null) {
1867 // At this point the resources have been updated to
1868 // have the most recent config, whatever that is. Use
1869 // the on in them which may be newer.
1870 if (mView != null) {
1871 config = mView.getResources().getConfiguration();
1872 }
1873 if (force || mLastConfiguration.diff(config) != 0) {
1874 mLastConfiguration.setTo(config);
1875 mView.dispatchConfigurationChanged(config);
1876 }
1877 }
1878 }
1879
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001880 /**
1881 * Return true if child is an ancestor of parent, (or equal to the parent).
1882 */
1883 private static boolean isViewDescendantOf(View child, View parent) {
1884 if (child == parent) {
1885 return true;
1886 }
1887
1888 final ViewParent theParent = child.getParent();
1889 return (theParent instanceof ViewGroup) && isViewDescendantOf((View) theParent, parent);
1890 }
1891
Romain Guycdb86672010-03-18 18:54:50 -07001892 private static void forceLayout(View view) {
1893 view.forceLayout();
1894 if (view instanceof ViewGroup) {
1895 ViewGroup group = (ViewGroup) view;
1896 final int count = group.getChildCount();
1897 for (int i = 0; i < count; i++) {
1898 forceLayout(group.getChildAt(i));
1899 }
1900 }
1901 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001902
1903 public final static int DO_TRAVERSAL = 1000;
1904 public final static int DIE = 1001;
1905 public final static int RESIZED = 1002;
1906 public final static int RESIZED_REPORT = 1003;
1907 public final static int WINDOW_FOCUS_CHANGED = 1004;
1908 public final static int DISPATCH_KEY = 1005;
1909 public final static int DISPATCH_POINTER = 1006;
1910 public final static int DISPATCH_TRACKBALL = 1007;
1911 public final static int DISPATCH_APP_VISIBILITY = 1008;
1912 public final static int DISPATCH_GET_NEW_SURFACE = 1009;
1913 public final static int FINISHED_EVENT = 1010;
1914 public final static int DISPATCH_KEY_FROM_IME = 1011;
1915 public final static int FINISH_INPUT_CONNECTION = 1012;
1916 public final static int CHECK_FOCUS = 1013;
Dianne Hackbornffa42482009-09-23 22:20:11 -07001917 public final static int CLOSE_SYSTEM_DIALOGS = 1014;
Christopher Tatea53146c2010-09-07 11:57:52 -07001918 public final static int DISPATCH_DRAG_EVENT = 1015;
Chris Tate91e9bb32010-10-12 12:58:43 -07001919 public final static int DISPATCH_DRAG_LOCATION_EVENT = 1016;
Joe Onorato664644d2011-01-23 17:53:23 -08001920 public final static int DISPATCH_SYSTEM_UI_VISIBILITY = 1017;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001921
1922 @Override
1923 public void handleMessage(Message msg) {
1924 switch (msg.what) {
1925 case View.AttachInfo.INVALIDATE_MSG:
1926 ((View) msg.obj).invalidate();
1927 break;
1928 case View.AttachInfo.INVALIDATE_RECT_MSG:
1929 final View.AttachInfo.InvalidateInfo info = (View.AttachInfo.InvalidateInfo) msg.obj;
1930 info.target.invalidate(info.left, info.top, info.right, info.bottom);
1931 info.release();
1932 break;
1933 case DO_TRAVERSAL:
1934 if (mProfile) {
1935 Debug.startMethodTracing("ViewRoot");
1936 }
1937
1938 performTraversals();
1939
1940 if (mProfile) {
1941 Debug.stopMethodTracing();
1942 mProfile = false;
1943 }
1944 break;
1945 case FINISHED_EVENT:
1946 handleFinishedEvent(msg.arg1, msg.arg2 != 0);
1947 break;
1948 case DISPATCH_KEY:
Jeff Brown92ff1dd2010-08-11 16:16:06 -07001949 deliverKeyEvent((KeyEvent)msg.obj, msg.arg1 != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001950 break;
Jeff Brown3915bb82010-11-05 15:02:16 -07001951 case DISPATCH_POINTER:
1952 deliverPointerEvent((MotionEvent) msg.obj, msg.arg1 != 0);
1953 break;
1954 case DISPATCH_TRACKBALL:
1955 deliverTrackballEvent((MotionEvent) msg.obj, msg.arg1 != 0);
1956 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001957 case DISPATCH_APP_VISIBILITY:
1958 handleAppVisibility(msg.arg1 != 0);
1959 break;
1960 case DISPATCH_GET_NEW_SURFACE:
1961 handleGetNewSurface();
1962 break;
1963 case RESIZED:
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001964 ResizedInfo ri = (ResizedInfo)msg.obj;
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001965
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001966 if (mWinFrame.width() == msg.arg1 && mWinFrame.height() == msg.arg2
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001967 && mPendingContentInsets.equals(ri.coveredInsets)
Dianne Hackbornd49258f2010-03-26 00:44:29 -07001968 && mPendingVisibleInsets.equals(ri.visibleInsets)
1969 && ((ResizedInfo)msg.obj).newConfig == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001970 break;
1971 }
1972 // fall through...
1973 case RESIZED_REPORT:
1974 if (mAdded) {
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001975 Configuration config = ((ResizedInfo)msg.obj).newConfig;
1976 if (config != null) {
Dianne Hackborn694f79b2010-03-17 19:44:59 -07001977 updateConfiguration(config, false);
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001978 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001979 mWinFrame.left = 0;
1980 mWinFrame.right = msg.arg1;
1981 mWinFrame.top = 0;
1982 mWinFrame.bottom = msg.arg2;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001983 mPendingContentInsets.set(((ResizedInfo)msg.obj).coveredInsets);
1984 mPendingVisibleInsets.set(((ResizedInfo)msg.obj).visibleInsets);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001985 if (msg.what == RESIZED_REPORT) {
1986 mReportNextDraw = true;
1987 }
Romain Guycdb86672010-03-18 18:54:50 -07001988
1989 if (mView != null) {
1990 forceLayout(mView);
1991 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001992 requestLayout();
1993 }
1994 break;
1995 case WINDOW_FOCUS_CHANGED: {
1996 if (mAdded) {
1997 boolean hasWindowFocus = msg.arg1 != 0;
1998 mAttachInfo.mHasWindowFocus = hasWindowFocus;
1999 if (hasWindowFocus) {
2000 boolean inTouchMode = msg.arg2 != 0;
Romain Guy2d4cff62010-04-09 15:39:00 -07002001 ensureTouchModeLocally(inTouchMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002002
Romain Guyc361da82010-10-25 15:29:10 -07002003 if (mAttachInfo.mHardwareRenderer != null &&
2004 mSurface != null && mSurface.isValid()) {
Romain Guy7d7b5492011-01-24 16:33:45 -08002005 mFullRedrawNeeded = true;
Romain Guyb051e892010-09-28 19:09:36 -07002006 mAttachInfo.mHardwareRenderer.initializeIfNeeded(mWidth, mHeight,
2007 mAttachInfo, mHolder);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002008 }
2009 }
Romain Guy8506ab42009-06-11 17:35:47 -07002010
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002011 mLastWasImTarget = WindowManager.LayoutParams
2012 .mayUseInputMethod(mWindowAttributes.flags);
Romain Guy8506ab42009-06-11 17:35:47 -07002013
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002014 InputMethodManager imm = InputMethodManager.peekInstance();
2015 if (mView != null) {
2016 if (hasWindowFocus && imm != null && mLastWasImTarget) {
2017 imm.startGettingWindowFocus(mView);
2018 }
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07002019 mAttachInfo.mKeyDispatchState.reset();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002020 mView.dispatchWindowFocusChanged(hasWindowFocus);
2021 }
svetoslavganov75986cf2009-05-14 22:28:01 -07002022
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002023 // Note: must be done after the focus change callbacks,
2024 // so all of the view state is set up correctly.
2025 if (hasWindowFocus) {
2026 if (imm != null && mLastWasImTarget) {
2027 imm.onWindowFocus(mView, mView.findFocus(),
2028 mWindowAttributes.softInputMode,
2029 !mHasHadWindowFocus, mWindowAttributes.flags);
2030 }
2031 // Clear the forward bit. We can just do this directly, since
2032 // the window manager doesn't care about it.
2033 mWindowAttributes.softInputMode &=
2034 ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
2035 ((WindowManager.LayoutParams)mView.getLayoutParams())
2036 .softInputMode &=
2037 ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
2038 mHasHadWindowFocus = true;
2039 }
svetoslavganov75986cf2009-05-14 22:28:01 -07002040
2041 if (hasWindowFocus && mView != null) {
2042 sendAccessibilityEvents();
2043 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002044 }
2045 } break;
2046 case DIE:
Dianne Hackborn94d69142009-09-28 22:14:42 -07002047 doDie();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002048 break;
The Android Open Source Project10592532009-03-18 17:39:46 -07002049 case DISPATCH_KEY_FROM_IME: {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002050 if (LOCAL_LOGV) Log.v(
Jeff Brownc5ed5912010-07-14 18:48:53 -07002051 TAG, "Dispatching key "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002052 + msg.obj + " from IME to " + mView);
The Android Open Source Project10592532009-03-18 17:39:46 -07002053 KeyEvent event = (KeyEvent)msg.obj;
2054 if ((event.getFlags()&KeyEvent.FLAG_FROM_SYSTEM) != 0) {
2055 // The IME is trying to say this event is from the
2056 // system! Bad bad bad!
Romain Guy812ccbe2010-06-01 14:07:24 -07002057 event = KeyEvent.changeFlags(event, event.getFlags() & ~KeyEvent.FLAG_FROM_SYSTEM);
The Android Open Source Project10592532009-03-18 17:39:46 -07002058 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002059 deliverKeyEventPostIme((KeyEvent)msg.obj, false);
The Android Open Source Project10592532009-03-18 17:39:46 -07002060 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002061 case FINISH_INPUT_CONNECTION: {
2062 InputMethodManager imm = InputMethodManager.peekInstance();
2063 if (imm != null) {
2064 imm.reportFinishInputConnection((InputConnection)msg.obj);
2065 }
2066 } break;
2067 case CHECK_FOCUS: {
2068 InputMethodManager imm = InputMethodManager.peekInstance();
2069 if (imm != null) {
2070 imm.checkFocus();
2071 }
2072 } break;
Dianne Hackbornffa42482009-09-23 22:20:11 -07002073 case CLOSE_SYSTEM_DIALOGS: {
2074 if (mView != null) {
2075 mView.onCloseSystemDialogs((String)msg.obj);
2076 }
2077 } break;
Chris Tate91e9bb32010-10-12 12:58:43 -07002078 case DISPATCH_DRAG_EVENT:
2079 case DISPATCH_DRAG_LOCATION_EVENT: {
Christopher Tate7fb8b562011-01-20 13:46:41 -08002080 DragEvent event = (DragEvent)msg.obj;
2081 event.mLocalState = mLocalDragState; // only present when this app called startDrag()
2082 handleDragEvent(event);
Christopher Tatea53146c2010-09-07 11:57:52 -07002083 } break;
Joe Onorato664644d2011-01-23 17:53:23 -08002084 case DISPATCH_SYSTEM_UI_VISIBILITY: {
2085 handleDispatchSystemUiVisibilityChanged(msg.arg1);
2086 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002087 }
2088 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002089
Jeff Brown3915bb82010-11-05 15:02:16 -07002090 private void startInputEvent(InputQueue.FinishedCallback finishedCallback) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07002091 if (mFinishedCallback != null) {
2092 Slog.w(TAG, "Received a new input event from the input queue but there is "
2093 + "already an unfinished input event in progress.");
2094 }
2095
2096 mFinishedCallback = finishedCallback;
2097 }
2098
Jeff Brown3915bb82010-11-05 15:02:16 -07002099 private void finishInputEvent(boolean handled) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07002100 if (LOCAL_LOGV) Log.v(TAG, "Telling window manager input event is finished");
Jeff Brown92ff1dd2010-08-11 16:16:06 -07002101
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002102 if (mFinishedCallback != null) {
Jeff Brown3915bb82010-11-05 15:02:16 -07002103 mFinishedCallback.finished(handled);
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002104 mFinishedCallback = null;
Jeff Brown92ff1dd2010-08-11 16:16:06 -07002105 } else {
Jeff Brown93ed4e32010-09-23 13:51:48 -07002106 Slog.w(TAG, "Attempted to tell the input queue that the current input event "
2107 + "is finished but there is no input event actually in progress.");
Jeff Brown46b9ac02010-04-22 18:58:52 -07002108 }
2109 }
2110
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002111 /**
2112 * Something in the current window tells us we need to change the touch mode. For
2113 * example, we are not in touch mode, and the user touches the screen.
2114 *
2115 * If the touch mode has changed, tell the window manager, and handle it locally.
2116 *
2117 * @param inTouchMode Whether we want to be in touch mode.
2118 * @return True if the touch mode changed and focus changed was changed as a result
2119 */
2120 boolean ensureTouchMode(boolean inTouchMode) {
2121 if (DBG) Log.d("touchmode", "ensureTouchMode(" + inTouchMode + "), current "
2122 + "touch mode is " + mAttachInfo.mInTouchMode);
2123 if (mAttachInfo.mInTouchMode == inTouchMode) return false;
2124
2125 // tell the window manager
2126 try {
2127 sWindowSession.setInTouchMode(inTouchMode);
2128 } catch (RemoteException e) {
2129 throw new RuntimeException(e);
2130 }
2131
2132 // handle the change
Romain Guy2d4cff62010-04-09 15:39:00 -07002133 return ensureTouchModeLocally(inTouchMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002134 }
2135
2136 /**
2137 * Ensure that the touch mode for this window is set, and if it is changing,
2138 * take the appropriate action.
2139 * @param inTouchMode Whether we want to be in touch mode.
2140 * @return True if the touch mode changed and focus changed was changed as a result
2141 */
Romain Guy2d4cff62010-04-09 15:39:00 -07002142 private boolean ensureTouchModeLocally(boolean inTouchMode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002143 if (DBG) Log.d("touchmode", "ensureTouchModeLocally(" + inTouchMode + "), current "
2144 + "touch mode is " + mAttachInfo.mInTouchMode);
2145
2146 if (mAttachInfo.mInTouchMode == inTouchMode) return false;
2147
2148 mAttachInfo.mInTouchMode = inTouchMode;
2149 mAttachInfo.mTreeObserver.dispatchOnTouchModeChanged(inTouchMode);
2150
Romain Guy2d4cff62010-04-09 15:39:00 -07002151 return (inTouchMode) ? enterTouchMode() : leaveTouchMode();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002152 }
2153
2154 private boolean enterTouchMode() {
2155 if (mView != null) {
2156 if (mView.hasFocus()) {
2157 // note: not relying on mFocusedView here because this could
2158 // be when the window is first being added, and mFocused isn't
2159 // set yet.
2160 final View focused = mView.findFocus();
2161 if (focused != null && !focused.isFocusableInTouchMode()) {
2162
2163 final ViewGroup ancestorToTakeFocus =
2164 findAncestorToTakeFocusInTouchMode(focused);
2165 if (ancestorToTakeFocus != null) {
2166 // there is an ancestor that wants focus after its descendants that
2167 // is focusable in touch mode.. give it focus
2168 return ancestorToTakeFocus.requestFocus();
2169 } else {
2170 // nothing appropriate to have focus in touch mode, clear it out
2171 mView.unFocus();
2172 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(focused, null);
2173 mFocusedView = null;
2174 return true;
2175 }
2176 }
2177 }
2178 }
2179 return false;
2180 }
2181
2182
2183 /**
2184 * Find an ancestor of focused that wants focus after its descendants and is
2185 * focusable in touch mode.
2186 * @param focused The currently focused view.
2187 * @return An appropriate view, or null if no such view exists.
2188 */
2189 private ViewGroup findAncestorToTakeFocusInTouchMode(View focused) {
2190 ViewParent parent = focused.getParent();
2191 while (parent instanceof ViewGroup) {
2192 final ViewGroup vgParent = (ViewGroup) parent;
2193 if (vgParent.getDescendantFocusability() == ViewGroup.FOCUS_AFTER_DESCENDANTS
2194 && vgParent.isFocusableInTouchMode()) {
2195 return vgParent;
2196 }
2197 if (vgParent.isRootNamespace()) {
2198 return null;
2199 } else {
2200 parent = vgParent.getParent();
2201 }
2202 }
2203 return null;
2204 }
2205
2206 private boolean leaveTouchMode() {
2207 if (mView != null) {
2208 if (mView.hasFocus()) {
2209 // i learned the hard way to not trust mFocusedView :)
2210 mFocusedView = mView.findFocus();
2211 if (!(mFocusedView instanceof ViewGroup)) {
2212 // some view has focus, let it keep it
2213 return false;
2214 } else if (((ViewGroup)mFocusedView).getDescendantFocusability() !=
2215 ViewGroup.FOCUS_AFTER_DESCENDANTS) {
2216 // some view group has focus, and doesn't prefer its children
2217 // over itself for focus, so let them keep it.
2218 return false;
2219 }
2220 }
2221
2222 // find the best view to give focus to in this brave new non-touch-mode
2223 // world
2224 final View focused = focusSearch(null, View.FOCUS_DOWN);
2225 if (focused != null) {
2226 return focused.requestFocus(View.FOCUS_DOWN);
2227 }
2228 }
2229 return false;
2230 }
2231
Jeff Brown3915bb82010-11-05 15:02:16 -07002232 private void deliverPointerEvent(MotionEvent event, boolean sendDone) {
2233 // If there is no view, then the event will not be handled.
2234 if (mView == null || !mAdded) {
2235 finishPointerEvent(event, sendDone, false);
2236 return;
2237 }
2238
2239 // Translate the pointer event for compatibility, if needed.
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002240 if (mTranslator != null) {
2241 mTranslator.translateEventInScreenToAppWindow(event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002242 }
2243
Jeff Brown3915bb82010-11-05 15:02:16 -07002244 // Enter touch mode on the down.
2245 boolean isDown = event.getAction() == MotionEvent.ACTION_DOWN;
2246 if (isDown) {
2247 ensureTouchMode(true);
2248 }
2249 if(Config.LOGV) {
2250 captureMotionLog("captureDispatchPointer", event);
2251 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002252
Jeff Brown3915bb82010-11-05 15:02:16 -07002253 // Offset the scroll position.
2254 if (mCurScrollY != 0) {
2255 event.offsetLocation(0, mCurScrollY);
2256 }
2257 if (MEASURE_LATENCY) {
2258 lt.sample("A Dispatching TouchEvents", System.nanoTime() - event.getEventTimeNano());
2259 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002260
Jeff Brown3915bb82010-11-05 15:02:16 -07002261 // Remember the touch position for possible drag-initiation.
2262 mLastTouchPoint.x = event.getRawX();
2263 mLastTouchPoint.y = event.getRawY();
2264
2265 // Dispatch touch to view hierarchy.
2266 boolean handled = mView.dispatchTouchEvent(event);
2267 if (MEASURE_LATENCY) {
2268 lt.sample("B Dispatched TouchEvents ", System.nanoTime() - event.getEventTimeNano());
2269 }
2270 if (handled) {
2271 finishPointerEvent(event, sendDone, true);
2272 return;
2273 }
2274
2275 // Apply edge slop and try again, if appropriate.
2276 final int edgeFlags = event.getEdgeFlags();
2277 if (edgeFlags != 0 && mView instanceof ViewGroup) {
2278 final int edgeSlop = mViewConfiguration.getScaledEdgeSlop();
2279 int direction = View.FOCUS_UP;
2280 int x = (int)event.getX();
2281 int y = (int)event.getY();
2282 final int[] deltas = new int[2];
2283
2284 if ((edgeFlags & MotionEvent.EDGE_TOP) != 0) {
2285 direction = View.FOCUS_DOWN;
2286 if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
2287 deltas[0] = edgeSlop;
2288 x += edgeSlop;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002289 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
Jeff Brown3915bb82010-11-05 15:02:16 -07002290 deltas[0] = -edgeSlop;
2291 x -= edgeSlop;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002292 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002293 } else if ((edgeFlags & MotionEvent.EDGE_BOTTOM) != 0) {
2294 direction = View.FOCUS_UP;
2295 if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
2296 deltas[0] = edgeSlop;
2297 x += edgeSlop;
2298 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
2299 deltas[0] = -edgeSlop;
2300 x -= edgeSlop;
2301 }
2302 } else if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
2303 direction = View.FOCUS_RIGHT;
2304 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
2305 direction = View.FOCUS_LEFT;
2306 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002307
Jeff Brown3915bb82010-11-05 15:02:16 -07002308 View nearest = FocusFinder.getInstance().findNearestTouchable(
2309 ((ViewGroup) mView), x, y, direction, deltas);
2310 if (nearest != null) {
2311 event.offsetLocation(deltas[0], deltas[1]);
2312 event.setEdgeFlags(0);
2313 if (mView.dispatchTouchEvent(event)) {
2314 finishPointerEvent(event, sendDone, true);
2315 return;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002316 }
2317 }
2318 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002319
2320 // Pointer event was unhandled.
2321 finishPointerEvent(event, sendDone, false);
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002322 }
2323
Jeff Brown3915bb82010-11-05 15:02:16 -07002324 private void finishPointerEvent(MotionEvent event, boolean sendDone, boolean handled) {
2325 event.recycle();
2326 if (sendDone) {
2327 finishInputEvent(handled);
2328 }
2329 if (LOCAL_LOGV || WATCH_POINTER) Log.i(TAG, "Done dispatching!");
2330 }
2331
2332 private void deliverTrackballEvent(MotionEvent event, boolean sendDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002333 if (DEBUG_TRACKBALL) Log.v(TAG, "Motion event:" + event);
2334
Jeff Brown3915bb82010-11-05 15:02:16 -07002335 // If there is no view, then the event will not be handled.
2336 if (mView == null || !mAdded) {
2337 finishTrackballEvent(event, sendDone, false);
2338 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002339 }
2340
Jeff Brown3915bb82010-11-05 15:02:16 -07002341 // Deliver the trackball event to the view.
2342 if (mView.dispatchTrackballEvent(event)) {
2343 // If we reach this, we delivered a trackball event to mView and
2344 // mView consumed it. Because we will not translate the trackball
2345 // event into a key event, touch mode will not exit, so we exit
2346 // touch mode here.
2347 ensureTouchMode(false);
2348
2349 finishTrackballEvent(event, sendDone, true);
2350 mLastTrackballTime = Integer.MIN_VALUE;
2351 return;
2352 }
2353
2354 // Translate the trackball event into DPAD keys and try to deliver those.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002355 final TrackballAxis x = mTrackballAxisX;
2356 final TrackballAxis y = mTrackballAxisY;
2357
2358 long curTime = SystemClock.uptimeMillis();
Jeff Brown3915bb82010-11-05 15:02:16 -07002359 if ((mLastTrackballTime + MAX_TRACKBALL_DELAY) < curTime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002360 // It has been too long since the last movement,
2361 // so restart at the beginning.
2362 x.reset(0);
2363 y.reset(0);
2364 mLastTrackballTime = curTime;
2365 }
2366
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002367 final int action = event.getAction();
Jeff Brown49ed71d2010-12-06 17:13:33 -08002368 final int metaState = event.getMetaState();
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002369 switch (action) {
2370 case MotionEvent.ACTION_DOWN:
2371 x.reset(2);
2372 y.reset(2);
2373 deliverKeyEvent(new KeyEvent(curTime, curTime,
Jeff Brown49ed71d2010-12-06 17:13:33 -08002374 KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_CENTER, 0, metaState,
2375 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
2376 InputDevice.SOURCE_KEYBOARD), false);
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002377 break;
2378 case MotionEvent.ACTION_UP:
2379 x.reset(2);
2380 y.reset(2);
2381 deliverKeyEvent(new KeyEvent(curTime, curTime,
Jeff Brown49ed71d2010-12-06 17:13:33 -08002382 KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_CENTER, 0, metaState,
2383 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
2384 InputDevice.SOURCE_KEYBOARD), false);
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002385 break;
2386 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002387
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002388 if (DEBUG_TRACKBALL) Log.v(TAG, "TB X=" + x.position + " step="
2389 + x.step + " dir=" + x.dir + " acc=" + x.acceleration
2390 + " move=" + event.getX()
2391 + " / Y=" + y.position + " step="
2392 + y.step + " dir=" + y.dir + " acc=" + y.acceleration
2393 + " move=" + event.getY());
2394 final float xOff = x.collect(event.getX(), event.getEventTime(), "X");
2395 final float yOff = y.collect(event.getY(), event.getEventTime(), "Y");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002396
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002397 // Generate DPAD events based on the trackball movement.
2398 // We pick the axis that has moved the most as the direction of
2399 // the DPAD. When we generate DPAD events for one axis, then the
2400 // other axis is reset -- we don't want to perform DPAD jumps due
2401 // to slight movements in the trackball when making major movements
2402 // along the other axis.
2403 int keycode = 0;
2404 int movement = 0;
2405 float accel = 1;
2406 if (xOff > yOff) {
2407 movement = x.generate((2/event.getXPrecision()));
2408 if (movement != 0) {
2409 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_RIGHT
2410 : KeyEvent.KEYCODE_DPAD_LEFT;
2411 accel = x.acceleration;
2412 y.reset(2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002413 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002414 } else if (yOff > 0) {
2415 movement = y.generate((2/event.getYPrecision()));
2416 if (movement != 0) {
2417 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_DOWN
2418 : KeyEvent.KEYCODE_DPAD_UP;
2419 accel = y.acceleration;
2420 x.reset(2);
2421 }
2422 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002423
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002424 if (keycode != 0) {
2425 if (movement < 0) movement = -movement;
2426 int accelMovement = (int)(movement * accel);
2427 if (DEBUG_TRACKBALL) Log.v(TAG, "Move: movement=" + movement
2428 + " accelMovement=" + accelMovement
2429 + " accel=" + accel);
2430 if (accelMovement > movement) {
2431 if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: "
2432 + keycode);
2433 movement--;
Jeff Brown49ed71d2010-12-06 17:13:33 -08002434 int repeatCount = accelMovement - movement;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002435 deliverKeyEvent(new KeyEvent(curTime, curTime,
Jeff Brown49ed71d2010-12-06 17:13:33 -08002436 KeyEvent.ACTION_MULTIPLE, keycode, repeatCount, metaState,
2437 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
2438 InputDevice.SOURCE_KEYBOARD), false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002439 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002440 while (movement > 0) {
2441 if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: "
2442 + keycode);
2443 movement--;
2444 curTime = SystemClock.uptimeMillis();
2445 deliverKeyEvent(new KeyEvent(curTime, curTime,
Jeff Brown49ed71d2010-12-06 17:13:33 -08002446 KeyEvent.ACTION_DOWN, keycode, 0, metaState,
2447 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
2448 InputDevice.SOURCE_KEYBOARD), false);
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002449 deliverKeyEvent(new KeyEvent(curTime, curTime,
Jeff Brown49ed71d2010-12-06 17:13:33 -08002450 KeyEvent.ACTION_UP, keycode, 0, metaState,
2451 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
2452 InputDevice.SOURCE_KEYBOARD), false);
2453 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002454 mLastTrackballTime = curTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002455 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002456
2457 // Unfortunately we can't tell whether the application consumed the keys, so
2458 // we always consider the trackball event handled.
2459 finishTrackballEvent(event, sendDone, true);
2460 }
2461
2462 private void finishTrackballEvent(MotionEvent event, boolean sendDone, boolean handled) {
2463 event.recycle();
2464 if (sendDone) {
2465 finishInputEvent(handled);
2466 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002467 }
2468
2469 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08002470 * Returns true if the key is used for keyboard navigation.
2471 * @param keyEvent The key event.
2472 * @return True if the key is used for keyboard navigation.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002473 */
Jeff Brown4e6319b2010-12-13 10:36:51 -08002474 private static boolean isNavigationKey(KeyEvent keyEvent) {
2475 switch (keyEvent.getKeyCode()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002476 case KeyEvent.KEYCODE_DPAD_LEFT:
2477 case KeyEvent.KEYCODE_DPAD_RIGHT:
2478 case KeyEvent.KEYCODE_DPAD_UP:
2479 case KeyEvent.KEYCODE_DPAD_DOWN:
Jeff Brown4e6319b2010-12-13 10:36:51 -08002480 case KeyEvent.KEYCODE_DPAD_CENTER:
2481 case KeyEvent.KEYCODE_PAGE_UP:
2482 case KeyEvent.KEYCODE_PAGE_DOWN:
2483 case KeyEvent.KEYCODE_MOVE_HOME:
2484 case KeyEvent.KEYCODE_MOVE_END:
2485 case KeyEvent.KEYCODE_TAB:
2486 case KeyEvent.KEYCODE_SPACE:
2487 case KeyEvent.KEYCODE_ENTER:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002488 return true;
2489 }
2490 return false;
2491 }
2492
2493 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08002494 * Returns true if the key is used for typing.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002495 * @param keyEvent The key event.
Jeff Brown4e6319b2010-12-13 10:36:51 -08002496 * @return True if the key is used for typing.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002497 */
Jeff Brown4e6319b2010-12-13 10:36:51 -08002498 private static boolean isTypingKey(KeyEvent keyEvent) {
2499 return keyEvent.getUnicodeChar() > 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002500 }
2501
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002502 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08002503 * 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 -08002504 * @param event The key event.
2505 * @return Whether this key event should be consumed (meaning the act of
2506 * leaving touch mode alone is considered the event).
2507 */
2508 private boolean checkForLeavingTouchModeAndConsume(KeyEvent event) {
Jeff Brown4e6319b2010-12-13 10:36:51 -08002509 // Only relevant in touch mode.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002510 if (!mAttachInfo.mInTouchMode) {
2511 return false;
2512 }
2513
Jeff Brown4e6319b2010-12-13 10:36:51 -08002514 // Only consider leaving touch mode on DOWN or MULTIPLE actions, never on UP.
2515 final int action = event.getAction();
2516 if (action != KeyEvent.ACTION_DOWN && action != KeyEvent.ACTION_MULTIPLE) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002517 return false;
2518 }
2519
Jeff Brown4e6319b2010-12-13 10:36:51 -08002520 // Don't leave touch mode if the IME told us not to.
2521 if ((event.getFlags() & KeyEvent.FLAG_KEEP_TOUCH_MODE) != 0) {
2522 return false;
2523 }
2524
2525 // If the key can be used for keyboard navigation then leave touch mode
2526 // and select a focused view if needed (in ensureTouchMode).
2527 // When a new focused view is selected, we consume the navigation key because
2528 // navigation doesn't make much sense unless a view already has focus so
2529 // the key's purpose is to set focus.
2530 if (isNavigationKey(event)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002531 return ensureTouchMode(false);
2532 }
Jeff Brown4e6319b2010-12-13 10:36:51 -08002533
2534 // If the key can be used for typing then leave touch mode
2535 // and select a focused view if needed (in ensureTouchMode).
2536 // Always allow the view to process the typing key.
2537 if (isTypingKey(event)) {
2538 ensureTouchMode(false);
2539 return false;
2540 }
2541
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002542 return false;
2543 }
2544
2545 /**
Romain Guy8506ab42009-06-11 17:35:47 -07002546 * log motion events
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002547 */
2548 private static void captureMotionLog(String subTag, MotionEvent ev) {
Romain Guy8506ab42009-06-11 17:35:47 -07002549 //check dynamic switch
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002550 if (ev == null ||
2551 SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_EVENT, 0) == 0) {
2552 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002553 }
Romain Guy8506ab42009-06-11 17:35:47 -07002554
2555 StringBuilder sb = new StringBuilder(subTag + ": ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002556 sb.append(ev.getDownTime()).append(',');
2557 sb.append(ev.getEventTime()).append(',');
2558 sb.append(ev.getAction()).append(',');
Romain Guy8506ab42009-06-11 17:35:47 -07002559 sb.append(ev.getX()).append(',');
2560 sb.append(ev.getY()).append(',');
2561 sb.append(ev.getPressure()).append(',');
2562 sb.append(ev.getSize()).append(',');
2563 sb.append(ev.getMetaState()).append(',');
2564 sb.append(ev.getXPrecision()).append(',');
2565 sb.append(ev.getYPrecision()).append(',');
2566 sb.append(ev.getDeviceId()).append(',');
2567 sb.append(ev.getEdgeFlags());
2568 Log.d(TAG, sb.toString());
2569 }
2570 /**
2571 * log motion events
2572 */
2573 private static void captureKeyLog(String subTag, KeyEvent ev) {
2574 //check dynamic switch
2575 if (ev == null ||
2576 SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_EVENT, 0) == 0) {
2577 return;
2578 }
2579 StringBuilder sb = new StringBuilder(subTag + ": ");
2580 sb.append(ev.getDownTime()).append(',');
2581 sb.append(ev.getEventTime()).append(',');
2582 sb.append(ev.getAction()).append(',');
2583 sb.append(ev.getKeyCode()).append(',');
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002584 sb.append(ev.getRepeatCount()).append(',');
2585 sb.append(ev.getMetaState()).append(',');
2586 sb.append(ev.getDeviceId()).append(',');
2587 sb.append(ev.getScanCode());
Romain Guy8506ab42009-06-11 17:35:47 -07002588 Log.d(TAG, sb.toString());
2589 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002590
2591 int enqueuePendingEvent(Object event, boolean sendDone) {
2592 int seq = mPendingEventSeq+1;
2593 if (seq < 0) seq = 0;
2594 mPendingEventSeq = seq;
2595 mPendingEvents.put(seq, event);
2596 return sendDone ? seq : -seq;
2597 }
2598
2599 Object retrievePendingEvent(int seq) {
2600 if (seq < 0) seq = -seq;
2601 Object event = mPendingEvents.get(seq);
2602 if (event != null) {
2603 mPendingEvents.remove(seq);
2604 }
2605 return event;
2606 }
Romain Guy8506ab42009-06-11 17:35:47 -07002607
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002608 private void deliverKeyEvent(KeyEvent event, boolean sendDone) {
Jeff Brown3915bb82010-11-05 15:02:16 -07002609 // If there is no view, then the event will not be handled.
2610 if (mView == null || !mAdded) {
2611 finishKeyEvent(event, sendDone, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002612 return;
2613 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002614
2615 if (LOCAL_LOGV) Log.v(TAG, "Dispatching key " + event + " to " + mView);
2616
2617 // Perform predispatching before the IME.
2618 if (mView.dispatchKeyEventPreIme(event)) {
2619 finishKeyEvent(event, sendDone, true);
2620 return;
2621 }
2622
2623 // Dispatch to the IME before propagating down the view hierarchy.
2624 // The IME will eventually call back into handleFinishedEvent.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002625 if (mLastWasImTarget) {
2626 InputMethodManager imm = InputMethodManager.peekInstance();
Jeff Brown3915bb82010-11-05 15:02:16 -07002627 if (imm != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002628 int seq = enqueuePendingEvent(event, sendDone);
2629 if (DEBUG_IMF) Log.v(TAG, "Sending key event to IME: seq="
2630 + seq + " event=" + event);
Jeff Brown3915bb82010-11-05 15:02:16 -07002631 imm.dispatchKeyEvent(mView.getContext(), seq, event, mInputMethodCallback);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002632 return;
2633 }
2634 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002635
2636 // Not dispatching to IME, continue with post IME actions.
2637 deliverKeyEventPostIme(event, sendDone);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002638 }
2639
Jeff Brown3915bb82010-11-05 15:02:16 -07002640 private void handleFinishedEvent(int seq, boolean handled) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002641 final KeyEvent event = (KeyEvent)retrievePendingEvent(seq);
2642 if (DEBUG_IMF) Log.v(TAG, "IME finished event: seq=" + seq
2643 + " handled=" + handled + " event=" + event);
2644 if (event != null) {
2645 final boolean sendDone = seq >= 0;
Jeff Brown3915bb82010-11-05 15:02:16 -07002646 if (handled) {
2647 finishKeyEvent(event, sendDone, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002648 } else {
Jeff Brown3915bb82010-11-05 15:02:16 -07002649 deliverKeyEventPostIme(event, sendDone);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002650 }
2651 }
2652 }
Romain Guy8506ab42009-06-11 17:35:47 -07002653
Jeff Brown3915bb82010-11-05 15:02:16 -07002654 private void deliverKeyEventPostIme(KeyEvent event, boolean sendDone) {
2655 // If the view went away, then the event will not be handled.
2656 if (mView == null || !mAdded) {
2657 finishKeyEvent(event, sendDone, false);
2658 return;
2659 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002660
Jeff Brown3915bb82010-11-05 15:02:16 -07002661 // If the key's purpose is to exit touch mode then we consume it and consider it handled.
2662 if (checkForLeavingTouchModeAndConsume(event)) {
2663 finishKeyEvent(event, sendDone, true);
2664 return;
2665 }
Romain Guy8506ab42009-06-11 17:35:47 -07002666
Jeff Brown3915bb82010-11-05 15:02:16 -07002667 if (Config.LOGV) {
2668 captureKeyLog("captureDispatchKeyEvent", event);
2669 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002670
Jeff Brown90655042010-12-02 13:50:46 -08002671 // Make sure the fallback event policy sees all keys that will be delivered to the
2672 // view hierarchy.
2673 mFallbackEventHandler.preDispatchKeyEvent(event);
2674
Jeff Brown3915bb82010-11-05 15:02:16 -07002675 // Deliver the key to the view hierarchy.
2676 if (mView.dispatchKeyEvent(event)) {
2677 finishKeyEvent(event, sendDone, true);
2678 return;
2679 }
Joe Onorato86f67862010-11-05 18:57:34 -07002680
Jeff Brownc1df9072010-12-21 16:38:50 -08002681 // If the Control modifier is held, try to interpret the key as a shortcut.
2682 if (event.getAction() == KeyEvent.ACTION_UP
2683 && event.isCtrlPressed()
2684 && !KeyEvent.isModifierKey(event.getKeyCode())) {
2685 if (mView.dispatchKeyShortcutEvent(event)) {
2686 finishKeyEvent(event, sendDone, true);
2687 return;
2688 }
2689 }
2690
Jeff Brown3915bb82010-11-05 15:02:16 -07002691 // Apply the fallback event policy.
2692 if (mFallbackEventHandler.dispatchKeyEvent(event)) {
2693 finishKeyEvent(event, sendDone, true);
2694 return;
2695 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002696
Jeff Brown3915bb82010-11-05 15:02:16 -07002697 // Handle automatic focus changes.
2698 if (event.getAction() == KeyEvent.ACTION_DOWN) {
2699 int direction = 0;
2700 switch (event.getKeyCode()) {
2701 case KeyEvent.KEYCODE_DPAD_LEFT:
Jeff Brown4e6319b2010-12-13 10:36:51 -08002702 if (event.hasNoModifiers()) {
2703 direction = View.FOCUS_LEFT;
2704 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002705 break;
2706 case KeyEvent.KEYCODE_DPAD_RIGHT:
Jeff Brown4e6319b2010-12-13 10:36:51 -08002707 if (event.hasNoModifiers()) {
2708 direction = View.FOCUS_RIGHT;
2709 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002710 break;
2711 case KeyEvent.KEYCODE_DPAD_UP:
Jeff Brown4e6319b2010-12-13 10:36:51 -08002712 if (event.hasNoModifiers()) {
2713 direction = View.FOCUS_UP;
2714 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002715 break;
2716 case KeyEvent.KEYCODE_DPAD_DOWN:
Jeff Brown4e6319b2010-12-13 10:36:51 -08002717 if (event.hasNoModifiers()) {
2718 direction = View.FOCUS_DOWN;
2719 }
2720 break;
2721 case KeyEvent.KEYCODE_TAB:
2722 if (event.hasNoModifiers()) {
2723 direction = View.FOCUS_FORWARD;
2724 } else if (event.hasModifiers(KeyEvent.META_SHIFT_ON)) {
2725 direction = View.FOCUS_BACKWARD;
2726 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002727 break;
2728 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002729
Jeff Brown3915bb82010-11-05 15:02:16 -07002730 if (direction != 0) {
2731 View focused = mView != null ? mView.findFocus() : null;
2732 if (focused != null) {
2733 View v = focused.focusSearch(direction);
2734 if (v != null && v != focused) {
2735 // do the math the get the interesting rect
2736 // of previous focused into the coord system of
2737 // newly focused view
2738 focused.getFocusedRect(mTempRect);
2739 if (mView instanceof ViewGroup) {
2740 ((ViewGroup) mView).offsetDescendantRectToMyCoords(
2741 focused, mTempRect);
2742 ((ViewGroup) mView).offsetRectIntoDescendantCoords(
2743 v, mTempRect);
2744 }
2745 if (v.requestFocus(direction, mTempRect)) {
2746 playSoundEffect(
2747 SoundEffectConstants.getContantForFocusDirection(direction));
2748 finishKeyEvent(event, sendDone, true);
2749 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002750 }
2751 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002752
2753 // Give the focused view a last chance to handle the dpad key.
2754 if (mView.dispatchUnhandledMove(focused, direction)) {
2755 finishKeyEvent(event, sendDone, true);
2756 return;
2757 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002758 }
2759 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002760 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002761
Jeff Brown3915bb82010-11-05 15:02:16 -07002762 // Key was unhandled.
2763 finishKeyEvent(event, sendDone, false);
2764 }
2765
2766 private void finishKeyEvent(KeyEvent event, boolean sendDone, boolean handled) {
2767 if (sendDone) {
2768 finishInputEvent(handled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002769 }
2770 }
2771
Christopher Tatea53146c2010-09-07 11:57:52 -07002772 /* drag/drop */
Christopher Tate407b4e92010-11-30 17:14:08 -08002773 void setLocalDragState(Object obj) {
2774 mLocalDragState = obj;
2775 }
2776
Christopher Tatea53146c2010-09-07 11:57:52 -07002777 private void handleDragEvent(DragEvent event) {
2778 // From the root, only drag start/end/location are dispatched. entered/exited
2779 // are determined and dispatched by the viewgroup hierarchy, who then report
2780 // that back here for ultimate reporting back to the framework.
2781 if (mView != null && mAdded) {
2782 final int what = event.mAction;
2783
2784 if (what == DragEvent.ACTION_DRAG_EXITED) {
2785 // A direct EXITED event means that the window manager knows we've just crossed
2786 // a window boundary, so the current drag target within this one must have
2787 // just been exited. Send it the usual notifications and then we're done
2788 // for now.
Chris Tate9d1ab882010-11-02 15:55:39 -07002789 mView.dispatchDragEvent(event);
Christopher Tatea53146c2010-09-07 11:57:52 -07002790 } else {
2791 // Cache the drag description when the operation starts, then fill it in
2792 // on subsequent calls as a convenience
2793 if (what == DragEvent.ACTION_DRAG_STARTED) {
Chris Tate9d1ab882010-11-02 15:55:39 -07002794 mCurrentDragView = null; // Start the current-recipient tracking
Christopher Tatea53146c2010-09-07 11:57:52 -07002795 mDragDescription = event.mClipDescription;
2796 } else {
2797 event.mClipDescription = mDragDescription;
2798 }
2799
2800 // For events with a [screen] location, translate into window coordinates
2801 if ((what == DragEvent.ACTION_DRAG_LOCATION) || (what == DragEvent.ACTION_DROP)) {
2802 mDragPoint.set(event.mX, event.mY);
2803 if (mTranslator != null) {
2804 mTranslator.translatePointInScreenToAppWindow(mDragPoint);
2805 }
2806
2807 if (mCurScrollY != 0) {
2808 mDragPoint.offset(0, mCurScrollY);
2809 }
2810
2811 event.mX = mDragPoint.x;
2812 event.mY = mDragPoint.y;
2813 }
2814
2815 // Remember who the current drag target is pre-dispatch
2816 final View prevDragView = mCurrentDragView;
2817
2818 // Now dispatch the drag/drop event
Chris Tated4533f12010-10-19 15:15:08 -07002819 boolean result = mView.dispatchDragEvent(event);
Christopher Tatea53146c2010-09-07 11:57:52 -07002820
2821 // If we changed apparent drag target, tell the OS about it
2822 if (prevDragView != mCurrentDragView) {
2823 try {
2824 if (prevDragView != null) {
2825 sWindowSession.dragRecipientExited(mWindow);
2826 }
2827 if (mCurrentDragView != null) {
2828 sWindowSession.dragRecipientEntered(mWindow);
2829 }
2830 } catch (RemoteException e) {
2831 Slog.e(TAG, "Unable to note drag target change");
2832 }
Christopher Tatea53146c2010-09-07 11:57:52 -07002833 }
Chris Tated4533f12010-10-19 15:15:08 -07002834
Christopher Tate407b4e92010-11-30 17:14:08 -08002835 // Report the drop result when we're done
Chris Tated4533f12010-10-19 15:15:08 -07002836 if (what == DragEvent.ACTION_DROP) {
Christopher Tate1fc014f2011-01-19 12:56:26 -08002837 mDragDescription = null;
Chris Tated4533f12010-10-19 15:15:08 -07002838 try {
2839 Log.i(TAG, "Reporting drop result: " + result);
2840 sWindowSession.reportDropResult(mWindow, result);
2841 } catch (RemoteException e) {
2842 Log.e(TAG, "Unable to report drop result");
2843 }
2844 }
Christopher Tate407b4e92010-11-30 17:14:08 -08002845
2846 // When the drag operation ends, release any local state object
2847 // that may have been in use
2848 if (what == DragEvent.ACTION_DRAG_ENDED) {
2849 setLocalDragState(null);
2850 }
Christopher Tatea53146c2010-09-07 11:57:52 -07002851 }
2852 }
2853 event.recycle();
2854 }
2855
Joe Onorato664644d2011-01-23 17:53:23 -08002856 public void handleDispatchSystemUiVisibilityChanged(int visibility) {
2857 if (mView == null) return;
2858 mView.dispatchSystemUiVisibilityChanged(visibility);
2859 }
2860
Christopher Tate2c095f32010-10-04 14:13:40 -07002861 public void getLastTouchPoint(Point outLocation) {
2862 outLocation.x = (int) mLastTouchPoint.x;
2863 outLocation.y = (int) mLastTouchPoint.y;
2864 }
2865
Chris Tate9d1ab882010-11-02 15:55:39 -07002866 public void setDragFocus(View newDragTarget) {
Christopher Tatea53146c2010-09-07 11:57:52 -07002867 if (mCurrentDragView != newDragTarget) {
Chris Tate048691c2010-10-12 17:39:18 -07002868 mCurrentDragView = newDragTarget;
Christopher Tatea53146c2010-09-07 11:57:52 -07002869 }
Christopher Tatea53146c2010-09-07 11:57:52 -07002870 }
2871
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002872 private AudioManager getAudioManager() {
2873 if (mView == null) {
2874 throw new IllegalStateException("getAudioManager called when there is no mView");
2875 }
2876 if (mAudioManager == null) {
2877 mAudioManager = (AudioManager) mView.getContext().getSystemService(Context.AUDIO_SERVICE);
2878 }
2879 return mAudioManager;
2880 }
2881
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002882 private int relayoutWindow(WindowManager.LayoutParams params, int viewVisibility,
2883 boolean insetsPending) throws RemoteException {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002884
2885 float appScale = mAttachInfo.mApplicationScale;
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002886 boolean restore = false;
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002887 if (params != null && mTranslator != null) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07002888 restore = true;
2889 params.backup();
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002890 mTranslator.translateWindowLayout(params);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002891 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002892 if (params != null) {
2893 if (DBG) Log.d(TAG, "WindowLayout in layoutWindow:" + params);
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002894 }
Dianne Hackborn694f79b2010-03-17 19:44:59 -07002895 mPendingConfiguration.seq = 0;
Dianne Hackbornf123e492010-09-24 11:16:23 -07002896 //Log.d(TAG, ">>>>>> CALLING relayout");
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002897 int relayoutResult = sWindowSession.relayout(
2898 mWindow, params,
Dianne Hackborn189ee182010-12-02 21:48:53 -08002899 (int) (mView.getMeasuredWidth() * appScale + 0.5f),
2900 (int) (mView.getMeasuredHeight() * appScale + 0.5f),
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002901 viewVisibility, insetsPending, mWinFrame,
Dianne Hackborn694f79b2010-03-17 19:44:59 -07002902 mPendingContentInsets, mPendingVisibleInsets,
2903 mPendingConfiguration, mSurface);
Dianne Hackbornf123e492010-09-24 11:16:23 -07002904 //Log.d(TAG, "<<<<<< BACK FROM relayout");
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002905 if (restore) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07002906 params.restore();
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002907 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002908
2909 if (mTranslator != null) {
2910 mTranslator.translateRectInScreenToAppWinFrame(mWinFrame);
2911 mTranslator.translateRectInScreenToAppWindow(mPendingContentInsets);
2912 mTranslator.translateRectInScreenToAppWindow(mPendingVisibleInsets);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002913 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002914 return relayoutResult;
2915 }
Romain Guy8506ab42009-06-11 17:35:47 -07002916
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002917 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002918 * {@inheritDoc}
2919 */
2920 public void playSoundEffect(int effectId) {
2921 checkThread();
2922
Jean-Michel Trivi13b18fd2010-05-05 09:18:15 -07002923 try {
2924 final AudioManager audioManager = getAudioManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002925
Jean-Michel Trivi13b18fd2010-05-05 09:18:15 -07002926 switch (effectId) {
2927 case SoundEffectConstants.CLICK:
2928 audioManager.playSoundEffect(AudioManager.FX_KEY_CLICK);
2929 return;
2930 case SoundEffectConstants.NAVIGATION_DOWN:
2931 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_DOWN);
2932 return;
2933 case SoundEffectConstants.NAVIGATION_LEFT:
2934 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_LEFT);
2935 return;
2936 case SoundEffectConstants.NAVIGATION_RIGHT:
2937 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_RIGHT);
2938 return;
2939 case SoundEffectConstants.NAVIGATION_UP:
2940 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_UP);
2941 return;
2942 default:
2943 throw new IllegalArgumentException("unknown effect id " + effectId +
2944 " not defined in " + SoundEffectConstants.class.getCanonicalName());
2945 }
2946 } catch (IllegalStateException e) {
2947 // Exception thrown by getAudioManager() when mView is null
2948 Log.e(TAG, "FATAL EXCEPTION when attempting to play sound effect: " + e);
2949 e.printStackTrace();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002950 }
2951 }
2952
2953 /**
2954 * {@inheritDoc}
2955 */
2956 public boolean performHapticFeedback(int effectId, boolean always) {
2957 try {
2958 return sWindowSession.performHapticFeedback(mWindow, effectId, always);
2959 } catch (RemoteException e) {
2960 return false;
2961 }
2962 }
2963
2964 /**
2965 * {@inheritDoc}
2966 */
2967 public View focusSearch(View focused, int direction) {
2968 checkThread();
2969 if (!(mView instanceof ViewGroup)) {
2970 return null;
2971 }
2972 return FocusFinder.getInstance().findNextFocus((ViewGroup) mView, focused, direction);
2973 }
2974
2975 public void debug() {
2976 mView.debug();
2977 }
2978
2979 public void die(boolean immediate) {
Dianne Hackborn94d69142009-09-28 22:14:42 -07002980 if (immediate) {
2981 doDie();
2982 } else {
2983 sendEmptyMessage(DIE);
2984 }
2985 }
2986
2987 void doDie() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002988 checkThread();
Jeff Brownb75fa302010-07-15 23:47:29 -07002989 if (LOCAL_LOGV) Log.v(TAG, "DIE in " + this + " of " + mSurface);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002990 synchronized (this) {
2991 if (mAdded && !mFirst) {
Romain Guy29d89972010-09-22 16:10:57 -07002992 destroyHardwareRenderer();
2993
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002994 int viewVisibility = mView.getVisibility();
2995 boolean viewVisibilityChanged = mViewVisibility != viewVisibility;
2996 if (mWindowAttributesChanged || viewVisibilityChanged) {
2997 // If layout params have been changed, first give them
2998 // to the window manager to make sure it has the correct
2999 // animation info.
3000 try {
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07003001 if ((relayoutWindow(mWindowAttributes, viewVisibility, false)
3002 & WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003003 sWindowSession.finishDrawing(mWindow);
3004 }
3005 } catch (RemoteException e) {
3006 }
3007 }
3008
Dianne Hackborn0586a1b2009-09-06 21:08:27 -07003009 mSurface.release();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003010 }
3011 if (mAdded) {
3012 mAdded = false;
Dianne Hackborn94d69142009-09-28 22:14:42 -07003013 dispatchDetachedFromWindow();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003014 }
3015 }
3016 }
3017
Romain Guy29d89972010-09-22 16:10:57 -07003018 private void destroyHardwareRenderer() {
Romain Guyb051e892010-09-28 19:09:36 -07003019 if (mAttachInfo.mHardwareRenderer != null) {
3020 mAttachInfo.mHardwareRenderer.destroy(true);
3021 mAttachInfo.mHardwareRenderer = null;
Romain Guy29d89972010-09-22 16:10:57 -07003022 mAttachInfo.mHardwareAccelerated = false;
3023 }
3024 }
3025
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003026 public void dispatchFinishedEvent(int seq, boolean handled) {
3027 Message msg = obtainMessage(FINISHED_EVENT);
3028 msg.arg1 = seq;
3029 msg.arg2 = handled ? 1 : 0;
3030 sendMessage(msg);
3031 }
Mitsuru Oshima3d914922009-05-13 22:29:15 -07003032
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003033 public void dispatchResized(int w, int h, Rect coveredInsets,
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003034 Rect visibleInsets, boolean reportDraw, Configuration newConfig) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003035 if (DEBUG_LAYOUT) Log.v(TAG, "Resizing " + this + ": w=" + w
3036 + " h=" + h + " coveredInsets=" + coveredInsets.toShortString()
3037 + " visibleInsets=" + visibleInsets.toShortString()
3038 + " reportDraw=" + reportDraw);
3039 Message msg = obtainMessage(reportDraw ? RESIZED_REPORT :RESIZED);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07003040 if (mTranslator != null) {
3041 mTranslator.translateRectInScreenToAppWindow(coveredInsets);
3042 mTranslator.translateRectInScreenToAppWindow(visibleInsets);
3043 w *= mTranslator.applicationInvertedScale;
3044 h *= mTranslator.applicationInvertedScale;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07003045 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07003046 msg.arg1 = w;
3047 msg.arg2 = h;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003048 ResizedInfo ri = new ResizedInfo();
3049 ri.coveredInsets = new Rect(coveredInsets);
3050 ri.visibleInsets = new Rect(visibleInsets);
3051 ri.newConfig = newConfig;
3052 msg.obj = ri;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003053 sendMessage(msg);
3054 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07003055
Jeff Brown3915bb82010-11-05 15:02:16 -07003056 private InputQueue.FinishedCallback mFinishedCallback;
Jeff Brown46b9ac02010-04-22 18:58:52 -07003057
3058 private final InputHandler mInputHandler = new InputHandler() {
Jeff Brown3915bb82010-11-05 15:02:16 -07003059 public void handleKey(KeyEvent event, InputQueue.FinishedCallback finishedCallback) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07003060 startInputEvent(finishedCallback);
Jeff Brown92ff1dd2010-08-11 16:16:06 -07003061 dispatchKey(event, true);
Jeff Brown46b9ac02010-04-22 18:58:52 -07003062 }
3063
Jeff Brown3915bb82010-11-05 15:02:16 -07003064 public void handleMotion(MotionEvent event, InputQueue.FinishedCallback finishedCallback) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07003065 startInputEvent(finishedCallback);
3066 dispatchMotion(event, true);
Jeff Brown46b9ac02010-04-22 18:58:52 -07003067 }
3068 };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003069
3070 public void dispatchKey(KeyEvent event) {
Jeff Brown92ff1dd2010-08-11 16:16:06 -07003071 dispatchKey(event, false);
3072 }
3073
3074 private void dispatchKey(KeyEvent event, boolean sendDone) {
3075 //noinspection ConstantConditions
3076 if (false && event.getAction() == KeyEvent.ACTION_DOWN) {
3077 if (event.getKeyCode() == KeyEvent.KEYCODE_CAMERA) {
Romain Guy812ccbe2010-06-01 14:07:24 -07003078 if (DBG) Log.d("keydisp", "===================================================");
3079 if (DBG) Log.d("keydisp", "Focused view Hierarchy is:");
3080
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003081 debug();
3082
Romain Guy812ccbe2010-06-01 14:07:24 -07003083 if (DBG) Log.d("keydisp", "===================================================");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003084 }
3085 }
3086
3087 Message msg = obtainMessage(DISPATCH_KEY);
3088 msg.obj = event;
Jeff Brown92ff1dd2010-08-11 16:16:06 -07003089 msg.arg1 = sendDone ? 1 : 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003090
3091 if (LOCAL_LOGV) Log.v(
Jeff Brownc5ed5912010-07-14 18:48:53 -07003092 TAG, "sending key " + event + " to " + mView);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003093
3094 sendMessageAtTime(msg, event.getEventTime());
3095 }
Jeff Brownc5ed5912010-07-14 18:48:53 -07003096
3097 public void dispatchMotion(MotionEvent event) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07003098 dispatchMotion(event, false);
3099 }
3100
3101 private void dispatchMotion(MotionEvent event, boolean sendDone) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07003102 int source = event.getSource();
3103 if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07003104 dispatchPointer(event, sendDone);
Jeff Brownc5ed5912010-07-14 18:48:53 -07003105 } else if ((source & InputDevice.SOURCE_CLASS_TRACKBALL) != 0) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07003106 dispatchTrackball(event, sendDone);
Jeff Brownc5ed5912010-07-14 18:48:53 -07003107 } else {
3108 // TODO
3109 Log.v(TAG, "Dropping unsupported motion event (unimplemented): " + event);
Jeff Brown93ed4e32010-09-23 13:51:48 -07003110 if (sendDone) {
Jeff Brown3915bb82010-11-05 15:02:16 -07003111 finishInputEvent(false);
Jeff Brown93ed4e32010-09-23 13:51:48 -07003112 }
Jeff Brownc5ed5912010-07-14 18:48:53 -07003113 }
3114 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003115
Jeff Brown00fa7bd2010-07-02 15:37:36 -07003116 public void dispatchPointer(MotionEvent event) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07003117 dispatchPointer(event, false);
3118 }
3119
3120 private void dispatchPointer(MotionEvent event, boolean sendDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003121 Message msg = obtainMessage(DISPATCH_POINTER);
3122 msg.obj = event;
Jeff Brown93ed4e32010-09-23 13:51:48 -07003123 msg.arg1 = sendDone ? 1 : 0;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07003124 sendMessageAtTime(msg, event.getEventTime());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003125 }
3126
Jeff Brown00fa7bd2010-07-02 15:37:36 -07003127 public void dispatchTrackball(MotionEvent event) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07003128 dispatchTrackball(event, false);
3129 }
3130
3131 private void dispatchTrackball(MotionEvent event, boolean sendDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003132 Message msg = obtainMessage(DISPATCH_TRACKBALL);
3133 msg.obj = event;
Jeff Brown93ed4e32010-09-23 13:51:48 -07003134 msg.arg1 = sendDone ? 1 : 0;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07003135 sendMessageAtTime(msg, event.getEventTime());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003136 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07003137
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003138 public void dispatchAppVisibility(boolean visible) {
3139 Message msg = obtainMessage(DISPATCH_APP_VISIBILITY);
3140 msg.arg1 = visible ? 1 : 0;
3141 sendMessage(msg);
3142 }
3143
3144 public void dispatchGetNewSurface() {
3145 Message msg = obtainMessage(DISPATCH_GET_NEW_SURFACE);
3146 sendMessage(msg);
3147 }
3148
3149 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
3150 Message msg = Message.obtain();
3151 msg.what = WINDOW_FOCUS_CHANGED;
3152 msg.arg1 = hasFocus ? 1 : 0;
3153 msg.arg2 = inTouchMode ? 1 : 0;
3154 sendMessage(msg);
3155 }
3156
Dianne Hackbornffa42482009-09-23 22:20:11 -07003157 public void dispatchCloseSystemDialogs(String reason) {
3158 Message msg = Message.obtain();
3159 msg.what = CLOSE_SYSTEM_DIALOGS;
3160 msg.obj = reason;
3161 sendMessage(msg);
3162 }
Christopher Tatea53146c2010-09-07 11:57:52 -07003163
3164 public void dispatchDragEvent(DragEvent event) {
Chris Tate91e9bb32010-10-12 12:58:43 -07003165 final int what;
3166 if (event.getAction() == DragEvent.ACTION_DRAG_LOCATION) {
3167 what = DISPATCH_DRAG_LOCATION_EVENT;
3168 removeMessages(what);
3169 } else {
3170 what = DISPATCH_DRAG_EVENT;
3171 }
3172 Message msg = obtainMessage(what, event);
Christopher Tatea53146c2010-09-07 11:57:52 -07003173 sendMessage(msg);
3174 }
3175
Joe Onorato664644d2011-01-23 17:53:23 -08003176 public void dispatchSystemUiVisibilityChanged(int visibility) {
3177 sendMessage(obtainMessage(DISPATCH_SYSTEM_UI_VISIBILITY, visibility, 0));
3178 }
3179
svetoslavganov75986cf2009-05-14 22:28:01 -07003180 /**
3181 * The window is getting focus so if there is anything focused/selected
3182 * send an {@link AccessibilityEvent} to announce that.
3183 */
3184 private void sendAccessibilityEvents() {
3185 if (!AccessibilityManager.getInstance(mView.getContext()).isEnabled()) {
3186 return;
3187 }
3188 mView.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
3189 View focusedView = mView.findFocus();
3190 if (focusedView != null && focusedView != mView) {
3191 focusedView.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
3192 }
3193 }
3194
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003195 public boolean showContextMenuForChild(View originalView) {
3196 return false;
3197 }
3198
Adam Powell6e346362010-07-23 10:18:23 -07003199 public ActionMode startActionModeForChild(View originalView, ActionMode.Callback callback) {
3200 return null;
3201 }
3202
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003203 public void createContextMenu(ContextMenu menu) {
3204 }
3205
3206 public void childDrawableStateChanged(View child) {
3207 }
3208
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003209 void checkThread() {
3210 if (mThread != Thread.currentThread()) {
3211 throw new CalledFromWrongThreadException(
3212 "Only the original thread that created a view hierarchy can touch its views.");
3213 }
3214 }
3215
3216 public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
3217 // ViewRoot never intercepts touch event, so this can be a no-op
3218 }
3219
3220 public boolean requestChildRectangleOnScreen(View child, Rect rectangle,
3221 boolean immediate) {
3222 return scrollToRectOrFocus(rectangle, immediate);
3223 }
Romain Guy8506ab42009-06-11 17:35:47 -07003224
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07003225 class TakenSurfaceHolder extends BaseSurfaceHolder {
3226 @Override
3227 public boolean onAllowLockCanvas() {
3228 return mDrawingAllowed;
3229 }
3230
3231 @Override
3232 public void onRelayoutContainer() {
3233 // Not currently interesting -- from changing between fixed and layout size.
3234 }
3235
3236 public void setFormat(int format) {
3237 ((RootViewSurfaceTaker)mView).setSurfaceFormat(format);
3238 }
3239
3240 public void setType(int type) {
3241 ((RootViewSurfaceTaker)mView).setSurfaceType(type);
3242 }
3243
3244 @Override
3245 public void onUpdateSurface() {
3246 // We take care of format and type changes on our own.
3247 throw new IllegalStateException("Shouldn't be here");
3248 }
3249
3250 public boolean isCreating() {
3251 return mIsCreating;
3252 }
3253
3254 @Override
3255 public void setFixedSize(int width, int height) {
3256 throw new UnsupportedOperationException(
3257 "Currently only support sizing from layout");
3258 }
3259
3260 public void setKeepScreenOn(boolean screenOn) {
3261 ((RootViewSurfaceTaker)mView).setSurfaceKeepScreenOn(screenOn);
3262 }
3263 }
3264
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003265 static class InputMethodCallback extends IInputMethodCallback.Stub {
3266 private WeakReference<ViewRoot> mViewRoot;
3267
3268 public InputMethodCallback(ViewRoot viewRoot) {
3269 mViewRoot = new WeakReference<ViewRoot>(viewRoot);
3270 }
Romain Guy8506ab42009-06-11 17:35:47 -07003271
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003272 public void finishedEvent(int seq, boolean handled) {
3273 final ViewRoot viewRoot = mViewRoot.get();
3274 if (viewRoot != null) {
3275 viewRoot.dispatchFinishedEvent(seq, handled);
3276 }
3277 }
3278
3279 public void sessionCreated(IInputMethodSession session) throws RemoteException {
3280 // Stub -- not for use in the client.
3281 }
3282 }
Romain Guy8506ab42009-06-11 17:35:47 -07003283
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003284 static class W extends IWindow.Stub {
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07003285 private final WeakReference<ViewRoot> mViewRoot;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003286
Romain Guyfb8b7632010-08-23 21:05:08 -07003287 W(ViewRoot viewRoot) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003288 mViewRoot = new WeakReference<ViewRoot>(viewRoot);
3289 }
3290
Romain Guyfb8b7632010-08-23 21:05:08 -07003291 public void resized(int w, int h, Rect coveredInsets, Rect visibleInsets,
3292 boolean reportDraw, Configuration newConfig) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003293 final ViewRoot viewRoot = mViewRoot.get();
3294 if (viewRoot != null) {
Romain Guyfb8b7632010-08-23 21:05:08 -07003295 viewRoot.dispatchResized(w, h, coveredInsets, visibleInsets, reportDraw, newConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003296 }
3297 }
3298
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003299 public void dispatchAppVisibility(boolean visible) {
3300 final ViewRoot viewRoot = mViewRoot.get();
3301 if (viewRoot != null) {
3302 viewRoot.dispatchAppVisibility(visible);
3303 }
3304 }
3305
3306 public void dispatchGetNewSurface() {
3307 final ViewRoot viewRoot = mViewRoot.get();
3308 if (viewRoot != null) {
3309 viewRoot.dispatchGetNewSurface();
3310 }
3311 }
3312
3313 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
3314 final ViewRoot viewRoot = mViewRoot.get();
3315 if (viewRoot != null) {
3316 viewRoot.windowFocusChanged(hasFocus, inTouchMode);
3317 }
3318 }
3319
3320 private static int checkCallingPermission(String permission) {
3321 if (!Process.supportsProcesses()) {
3322 return PackageManager.PERMISSION_GRANTED;
3323 }
3324
3325 try {
3326 return ActivityManagerNative.getDefault().checkPermission(
3327 permission, Binder.getCallingPid(), Binder.getCallingUid());
3328 } catch (RemoteException e) {
3329 return PackageManager.PERMISSION_DENIED;
3330 }
3331 }
3332
3333 public void executeCommand(String command, String parameters, ParcelFileDescriptor out) {
3334 final ViewRoot viewRoot = mViewRoot.get();
3335 if (viewRoot != null) {
3336 final View view = viewRoot.mView;
3337 if (view != null) {
3338 if (checkCallingPermission(Manifest.permission.DUMP) !=
3339 PackageManager.PERMISSION_GRANTED) {
3340 throw new SecurityException("Insufficient permissions to invoke"
3341 + " executeCommand() from pid=" + Binder.getCallingPid()
3342 + ", uid=" + Binder.getCallingUid());
3343 }
3344
3345 OutputStream clientStream = null;
3346 try {
3347 clientStream = new ParcelFileDescriptor.AutoCloseOutputStream(out);
3348 ViewDebug.dispatchCommand(view, command, parameters, clientStream);
3349 } catch (IOException e) {
3350 e.printStackTrace();
3351 } finally {
3352 if (clientStream != null) {
3353 try {
3354 clientStream.close();
3355 } catch (IOException e) {
3356 e.printStackTrace();
3357 }
3358 }
3359 }
3360 }
3361 }
3362 }
Dianne Hackborn72c82ab2009-08-11 21:13:54 -07003363
Dianne Hackbornffa42482009-09-23 22:20:11 -07003364 public void closeSystemDialogs(String reason) {
3365 final ViewRoot viewRoot = mViewRoot.get();
3366 if (viewRoot != null) {
3367 viewRoot.dispatchCloseSystemDialogs(reason);
3368 }
3369 }
3370
Marco Nelissenbf6956b2009-11-09 15:21:13 -08003371 public void dispatchWallpaperOffsets(float x, float y, float xStep, float yStep,
3372 boolean sync) {
Dianne Hackborn19382ac2009-09-11 21:13:37 -07003373 if (sync) {
3374 try {
3375 sWindowSession.wallpaperOffsetsComplete(asBinder());
3376 } catch (RemoteException e) {
3377 }
3378 }
Dianne Hackborn72c82ab2009-08-11 21:13:54 -07003379 }
Dianne Hackborn75804932009-10-20 20:15:20 -07003380
3381 public void dispatchWallpaperCommand(String action, int x, int y,
3382 int z, Bundle extras, boolean sync) {
3383 if (sync) {
3384 try {
3385 sWindowSession.wallpaperCommandComplete(asBinder(), null);
3386 } catch (RemoteException e) {
3387 }
3388 }
3389 }
Christopher Tatea53146c2010-09-07 11:57:52 -07003390
3391 /* Drag/drop */
3392 public void dispatchDragEvent(DragEvent event) {
3393 final ViewRoot viewRoot = mViewRoot.get();
3394 if (viewRoot != null) {
3395 viewRoot.dispatchDragEvent(event);
3396 }
3397 }
Joe Onorato664644d2011-01-23 17:53:23 -08003398
3399 @Override
3400 public void dispatchSystemUiVisibilityChanged(int visibility) {
3401 final ViewRoot viewRoot = mViewRoot.get();
3402 if (viewRoot != null) {
3403 viewRoot.dispatchSystemUiVisibilityChanged(visibility);
3404 }
3405 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003406 }
3407
3408 /**
3409 * Maintains state information for a single trackball axis, generating
3410 * discrete (DPAD) movements based on raw trackball motion.
3411 */
3412 static final class TrackballAxis {
3413 /**
3414 * The maximum amount of acceleration we will apply.
3415 */
3416 static final float MAX_ACCELERATION = 20;
Romain Guy8506ab42009-06-11 17:35:47 -07003417
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003418 /**
3419 * The maximum amount of time (in milliseconds) between events in order
3420 * for us to consider the user to be doing fast trackball movements,
3421 * and thus apply an acceleration.
3422 */
3423 static final long FAST_MOVE_TIME = 150;
Romain Guy8506ab42009-06-11 17:35:47 -07003424
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003425 /**
3426 * Scaling factor to the time (in milliseconds) between events to how
3427 * much to multiple/divide the current acceleration. When movement
3428 * is < FAST_MOVE_TIME this multiplies the acceleration; when >
3429 * FAST_MOVE_TIME it divides it.
3430 */
3431 static final float ACCEL_MOVE_SCALING_FACTOR = (1.0f/40);
Romain Guy8506ab42009-06-11 17:35:47 -07003432
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003433 float position;
3434 float absPosition;
3435 float acceleration = 1;
3436 long lastMoveTime = 0;
3437 int step;
3438 int dir;
3439 int nonAccelMovement;
3440
3441 void reset(int _step) {
3442 position = 0;
3443 acceleration = 1;
3444 lastMoveTime = 0;
3445 step = _step;
3446 dir = 0;
3447 }
3448
3449 /**
3450 * Add trackball movement into the state. If the direction of movement
3451 * has been reversed, the state is reset before adding the
3452 * movement (so that you don't have to compensate for any previously
3453 * collected movement before see the result of the movement in the
3454 * new direction).
3455 *
3456 * @return Returns the absolute value of the amount of movement
3457 * collected so far.
3458 */
3459 float collect(float off, long time, String axis) {
3460 long normTime;
3461 if (off > 0) {
3462 normTime = (long)(off * FAST_MOVE_TIME);
3463 if (dir < 0) {
3464 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to positive!");
3465 position = 0;
3466 step = 0;
3467 acceleration = 1;
3468 lastMoveTime = 0;
3469 }
3470 dir = 1;
3471 } else if (off < 0) {
3472 normTime = (long)((-off) * FAST_MOVE_TIME);
3473 if (dir > 0) {
3474 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to negative!");
3475 position = 0;
3476 step = 0;
3477 acceleration = 1;
3478 lastMoveTime = 0;
3479 }
3480 dir = -1;
3481 } else {
3482 normTime = 0;
3483 }
Romain Guy8506ab42009-06-11 17:35:47 -07003484
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003485 // The number of milliseconds between each movement that is
3486 // considered "normal" and will not result in any acceleration
3487 // or deceleration, scaled by the offset we have here.
3488 if (normTime > 0) {
3489 long delta = time - lastMoveTime;
3490 lastMoveTime = time;
3491 float acc = acceleration;
3492 if (delta < normTime) {
3493 // The user is scrolling rapidly, so increase acceleration.
3494 float scale = (normTime-delta) * ACCEL_MOVE_SCALING_FACTOR;
3495 if (scale > 1) acc *= scale;
3496 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " accelerate: off="
3497 + off + " normTime=" + normTime + " delta=" + delta
3498 + " scale=" + scale + " acc=" + acc);
3499 acceleration = acc < MAX_ACCELERATION ? acc : MAX_ACCELERATION;
3500 } else {
3501 // The user is scrolling slowly, so decrease acceleration.
3502 float scale = (delta-normTime) * ACCEL_MOVE_SCALING_FACTOR;
3503 if (scale > 1) acc /= scale;
3504 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " deccelerate: off="
3505 + off + " normTime=" + normTime + " delta=" + delta
3506 + " scale=" + scale + " acc=" + acc);
3507 acceleration = acc > 1 ? acc : 1;
3508 }
3509 }
3510 position += off;
3511 return (absPosition = Math.abs(position));
3512 }
3513
3514 /**
3515 * Generate the number of discrete movement events appropriate for
3516 * the currently collected trackball movement.
3517 *
3518 * @param precision The minimum movement required to generate the
3519 * first discrete movement.
3520 *
3521 * @return Returns the number of discrete movements, either positive
3522 * or negative, or 0 if there is not enough trackball movement yet
3523 * for a discrete movement.
3524 */
3525 int generate(float precision) {
3526 int movement = 0;
3527 nonAccelMovement = 0;
3528 do {
3529 final int dir = position >= 0 ? 1 : -1;
3530 switch (step) {
3531 // If we are going to execute the first step, then we want
3532 // to do this as soon as possible instead of waiting for
3533 // a full movement, in order to make things look responsive.
3534 case 0:
3535 if (absPosition < precision) {
3536 return movement;
3537 }
3538 movement += dir;
3539 nonAccelMovement += dir;
3540 step = 1;
3541 break;
3542 // If we have generated the first movement, then we need
3543 // to wait for the second complete trackball motion before
3544 // generating the second discrete movement.
3545 case 1:
3546 if (absPosition < 2) {
3547 return movement;
3548 }
3549 movement += dir;
3550 nonAccelMovement += dir;
3551 position += dir > 0 ? -2 : 2;
3552 absPosition = Math.abs(position);
3553 step = 2;
3554 break;
3555 // After the first two, we generate discrete movements
3556 // consistently with the trackball, applying an acceleration
3557 // if the trackball is moving quickly. This is a simple
3558 // acceleration on top of what we already compute based
3559 // on how quickly the wheel is being turned, to apply
3560 // a longer increasing acceleration to continuous movement
3561 // in one direction.
3562 default:
3563 if (absPosition < 1) {
3564 return movement;
3565 }
3566 movement += dir;
3567 position += dir >= 0 ? -1 : 1;
3568 absPosition = Math.abs(position);
3569 float acc = acceleration;
3570 acc *= 1.1f;
3571 acceleration = acc < MAX_ACCELERATION ? acc : acceleration;
3572 break;
3573 }
3574 } while (true);
3575 }
3576 }
3577
3578 public static final class CalledFromWrongThreadException extends AndroidRuntimeException {
3579 public CalledFromWrongThreadException(String msg) {
3580 super(msg);
3581 }
3582 }
3583
3584 private SurfaceHolder mHolder = new SurfaceHolder() {
3585 // we only need a SurfaceHolder for opengl. it would be nice
3586 // to implement everything else though, especially the callback
3587 // support (opengl doesn't make use of it right now, but eventually
3588 // will).
3589 public Surface getSurface() {
3590 return mSurface;
3591 }
3592
3593 public boolean isCreating() {
3594 return false;
3595 }
3596
3597 public void addCallback(Callback callback) {
3598 }
3599
3600 public void removeCallback(Callback callback) {
3601 }
3602
3603 public void setFixedSize(int width, int height) {
3604 }
3605
3606 public void setSizeFromLayout() {
3607 }
3608
3609 public void setFormat(int format) {
3610 }
3611
3612 public void setType(int type) {
3613 }
3614
3615 public void setKeepScreenOn(boolean screenOn) {
3616 }
3617
3618 public Canvas lockCanvas() {
3619 return null;
3620 }
3621
3622 public Canvas lockCanvas(Rect dirty) {
3623 return null;
3624 }
3625
3626 public void unlockCanvasAndPost(Canvas canvas) {
3627 }
3628 public Rect getSurfaceFrame() {
3629 return null;
3630 }
3631 };
3632
3633 static RunQueue getRunQueue() {
3634 RunQueue rq = sRunQueues.get();
3635 if (rq != null) {
3636 return rq;
3637 }
3638 rq = new RunQueue();
3639 sRunQueues.set(rq);
3640 return rq;
3641 }
Romain Guy8506ab42009-06-11 17:35:47 -07003642
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003643 /**
3644 * @hide
3645 */
3646 static final class RunQueue {
3647 private final ArrayList<HandlerAction> mActions = new ArrayList<HandlerAction>();
3648
3649 void post(Runnable action) {
3650 postDelayed(action, 0);
3651 }
3652
3653 void postDelayed(Runnable action, long delayMillis) {
3654 HandlerAction handlerAction = new HandlerAction();
3655 handlerAction.action = action;
3656 handlerAction.delay = delayMillis;
3657
3658 synchronized (mActions) {
3659 mActions.add(handlerAction);
3660 }
3661 }
3662
3663 void removeCallbacks(Runnable action) {
3664 final HandlerAction handlerAction = new HandlerAction();
3665 handlerAction.action = action;
3666
3667 synchronized (mActions) {
3668 final ArrayList<HandlerAction> actions = mActions;
3669
3670 while (actions.remove(handlerAction)) {
3671 // Keep going
3672 }
3673 }
3674 }
3675
3676 void executeActions(Handler handler) {
3677 synchronized (mActions) {
3678 final ArrayList<HandlerAction> actions = mActions;
3679 final int count = actions.size();
3680
3681 for (int i = 0; i < count; i++) {
3682 final HandlerAction handlerAction = actions.get(i);
3683 handler.postDelayed(handlerAction.action, handlerAction.delay);
3684 }
3685
Romain Guy15df6702009-08-17 20:17:30 -07003686 actions.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003687 }
3688 }
3689
3690 private static class HandlerAction {
3691 Runnable action;
3692 long delay;
3693
3694 @Override
3695 public boolean equals(Object o) {
3696 if (this == o) return true;
3697 if (o == null || getClass() != o.getClass()) return false;
3698
3699 HandlerAction that = (HandlerAction) o;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003700 return !(action != null ? !action.equals(that.action) : that.action != null);
3701
3702 }
3703
3704 @Override
3705 public int hashCode() {
3706 int result = action != null ? action.hashCode() : 0;
3707 result = 31 * result + (int) (delay ^ (delay >>> 32));
3708 return result;
3709 }
3710 }
3711 }
3712
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003713 private static native void nativeShowFPS(Canvas canvas, int durationMillis);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003714}