blob: 19726928e77b986abe38f0c8942b98f6630d22be [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;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080028import android.graphics.Canvas;
29import android.graphics.PixelFormat;
Christopher Tate2c095f32010-10-04 14:13:40 -070030import android.graphics.Point;
Christopher Tatea53146c2010-09-07 11:57:52 -070031import android.graphics.PointF;
Romain Guy6b7bd242010-10-06 19:49:23 -070032import android.graphics.PorterDuff;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080033import android.graphics.Rect;
34import android.graphics.Region;
Romain Guy6b7bd242010-10-06 19:49:23 -070035import android.media.AudioManager;
36import android.os.Binder;
37import android.os.Bundle;
38import android.os.Debug;
39import android.os.Handler;
40import android.os.LatencyTimer;
41import android.os.Looper;
42import android.os.Message;
43import android.os.ParcelFileDescriptor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080044import android.os.Process;
Romain Guy6b7bd242010-10-06 19:49:23 -070045import android.os.RemoteException;
46import android.os.ServiceManager;
47import android.os.SystemClock;
48import android.os.SystemProperties;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080049import android.util.AndroidRuntimeException;
50import android.util.Config;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -070051import android.util.DisplayMetrics;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080052import android.util.EventLog;
Romain Guy6b7bd242010-10-06 19:49:23 -070053import android.util.Log;
Chet Haase949dbf72010-08-11 18:41:06 -070054import android.util.Slog;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080055import android.util.SparseArray;
Jeff Brown3915bb82010-11-05 15:02:16 -070056import android.view.InputQueue.FinishedCallback;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080057import android.view.View.MeasureSpec;
svetoslavganov75986cf2009-05-14 22:28:01 -070058import android.view.accessibility.AccessibilityEvent;
59import android.view.accessibility.AccessibilityManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080060import android.view.inputmethod.InputConnection;
61import android.view.inputmethod.InputMethodManager;
62import android.widget.Scroller;
Joe Onorato86f67862010-11-05 18:57:34 -070063import com.android.internal.policy.PolicyManager;
Romain Guy6b7bd242010-10-06 19:49:23 -070064import com.android.internal.view.BaseSurfaceHolder;
65import com.android.internal.view.IInputMethodCallback;
66import com.android.internal.view.IInputMethodSession;
67import com.android.internal.view.RootViewSurfaceTaker;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080068
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080069import java.io.IOException;
70import java.io.OutputStream;
Romain Guy6b7bd242010-10-06 19:49:23 -070071import java.lang.ref.WeakReference;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080072import java.util.ArrayList;
73
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080074/**
75 * The top of a view hierarchy, implementing the needed protocol between View
76 * and the WindowManager. This is for the most part an internal implementation
77 * detail of {@link WindowManagerImpl}.
78 *
79 * {@hide}
80 */
Romain Guy812ccbe2010-06-01 14:07:24 -070081@SuppressWarnings({"EmptyCatchBlock", "PointlessBooleanExpression"})
82public final class ViewRoot extends Handler implements ViewParent, View.AttachInfo.Callbacks {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080083 private static final String TAG = "ViewRoot";
84 private static final boolean DBG = false;
Mike Reedfd716532009-10-12 14:42:56 -040085 private static final boolean SHOW_FPS = false;
Romain Guy812ccbe2010-06-01 14:07:24 -070086 private static final boolean LOCAL_LOGV = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080087 /** @noinspection PointlessBooleanExpression*/
88 private static final boolean DEBUG_DRAW = false || LOCAL_LOGV;
89 private static final boolean DEBUG_LAYOUT = false || LOCAL_LOGV;
Christopher Tatefa9e7c02010-05-06 12:07:10 -070090 private static final boolean DEBUG_INPUT = true || LOCAL_LOGV;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080091 private static final boolean DEBUG_INPUT_RESIZE = false || LOCAL_LOGV;
92 private static final boolean DEBUG_ORIENTATION = false || LOCAL_LOGV;
93 private static final boolean DEBUG_TRACKBALL = false || LOCAL_LOGV;
94 private static final boolean DEBUG_IMF = false || LOCAL_LOGV;
Dianne Hackborn694f79b2010-03-17 19:44:59 -070095 private static final boolean DEBUG_CONFIGURATION = false || LOCAL_LOGV;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080096 private static final boolean WATCH_POINTER = false;
97
Michael Chan53071d62009-05-13 17:29:48 -070098 private static final boolean MEASURE_LATENCY = false;
99 private static LatencyTimer lt;
100
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800101 /**
102 * Maximum time we allow the user to roll the trackball enough to generate
103 * a key event, before resetting the counters.
104 */
105 static final int MAX_TRACKBALL_DELAY = 250;
106
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800107 static IWindowSession sWindowSession;
108
109 static final Object mStaticInit = new Object();
110 static boolean mInitialized = false;
111
112 static final ThreadLocal<RunQueue> sRunQueues = new ThreadLocal<RunQueue>();
113
Dianne Hackborn2a9094d2010-02-03 19:20:09 -0800114 static final ArrayList<Runnable> sFirstDrawHandlers = new ArrayList<Runnable>();
115 static boolean sFirstDrawComplete = false;
116
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800117 static final ArrayList<ComponentCallbacks> sConfigCallbacks
118 = new ArrayList<ComponentCallbacks>();
119
Romain Guy8506ab42009-06-11 17:35:47 -0700120 private static int sDrawTime;
Romain Guy13922e02009-05-12 17:56:14 -0700121
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800122 long mLastTrackballTime = 0;
123 final TrackballAxis mTrackballAxisX = new TrackballAxis();
124 final TrackballAxis mTrackballAxisY = new TrackballAxis();
125
126 final int[] mTmpLocation = new int[2];
Romain Guy8506ab42009-06-11 17:35:47 -0700127
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800128 final InputMethodCallback mInputMethodCallback;
129 final SparseArray<Object> mPendingEvents = new SparseArray<Object>();
130 int mPendingEventSeq = 0;
Romain Guy8506ab42009-06-11 17:35:47 -0700131
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800132 final Thread mThread;
133
134 final WindowLeaked mLocation;
135
136 final WindowManager.LayoutParams mWindowAttributes = new WindowManager.LayoutParams();
137
138 final W mWindow;
139
140 View mView;
141 View mFocusedView;
142 View mRealFocusedView; // this is not set to null in touch mode
143 int mViewVisibility;
144 boolean mAppVisible = true;
145
Dianne Hackbornd76b67c2010-07-13 17:48:30 -0700146 SurfaceHolder.Callback2 mSurfaceHolderCallback;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700147 BaseSurfaceHolder mSurfaceHolder;
148 boolean mIsCreating;
149 boolean mDrawingAllowed;
150
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800151 final Region mTransparentRegion;
152 final Region mPreviousTransparentRegion;
153
154 int mWidth;
155 int mHeight;
156 Rect mDirty; // will be a graphics.Region soon
Romain Guybb93d552009-03-24 21:04:15 -0700157 boolean mIsAnimating;
Romain Guy8506ab42009-06-11 17:35:47 -0700158
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700159 CompatibilityInfo.Translator mTranslator;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800160
161 final View.AttachInfo mAttachInfo;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700162 InputChannel mInputChannel;
Dianne Hackborn1e4b9f32010-06-23 14:10:57 -0700163 InputQueue.Callback mInputQueueCallback;
164 InputQueue mInputQueue;
Joe Onorato86f67862010-11-05 18:57:34 -0700165 FallbackEventHandler mFallbackEventHandler;
Dianne Hackborna95e4cb2010-06-18 18:09:33 -0700166
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800167 final Rect mTempRect; // used in the transaction to not thrash the heap.
168 final Rect mVisRect; // used to retrieve visible rect of focused view.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800169
170 boolean mTraversalScheduled;
171 boolean mWillDrawSoon;
172 boolean mLayoutRequested;
173 boolean mFirst;
174 boolean mReportNextDraw;
175 boolean mFullRedrawNeeded;
176 boolean mNewSurfaceNeeded;
177 boolean mHasHadWindowFocus;
178 boolean mLastWasImTarget;
179
180 boolean mWindowAttributesChanged = false;
181
182 // These can be accessed by any thread, must be protected with a lock.
Mathias Agopian5583dc62009-07-09 16:28:11 -0700183 // Surface can never be reassigned or cleared (use Surface.clear()).
184 private final Surface mSurface = new Surface();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800185
186 boolean mAdded;
187 boolean mAddedTouchMode;
188
189 /*package*/ int mAddNesting;
190
191 // These are accessed by multiple threads.
192 final Rect mWinFrame; // frame given by window manager.
193
194 final Rect mPendingVisibleInsets = new Rect();
195 final Rect mPendingContentInsets = new Rect();
196 final ViewTreeObserver.InternalInsetsInfo mLastGivenInsets
197 = new ViewTreeObserver.InternalInsetsInfo();
198
Dianne Hackborn694f79b2010-03-17 19:44:59 -0700199 final Configuration mLastConfiguration = new Configuration();
200 final Configuration mPendingConfiguration = new Configuration();
201
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800202 class ResizedInfo {
203 Rect coveredInsets;
204 Rect visibleInsets;
205 Configuration newConfig;
206 }
207
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800208 boolean mScrollMayChange;
209 int mSoftInputMode;
210 View mLastScrolledFocus;
211 int mScrollY;
212 int mCurScrollY;
213 Scroller mScroller;
Romain Guy8506ab42009-06-11 17:35:47 -0700214
Romain Guy8506ab42009-06-11 17:35:47 -0700215 final ViewConfiguration mViewConfiguration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800216
Christopher Tatea53146c2010-09-07 11:57:52 -0700217 /* Drag/drop */
218 ClipDescription mDragDescription;
219 View mCurrentDragView;
220 final PointF mDragPoint = new PointF();
Christopher Tate2c095f32010-10-04 14:13:40 -0700221 final PointF mLastTouchPoint = new PointF();
Christopher Tatea53146c2010-09-07 11:57:52 -0700222
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800223 /**
224 * see {@link #playSoundEffect(int)}
225 */
226 AudioManager mAudioManager;
227
Dianne Hackborn11ea3342009-07-22 21:48:55 -0700228 private final int mDensity;
Adam Powellb08013c2010-09-16 16:28:11 -0700229
Dianne Hackborn4c62fc02009-08-08 20:40:27 -0700230 public static IWindowSession getWindowSession(Looper mainLooper) {
231 synchronized (mStaticInit) {
232 if (!mInitialized) {
233 try {
234 InputMethodManager imm = InputMethodManager.getInstance(mainLooper);
235 sWindowSession = IWindowManager.Stub.asInterface(
236 ServiceManager.getService("window"))
237 .openSession(imm.getClient(), imm.getInputContext());
238 mInitialized = true;
239 } catch (RemoteException e) {
240 }
241 }
242 return sWindowSession;
243 }
244 }
245
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800246 public ViewRoot(Context context) {
247 super();
248
Romain Guy812ccbe2010-06-01 14:07:24 -0700249 if (MEASURE_LATENCY) {
250 if (lt == null) {
251 lt = new LatencyTimer(100, 1000);
252 }
Michael Chan53071d62009-05-13 17:29:48 -0700253 }
254
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800255 // Initialize the statics when this class is first instantiated. This is
256 // done here instead of in the static block because Zygote does not
257 // allow the spawning of threads.
Dianne Hackborn4c62fc02009-08-08 20:40:27 -0700258 getWindowSession(context.getMainLooper());
259
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800260 mThread = Thread.currentThread();
261 mLocation = new WindowLeaked(null);
262 mLocation.fillInStackTrace();
263 mWidth = -1;
264 mHeight = -1;
265 mDirty = new Rect();
266 mTempRect = new Rect();
267 mVisRect = new Rect();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800268 mWinFrame = new Rect();
Romain Guyfb8b7632010-08-23 21:05:08 -0700269 mWindow = new W(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800270 mInputMethodCallback = new InputMethodCallback(this);
271 mViewVisibility = View.GONE;
272 mTransparentRegion = new Region();
273 mPreviousTransparentRegion = new Region();
274 mFirst = true; // true for the first time the view is added
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800275 mAdded = false;
276 mAttachInfo = new View.AttachInfo(sWindowSession, mWindow, this, this);
277 mViewConfiguration = ViewConfiguration.get(context);
Dianne Hackborn11ea3342009-07-22 21:48:55 -0700278 mDensity = context.getResources().getDisplayMetrics().densityDpi;
Joe Onorato86f67862010-11-05 18:57:34 -0700279 mFallbackEventHandler = PolicyManager.makeNewFallbackEventHandler(context);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800280 }
281
Dianne Hackborn2a9094d2010-02-03 19:20:09 -0800282 public static void addFirstDrawHandler(Runnable callback) {
283 synchronized (sFirstDrawHandlers) {
284 if (!sFirstDrawComplete) {
285 sFirstDrawHandlers.add(callback);
286 }
287 }
288 }
289
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800290 public static void addConfigCallback(ComponentCallbacks callback) {
291 synchronized (sConfigCallbacks) {
292 sConfigCallbacks.add(callback);
293 }
294 }
295
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800296 // FIXME for perf testing only
297 private boolean mProfile = false;
298
299 /**
300 * Call this to profile the next traversal call.
301 * FIXME for perf testing only. Remove eventually
302 */
303 public void profile() {
304 mProfile = true;
305 }
306
307 /**
308 * Indicates whether we are in touch mode. Calling this method triggers an IPC
309 * call and should be avoided whenever possible.
310 *
311 * @return True, if the device is in touch mode, false otherwise.
312 *
313 * @hide
314 */
315 static boolean isInTouchMode() {
316 if (mInitialized) {
317 try {
318 return sWindowSession.getInTouchMode();
319 } catch (RemoteException e) {
320 }
321 }
322 return false;
323 }
324
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800325 /**
326 * We have one child
327 */
Romain Guye4d01122010-06-16 18:44:05 -0700328 public void setView(View view, WindowManager.LayoutParams attrs, View panelParentView) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800329 synchronized (this) {
330 if (mView == null) {
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700331 mView = view;
Joe Onorato86f67862010-11-05 18:57:34 -0700332 mFallbackEventHandler.setView(view);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700333 mWindowAttributes.copyFrom(attrs);
Mitsuru Oshima1ecf5d22009-07-06 17:20:38 -0700334 attrs = mWindowAttributes;
Romain Guye4d01122010-06-16 18:44:05 -0700335
Romain Guy529b60a2010-08-03 18:05:47 -0700336 enableHardwareAcceleration(attrs);
Romain Guye4d01122010-06-16 18:44:05 -0700337
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700338 if (view instanceof RootViewSurfaceTaker) {
339 mSurfaceHolderCallback =
340 ((RootViewSurfaceTaker)view).willYouTakeTheSurface();
341 if (mSurfaceHolderCallback != null) {
342 mSurfaceHolder = new TakenSurfaceHolder();
Dianne Hackborn289b9b62010-07-09 11:44:11 -0700343 mSurfaceHolder.setFormat(PixelFormat.UNKNOWN);
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700344 }
345 }
Mitsuru Oshima38ed7d772009-07-21 14:39:34 -0700346 Resources resources = mView.getContext().getResources();
347 CompatibilityInfo compatibilityInfo = resources.getCompatibilityInfo();
Mitsuru Oshima589cebe2009-07-22 20:38:58 -0700348 mTranslator = compatibilityInfo.getTranslator();
Mitsuru Oshima38ed7d772009-07-21 14:39:34 -0700349
350 if (mTranslator != null || !compatibilityInfo.supportsScreen()) {
Mitsuru Oshima240f8a72009-07-22 20:39:14 -0700351 mSurface.setCompatibleDisplayMetrics(resources.getDisplayMetrics(),
352 mTranslator);
Mitsuru Oshima38ed7d772009-07-21 14:39:34 -0700353 }
354
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -0700355 boolean restore = false;
Romain Guy35b38ce2009-10-07 13:38:55 -0700356 if (mTranslator != null) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -0700357 restore = true;
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700358 attrs.backup();
359 mTranslator.translateWindowLayout(attrs);
Mitsuru Oshima3d914922009-05-13 22:29:15 -0700360 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700361 if (DEBUG_LAYOUT) Log.d(TAG, "WindowLayout in setView:" + attrs);
362
Mitsuru Oshima1ecf5d22009-07-06 17:20:38 -0700363 if (!compatibilityInfo.supportsScreen()) {
364 attrs.flags |= WindowManager.LayoutParams.FLAG_COMPATIBLE_WINDOW;
365 }
366
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800367 mSoftInputMode = attrs.softInputMode;
368 mWindowAttributesChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800369 mAttachInfo.mRootView = view;
Romain Guy35b38ce2009-10-07 13:38:55 -0700370 mAttachInfo.mScalingRequired = mTranslator != null;
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700371 mAttachInfo.mApplicationScale =
372 mTranslator == null ? 1.0f : mTranslator.applicationScale;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800373 if (panelParentView != null) {
374 mAttachInfo.mPanelParentWindowToken
375 = panelParentView.getApplicationWindowToken();
376 }
377 mAdded = true;
378 int res; /* = WindowManagerImpl.ADD_OKAY; */
Romain Guy8506ab42009-06-11 17:35:47 -0700379
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800380 // Schedule the first layout -before- adding to the window
381 // manager, to make sure we do the relayout before receiving
382 // any other events from the system.
383 requestLayout();
Jeff Brown46b9ac02010-04-22 18:58:52 -0700384 mInputChannel = new InputChannel();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800385 try {
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700386 res = sWindowSession.add(mWindow, mWindowAttributes,
Jeff Brown46b9ac02010-04-22 18:58:52 -0700387 getHostVisibility(), mAttachInfo.mContentInsets,
388 mInputChannel);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800389 } catch (RemoteException e) {
390 mAdded = false;
391 mView = null;
392 mAttachInfo.mRootView = null;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700393 mInputChannel = null;
Joe Onorato86f67862010-11-05 18:57:34 -0700394 mFallbackEventHandler.setView(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800395 unscheduleTraversals();
396 throw new RuntimeException("Adding window failed", e);
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700397 } finally {
398 if (restore) {
399 attrs.restore();
400 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800401 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700402
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700403 if (mTranslator != null) {
404 mTranslator.translateRectInScreenToAppWindow(mAttachInfo.mContentInsets);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700405 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800406 mPendingContentInsets.set(mAttachInfo.mContentInsets);
407 mPendingVisibleInsets.set(0, 0, 0, 0);
Jeff Brownc5ed5912010-07-14 18:48:53 -0700408 if (Config.LOGV) Log.v(TAG, "Added window " + mWindow);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800409 if (res < WindowManagerImpl.ADD_OKAY) {
410 mView = null;
411 mAttachInfo.mRootView = null;
412 mAdded = false;
Joe Onorato86f67862010-11-05 18:57:34 -0700413 mFallbackEventHandler.setView(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800414 unscheduleTraversals();
415 switch (res) {
416 case WindowManagerImpl.ADD_BAD_APP_TOKEN:
417 case WindowManagerImpl.ADD_BAD_SUBWINDOW_TOKEN:
418 throw new WindowManagerImpl.BadTokenException(
419 "Unable to add window -- token " + attrs.token
420 + " is not valid; is your activity running?");
421 case WindowManagerImpl.ADD_NOT_APP_TOKEN:
422 throw new WindowManagerImpl.BadTokenException(
423 "Unable to add window -- token " + attrs.token
424 + " is not for an application");
425 case WindowManagerImpl.ADD_APP_EXITING:
426 throw new WindowManagerImpl.BadTokenException(
427 "Unable to add window -- app for token " + attrs.token
428 + " is exiting");
429 case WindowManagerImpl.ADD_DUPLICATE_ADD:
430 throw new WindowManagerImpl.BadTokenException(
431 "Unable to add window -- window " + mWindow
432 + " has already been added");
433 case WindowManagerImpl.ADD_STARTING_NOT_NEEDED:
434 // Silently ignore -- we would have just removed it
435 // right away, anyway.
436 return;
437 case WindowManagerImpl.ADD_MULTIPLE_SINGLETON:
438 throw new WindowManagerImpl.BadTokenException(
439 "Unable to add window " + mWindow +
440 " -- another window of this type already exists");
441 case WindowManagerImpl.ADD_PERMISSION_DENIED:
442 throw new WindowManagerImpl.BadTokenException(
443 "Unable to add window " + mWindow +
444 " -- permission denied for this window type");
445 }
446 throw new RuntimeException(
447 "Unable to add window -- unknown error code " + res);
448 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700449
Jeff Brown00fa7bd2010-07-02 15:37:36 -0700450 if (view instanceof RootViewSurfaceTaker) {
451 mInputQueueCallback =
452 ((RootViewSurfaceTaker)view).willYouTakeTheInputQueue();
453 }
454 if (mInputQueueCallback != null) {
455 mInputQueue = new InputQueue(mInputChannel);
456 mInputQueueCallback.onInputQueueCreated(mInputQueue);
457 } else {
458 InputQueue.registerInputChannel(mInputChannel, mInputHandler,
459 Looper.myQueue());
Jeff Brown46b9ac02010-04-22 18:58:52 -0700460 }
461
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800462 view.assignParent(this);
463 mAddedTouchMode = (res&WindowManagerImpl.ADD_FLAG_IN_TOUCH_MODE) != 0;
464 mAppVisible = (res&WindowManagerImpl.ADD_FLAG_APP_VISIBLE) != 0;
465 }
466 }
467 }
468
Romain Guy529b60a2010-08-03 18:05:47 -0700469 private void enableHardwareAcceleration(WindowManager.LayoutParams attrs) {
Dianne Hackborn7eec10e2010-11-12 18:03:47 -0800470 mAttachInfo.mHardwareAccelerated = false;
471 mAttachInfo.mHardwareAccelerationRequested = false;
472
473 // Try to enable hardware acceleration if requested
474 if (attrs != null &&
475 (attrs.flags & WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED) != 0) {
476 // Only enable hardware acceleration if we are not in the system process
477 // The window manager creates ViewRoots to display animated preview windows
478 // of launching apps and we don't want those to be hardware accelerated
479 if (!HardwareRenderer.sRendererDisabled) {
Romain Guye4d01122010-06-16 18:44:05 -0700480 final boolean translucent = attrs.format != PixelFormat.OPAQUE;
Romain Guyb051e892010-09-28 19:09:36 -0700481 if (mAttachInfo.mHardwareRenderer != null) {
482 mAttachInfo.mHardwareRenderer.destroy(true);
Romain Guy4caa4ed2010-08-25 14:46:24 -0700483 }
Romain Guyb051e892010-09-28 19:09:36 -0700484 mAttachInfo.mHardwareRenderer = HardwareRenderer.createGlRenderer(2, translucent);
Dianne Hackborn7eec10e2010-11-12 18:03:47 -0800485 mAttachInfo.mHardwareAccelerated = mAttachInfo.mHardwareAccelerationRequested
486 = mAttachInfo.mHardwareRenderer != null;
487 } else if (HardwareRenderer.isAvailable()) {
488 mAttachInfo.mHardwareAccelerationRequested = true;
Romain Guye4d01122010-06-16 18:44:05 -0700489 }
490 }
491 }
492
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800493 public View getView() {
494 return mView;
495 }
496
497 final WindowLeaked getLocation() {
498 return mLocation;
499 }
500
501 void setLayoutParams(WindowManager.LayoutParams attrs, boolean newView) {
502 synchronized (this) {
The Android Open Source Project10592532009-03-18 17:39:46 -0700503 int oldSoftInputMode = mWindowAttributes.softInputMode;
Mitsuru Oshima5a2b91d2009-07-16 16:30:02 -0700504 // preserve compatible window flag if exists.
505 int compatibleWindowFlag =
506 mWindowAttributes.flags & WindowManager.LayoutParams.FLAG_COMPATIBLE_WINDOW;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800507 mWindowAttributes.copyFrom(attrs);
Mitsuru Oshima5a2b91d2009-07-16 16:30:02 -0700508 mWindowAttributes.flags |= compatibleWindowFlag;
509
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800510 if (newView) {
511 mSoftInputMode = attrs.softInputMode;
512 requestLayout();
513 }
The Android Open Source Project10592532009-03-18 17:39:46 -0700514 // Don't lose the mode we last auto-computed.
515 if ((attrs.softInputMode&WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST)
516 == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED) {
517 mWindowAttributes.softInputMode = (mWindowAttributes.softInputMode
518 & ~WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST)
519 | (oldSoftInputMode
520 & WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST);
521 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800522 mWindowAttributesChanged = true;
523 scheduleTraversals();
524 }
525 }
526
527 void handleAppVisibility(boolean visible) {
528 if (mAppVisible != visible) {
529 mAppVisible = visible;
530 scheduleTraversals();
531 }
532 }
533
534 void handleGetNewSurface() {
535 mNewSurfaceNeeded = true;
536 mFullRedrawNeeded = true;
537 scheduleTraversals();
538 }
539
540 /**
541 * {@inheritDoc}
542 */
543 public void requestLayout() {
544 checkThread();
545 mLayoutRequested = true;
546 scheduleTraversals();
547 }
548
549 /**
550 * {@inheritDoc}
551 */
552 public boolean isLayoutRequested() {
553 return mLayoutRequested;
554 }
555
556 public void invalidateChild(View child, Rect dirty) {
557 checkThread();
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700558 if (DEBUG_DRAW) Log.v(TAG, "Invalidate child: " + dirty);
Chet Haase70d4ba12010-10-06 09:46:45 -0700559 if (dirty == null) {
560 // Fast invalidation for GL-enabled applications; GL must redraw everything
561 invalidate();
562 return;
563 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700564 if (mCurScrollY != 0 || mTranslator != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800565 mTempRect.set(dirty);
Romain Guy1e095972009-07-07 11:22:45 -0700566 dirty = mTempRect;
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700567 if (mCurScrollY != 0) {
Romain Guy1e095972009-07-07 11:22:45 -0700568 dirty.offset(0, -mCurScrollY);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700569 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700570 if (mTranslator != null) {
Romain Guy1e095972009-07-07 11:22:45 -0700571 mTranslator.translateRectInAppWindowToScreen(dirty);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700572 }
Romain Guy1e095972009-07-07 11:22:45 -0700573 if (mAttachInfo.mScalingRequired) {
574 dirty.inset(-1, -1);
575 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800576 }
577 mDirty.union(dirty);
578 if (!mWillDrawSoon) {
579 scheduleTraversals();
580 }
581 }
Romain Guy0d9275e2010-10-26 14:22:30 -0700582
583 void invalidate() {
584 mDirty.set(0, 0, mWidth, mHeight);
585 scheduleTraversals();
586 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800587
588 public ViewParent getParent() {
589 return null;
590 }
591
592 public ViewParent invalidateChildInParent(final int[] location, final Rect dirty) {
593 invalidateChild(null, dirty);
594 return null;
595 }
596
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700597 public boolean getChildVisibleRect(View child, Rect r, android.graphics.Point offset) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800598 if (child != mView) {
599 throw new RuntimeException("child is not mine, honest!");
600 }
601 // Note: don't apply scroll offset, because we want to know its
602 // visibility in the virtual canvas being given to the view hierarchy.
603 return r.intersect(0, 0, mWidth, mHeight);
604 }
605
606 public void bringChildToFront(View child) {
607 }
608
609 public void scheduleTraversals() {
610 if (!mTraversalScheduled) {
611 mTraversalScheduled = true;
612 sendEmptyMessage(DO_TRAVERSAL);
613 }
614 }
615
616 public void unscheduleTraversals() {
617 if (mTraversalScheduled) {
618 mTraversalScheduled = false;
619 removeMessages(DO_TRAVERSAL);
620 }
621 }
622
623 int getHostVisibility() {
624 return mAppVisible ? mView.getVisibility() : View.GONE;
625 }
Romain Guy8506ab42009-06-11 17:35:47 -0700626
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800627 private void performTraversals() {
628 // cache mView since it is used so much below...
629 final View host = mView;
630
631 if (DBG) {
632 System.out.println("======================================");
633 System.out.println("performTraversals");
634 host.debug();
635 }
636
637 if (host == null || !mAdded)
638 return;
639
640 mTraversalScheduled = false;
641 mWillDrawSoon = true;
642 boolean windowResizesToFitContent = false;
643 boolean fullRedrawNeeded = mFullRedrawNeeded;
644 boolean newSurface = false;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700645 boolean surfaceChanged = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800646 WindowManager.LayoutParams lp = mWindowAttributes;
647
648 int desiredWindowWidth;
649 int desiredWindowHeight;
650 int childWidthMeasureSpec;
651 int childHeightMeasureSpec;
652
653 final View.AttachInfo attachInfo = mAttachInfo;
654
655 final int viewVisibility = getHostVisibility();
656 boolean viewVisibilityChanged = mViewVisibility != viewVisibility
657 || mNewSurfaceNeeded;
658
659 WindowManager.LayoutParams params = null;
660 if (mWindowAttributesChanged) {
661 mWindowAttributesChanged = false;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700662 surfaceChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800663 params = lp;
664 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700665 Rect frame = mWinFrame;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800666 if (mFirst) {
667 fullRedrawNeeded = true;
668 mLayoutRequested = true;
669
Romain Guy8506ab42009-06-11 17:35:47 -0700670 DisplayMetrics packageMetrics =
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700671 mView.getContext().getResources().getDisplayMetrics();
672 desiredWindowWidth = packageMetrics.widthPixels;
673 desiredWindowHeight = packageMetrics.heightPixels;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800674
675 // For the very first time, tell the view hierarchy that it
676 // is attached to the window. Note that at this point the surface
677 // object is not initialized to its backing store, but soon it
678 // will be (assuming the window is visible).
679 attachInfo.mSurface = mSurface;
Adam Powell26153a32010-11-08 15:22:27 -0800680 attachInfo.mUse32BitDrawingCache = PixelFormat.formatHasAlpha(lp.format) ||
681 lp.format == PixelFormat.RGBX_8888;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800682 attachInfo.mHasWindowFocus = false;
683 attachInfo.mWindowVisibility = viewVisibility;
684 attachInfo.mRecomputeGlobalAttributes = false;
685 attachInfo.mKeepScreenOn = false;
686 viewVisibilityChanged = false;
Dianne Hackborn694f79b2010-03-17 19:44:59 -0700687 mLastConfiguration.setTo(host.getResources().getConfiguration());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800688 host.dispatchAttachedToWindow(attachInfo, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800689 //Log.i(TAG, "Screen on initialized: " + attachInfo.mKeepScreenOn);
svetoslavganov75986cf2009-05-14 22:28:01 -0700690
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800691 } else {
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700692 desiredWindowWidth = frame.width();
693 desiredWindowHeight = frame.height();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800694 if (desiredWindowWidth != mWidth || desiredWindowHeight != mHeight) {
Jeff Brownc5ed5912010-07-14 18:48:53 -0700695 if (DEBUG_ORIENTATION) Log.v(TAG,
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700696 "View " + host + " resized to: " + frame);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800697 fullRedrawNeeded = true;
698 mLayoutRequested = true;
699 windowResizesToFitContent = true;
700 }
701 }
702
703 if (viewVisibilityChanged) {
704 attachInfo.mWindowVisibility = viewVisibility;
705 host.dispatchWindowVisibilityChanged(viewVisibility);
706 if (viewVisibility != View.VISIBLE || mNewSurfaceNeeded) {
Romain Guyb051e892010-09-28 19:09:36 -0700707 if (mAttachInfo.mHardwareRenderer != null) {
708 mAttachInfo.mHardwareRenderer.destroy(false);
Romain Guy4caa4ed2010-08-25 14:46:24 -0700709 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800710 }
711 if (viewVisibility == View.GONE) {
712 // After making a window gone, we will count it as being
713 // shown for the first time the next time it gets focus.
714 mHasHadWindowFocus = false;
715 }
716 }
717
718 boolean insetsChanged = false;
Romain Guy8506ab42009-06-11 17:35:47 -0700719
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800720 if (mLayoutRequested) {
Romain Guy15df6702009-08-17 20:17:30 -0700721 // Execute enqueued actions on every layout in case a view that was detached
722 // enqueued an action after being detached
723 getRunQueue().executeActions(attachInfo.mHandler);
724
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800725 if (mFirst) {
726 host.fitSystemWindows(mAttachInfo.mContentInsets);
727 // make sure touch mode code executes by setting cached value
728 // to opposite of the added touch mode.
729 mAttachInfo.mInTouchMode = !mAddedTouchMode;
Romain Guy2d4cff62010-04-09 15:39:00 -0700730 ensureTouchModeLocally(mAddedTouchMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800731 } else {
732 if (!mAttachInfo.mContentInsets.equals(mPendingContentInsets)) {
733 mAttachInfo.mContentInsets.set(mPendingContentInsets);
734 host.fitSystemWindows(mAttachInfo.mContentInsets);
735 insetsChanged = true;
736 if (DEBUG_LAYOUT) Log.v(TAG, "Content insets changing to: "
737 + mAttachInfo.mContentInsets);
738 }
739 if (!mAttachInfo.mVisibleInsets.equals(mPendingVisibleInsets)) {
740 mAttachInfo.mVisibleInsets.set(mPendingVisibleInsets);
741 if (DEBUG_LAYOUT) Log.v(TAG, "Visible insets changing to: "
742 + mAttachInfo.mVisibleInsets);
743 }
744 if (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT
745 || lp.height == ViewGroup.LayoutParams.WRAP_CONTENT) {
746 windowResizesToFitContent = true;
747
Romain Guy8506ab42009-06-11 17:35:47 -0700748 DisplayMetrics packageMetrics =
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700749 mView.getContext().getResources().getDisplayMetrics();
750 desiredWindowWidth = packageMetrics.widthPixels;
751 desiredWindowHeight = packageMetrics.heightPixels;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800752 }
753 }
754
755 childWidthMeasureSpec = getRootMeasureSpec(desiredWindowWidth, lp.width);
756 childHeightMeasureSpec = getRootMeasureSpec(desiredWindowHeight, lp.height);
757
758 // Ask host how big it wants to be
Jeff Brownc5ed5912010-07-14 18:48:53 -0700759 if (DEBUG_ORIENTATION || DEBUG_LAYOUT) Log.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800760 "Measuring " + host + " in display " + desiredWindowWidth
761 + "x" + desiredWindowHeight + "...");
762 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
763
764 if (DBG) {
765 System.out.println("======================================");
766 System.out.println("performTraversals -- after measure");
767 host.debug();
768 }
769 }
770
771 if (attachInfo.mRecomputeGlobalAttributes) {
772 //Log.i(TAG, "Computing screen on!");
773 attachInfo.mRecomputeGlobalAttributes = false;
774 boolean oldVal = attachInfo.mKeepScreenOn;
775 attachInfo.mKeepScreenOn = false;
776 host.dispatchCollectViewAttributes(0);
777 if (attachInfo.mKeepScreenOn != oldVal) {
778 params = lp;
779 //Log.i(TAG, "Keep screen on changed: " + attachInfo.mKeepScreenOn);
780 }
781 }
782
783 if (mFirst || attachInfo.mViewVisibilityChanged) {
784 attachInfo.mViewVisibilityChanged = false;
785 int resizeMode = mSoftInputMode &
786 WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST;
787 // If we are in auto resize mode, then we need to determine
788 // what mode to use now.
789 if (resizeMode == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED) {
790 final int N = attachInfo.mScrollContainers.size();
791 for (int i=0; i<N; i++) {
792 if (attachInfo.mScrollContainers.get(i).isShown()) {
793 resizeMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE;
794 }
795 }
796 if (resizeMode == 0) {
797 resizeMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN;
798 }
799 if ((lp.softInputMode &
800 WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) != resizeMode) {
801 lp.softInputMode = (lp.softInputMode &
802 ~WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) |
803 resizeMode;
804 params = lp;
805 }
806 }
807 }
Romain Guy8506ab42009-06-11 17:35:47 -0700808
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800809 if (params != null && (host.mPrivateFlags & View.REQUEST_TRANSPARENT_REGIONS) != 0) {
810 if (!PixelFormat.formatHasAlpha(params.format)) {
811 params.format = PixelFormat.TRANSLUCENT;
812 }
813 }
814
815 boolean windowShouldResize = mLayoutRequested && windowResizesToFitContent
Romain Guy2e4f4262010-04-06 11:07:52 -0700816 && ((mWidth != host.mMeasuredWidth || mHeight != host.mMeasuredHeight)
817 || (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT &&
818 frame.width() < desiredWindowWidth && frame.width() != mWidth)
819 || (lp.height == ViewGroup.LayoutParams.WRAP_CONTENT &&
820 frame.height() < desiredWindowHeight && frame.height() != mHeight));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800821
822 final boolean computesInternalInsets =
823 attachInfo.mTreeObserver.hasComputeInternalInsetsListeners();
Romain Guy812ccbe2010-06-01 14:07:24 -0700824
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800825 boolean insetsPending = false;
826 int relayoutResult = 0;
Romain Guy812ccbe2010-06-01 14:07:24 -0700827
828 if (mFirst || windowShouldResize || insetsChanged ||
829 viewVisibilityChanged || params != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800830
831 if (viewVisibility == View.VISIBLE) {
832 // If this window is giving internal insets to the window
833 // manager, and it is being added or changing its visibility,
834 // then we want to first give the window manager "fake"
835 // insets to cause it to effectively ignore the content of
836 // the window during layout. This avoids it briefly causing
837 // other windows to resize/move based on the raw frame of the
838 // window, waiting until we can finish laying out this window
839 // and get back to the window manager with the ultimately
840 // computed insets.
Romain Guy812ccbe2010-06-01 14:07:24 -0700841 insetsPending = computesInternalInsets && (mFirst || viewVisibilityChanged);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800842 }
843
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700844 if (mSurfaceHolder != null) {
845 mSurfaceHolder.mSurfaceLock.lock();
846 mDrawingAllowed = true;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700847 }
Romain Guy812ccbe2010-06-01 14:07:24 -0700848
Romain Guyc361da82010-10-25 15:29:10 -0700849 boolean hwInitialized = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800850 boolean contentInsetsChanged = false;
Romain Guy13922e02009-05-12 17:56:14 -0700851 boolean visibleInsetsChanged;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700852 boolean hadSurface = mSurface.isValid();
Romain Guy812ccbe2010-06-01 14:07:24 -0700853
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800854 try {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800855 int fl = 0;
856 if (params != null) {
857 fl = params.flags;
858 if (attachInfo.mKeepScreenOn) {
859 params.flags |= WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
860 }
861 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700862 if (DEBUG_LAYOUT) {
863 Log.i(TAG, "host=w:" + host.mMeasuredWidth + ", h:" +
864 host.mMeasuredHeight + ", params=" + params);
865 }
866 relayoutResult = relayoutWindow(params, viewVisibility, insetsPending);
867
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800868 if (params != null) {
869 params.flags = fl;
870 }
871
872 if (DEBUG_LAYOUT) Log.v(TAG, "relayout: frame=" + frame.toShortString()
873 + " content=" + mPendingContentInsets.toShortString()
874 + " visible=" + mPendingVisibleInsets.toShortString()
875 + " surface=" + mSurface);
Romain Guy8506ab42009-06-11 17:35:47 -0700876
Dianne Hackborn694f79b2010-03-17 19:44:59 -0700877 if (mPendingConfiguration.seq != 0) {
878 if (DEBUG_CONFIGURATION) Log.v(TAG, "Visible with new config: "
879 + mPendingConfiguration);
880 updateConfiguration(mPendingConfiguration, !mFirst);
881 mPendingConfiguration.seq = 0;
882 }
883
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800884 contentInsetsChanged = !mPendingContentInsets.equals(
885 mAttachInfo.mContentInsets);
886 visibleInsetsChanged = !mPendingVisibleInsets.equals(
887 mAttachInfo.mVisibleInsets);
888 if (contentInsetsChanged) {
889 mAttachInfo.mContentInsets.set(mPendingContentInsets);
890 host.fitSystemWindows(mAttachInfo.mContentInsets);
891 if (DEBUG_LAYOUT) Log.v(TAG, "Content insets changing to: "
892 + mAttachInfo.mContentInsets);
893 }
894 if (visibleInsetsChanged) {
895 mAttachInfo.mVisibleInsets.set(mPendingVisibleInsets);
896 if (DEBUG_LAYOUT) Log.v(TAG, "Visible insets changing to: "
897 + mAttachInfo.mVisibleInsets);
898 }
899
900 if (!hadSurface) {
901 if (mSurface.isValid()) {
902 // If we are creating a new surface, then we need to
903 // completely redraw it. Also, when we get to the
904 // point of drawing it we will hold off and schedule
905 // a new traversal instead. This is so we can tell the
906 // window manager about all of the windows being displayed
907 // before actually drawing them, so it can display then
908 // all at once.
909 newSurface = true;
910 fullRedrawNeeded = true;
Jack Palevich61a6e682009-10-09 17:37:50 -0700911 mPreviousTransparentRegion.setEmpty();
Romain Guy8506ab42009-06-11 17:35:47 -0700912
Romain Guyb051e892010-09-28 19:09:36 -0700913 if (mAttachInfo.mHardwareRenderer != null) {
Romain Guyc361da82010-10-25 15:29:10 -0700914 hwInitialized = mAttachInfo.mHardwareRenderer.initialize(mHolder);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800915 }
916 }
917 } else if (!mSurface.isValid()) {
918 // If the surface has been removed, then reset the scroll
919 // positions.
920 mLastScrolledFocus = null;
921 mScrollY = mCurScrollY = 0;
922 if (mScroller != null) {
923 mScroller.abortAnimation();
924 }
925 }
926 } catch (RemoteException e) {
927 }
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700928
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800929 if (DEBUG_ORIENTATION) Log.v(
Jeff Brownc5ed5912010-07-14 18:48:53 -0700930 TAG, "Relayout returned: frame=" + frame + ", surface=" + mSurface);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800931
932 attachInfo.mWindowLeft = frame.left;
933 attachInfo.mWindowTop = frame.top;
934
935 // !!FIXME!! This next section handles the case where we did not get the
936 // window size we asked for. We should avoid this by getting a maximum size from
937 // the window session beforehand.
938 mWidth = frame.width();
939 mHeight = frame.height();
940
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700941 if (mSurfaceHolder != null) {
942 // The app owns the surface; tell it about what is going on.
943 if (mSurface.isValid()) {
944 // XXX .copyFrom() doesn't work!
945 //mSurfaceHolder.mSurface.copyFrom(mSurface);
946 mSurfaceHolder.mSurface = mSurface;
947 }
948 mSurfaceHolder.mSurfaceLock.unlock();
949 if (mSurface.isValid()) {
950 if (!hadSurface) {
951 mSurfaceHolder.ungetCallbacks();
952
953 mIsCreating = true;
954 mSurfaceHolderCallback.surfaceCreated(mSurfaceHolder);
955 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
956 if (callbacks != null) {
957 for (SurfaceHolder.Callback c : callbacks) {
958 c.surfaceCreated(mSurfaceHolder);
959 }
960 }
961 surfaceChanged = true;
Romain Guyc361da82010-10-25 15:29:10 -0700962
963 if (mAttachInfo.mHardwareRenderer != null) {
964 // This will bail out early if already initialized
965 mAttachInfo.mHardwareRenderer.initialize(mHolder);
966 }
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700967 }
968 if (surfaceChanged) {
969 mSurfaceHolderCallback.surfaceChanged(mSurfaceHolder,
970 lp.format, mWidth, mHeight);
971 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
972 if (callbacks != null) {
973 for (SurfaceHolder.Callback c : callbacks) {
974 c.surfaceChanged(mSurfaceHolder, lp.format,
975 mWidth, mHeight);
976 }
977 }
978 }
979 mIsCreating = false;
980 } else if (hadSurface) {
981 mSurfaceHolder.ungetCallbacks();
982 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
983 mSurfaceHolderCallback.surfaceDestroyed(mSurfaceHolder);
984 if (callbacks != null) {
985 for (SurfaceHolder.Callback c : callbacks) {
986 c.surfaceDestroyed(mSurfaceHolder);
987 }
988 }
989 mSurfaceHolder.mSurfaceLock.lock();
990 // Make surface invalid.
991 //mSurfaceHolder.mSurface.copyFrom(mSurface);
992 mSurfaceHolder.mSurface = new Surface();
993 mSurfaceHolder.mSurfaceLock.unlock();
994 }
995 }
Romain Guy53389bd2010-09-07 17:16:32 -0700996
Romain Guyc361da82010-10-25 15:29:10 -0700997 if (hwInitialized || (windowShouldResize && mAttachInfo.mHardwareRenderer != null)) {
Romain Guyb051e892010-09-28 19:09:36 -0700998 mAttachInfo.mHardwareRenderer.setup(mWidth, mHeight);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800999 }
1000
1001 boolean focusChangedDueToTouchMode = ensureTouchModeLocally(
Romain Guy2d4cff62010-04-09 15:39:00 -07001002 (relayoutResult&WindowManagerImpl.RELAYOUT_IN_TOUCH_MODE) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001003 if (focusChangedDueToTouchMode || mWidth != host.mMeasuredWidth
1004 || mHeight != host.mMeasuredHeight || contentInsetsChanged) {
1005 childWidthMeasureSpec = getRootMeasureSpec(mWidth, lp.width);
1006 childHeightMeasureSpec = getRootMeasureSpec(mHeight, lp.height);
1007
1008 if (DEBUG_LAYOUT) Log.v(TAG, "Ooops, something changed! mWidth="
1009 + mWidth + " measuredWidth=" + host.mMeasuredWidth
1010 + " mHeight=" + mHeight
1011 + " measuredHeight" + host.mMeasuredHeight
1012 + " coveredInsetsChanged=" + contentInsetsChanged);
Romain Guy8506ab42009-06-11 17:35:47 -07001013
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001014 // Ask host how big it wants to be
1015 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
1016
1017 // Implementation of weights from WindowManager.LayoutParams
1018 // We just grow the dimensions as needed and re-measure if
1019 // needs be
1020 int width = host.mMeasuredWidth;
1021 int height = host.mMeasuredHeight;
1022 boolean measureAgain = false;
1023
1024 if (lp.horizontalWeight > 0.0f) {
1025 width += (int) ((mWidth - width) * lp.horizontalWeight);
1026 childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(width,
1027 MeasureSpec.EXACTLY);
1028 measureAgain = true;
1029 }
1030 if (lp.verticalWeight > 0.0f) {
1031 height += (int) ((mHeight - height) * lp.verticalWeight);
1032 childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(height,
1033 MeasureSpec.EXACTLY);
1034 measureAgain = true;
1035 }
1036
1037 if (measureAgain) {
1038 if (DEBUG_LAYOUT) Log.v(TAG,
1039 "And hey let's measure once more: width=" + width
1040 + " height=" + height);
1041 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
1042 }
1043
1044 mLayoutRequested = true;
1045 }
1046 }
1047
1048 final boolean didLayout = mLayoutRequested;
1049 boolean triggerGlobalLayoutListener = didLayout
1050 || attachInfo.mRecomputeGlobalAttributes;
1051 if (didLayout) {
1052 mLayoutRequested = false;
1053 mScrollMayChange = true;
1054 if (DEBUG_ORIENTATION || DEBUG_LAYOUT) Log.v(
Jeff Brownc5ed5912010-07-14 18:48:53 -07001055 TAG, "Laying out " + host + " to (" +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001056 host.mMeasuredWidth + ", " + host.mMeasuredHeight + ")");
Romain Guy13922e02009-05-12 17:56:14 -07001057 long startTime = 0L;
Romain Guy5429e1d2010-09-07 12:38:00 -07001058 if (ViewDebug.DEBUG_PROFILE_LAYOUT) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001059 startTime = SystemClock.elapsedRealtime();
1060 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001061 host.layout(0, 0, host.mMeasuredWidth, host.mMeasuredHeight);
1062
Romain Guy13922e02009-05-12 17:56:14 -07001063 if (Config.DEBUG && ViewDebug.consistencyCheckEnabled) {
1064 if (!host.dispatchConsistencyCheck(ViewDebug.CONSISTENCY_LAYOUT)) {
1065 throw new IllegalStateException("The view hierarchy is an inconsistent state,"
1066 + "please refer to the logs with the tag "
1067 + ViewDebug.CONSISTENCY_LOG_TAG + " for more infomation.");
1068 }
1069 }
1070
Romain Guy5429e1d2010-09-07 12:38:00 -07001071 if (ViewDebug.DEBUG_PROFILE_LAYOUT) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001072 EventLog.writeEvent(60001, SystemClock.elapsedRealtime() - startTime);
1073 }
1074
1075 // By this point all views have been sized and positionned
1076 // We can compute the transparent area
1077
1078 if ((host.mPrivateFlags & View.REQUEST_TRANSPARENT_REGIONS) != 0) {
1079 // start out transparent
1080 // TODO: AVOID THAT CALL BY CACHING THE RESULT?
1081 host.getLocationInWindow(mTmpLocation);
1082 mTransparentRegion.set(mTmpLocation[0], mTmpLocation[1],
1083 mTmpLocation[0] + host.mRight - host.mLeft,
1084 mTmpLocation[1] + host.mBottom - host.mTop);
1085
1086 host.gatherTransparentRegion(mTransparentRegion);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001087 if (mTranslator != null) {
1088 mTranslator.translateRegionInWindowToScreen(mTransparentRegion);
1089 }
1090
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001091 if (!mTransparentRegion.equals(mPreviousTransparentRegion)) {
1092 mPreviousTransparentRegion.set(mTransparentRegion);
1093 // reconfigure window manager
1094 try {
1095 sWindowSession.setTransparentRegion(mWindow, mTransparentRegion);
1096 } catch (RemoteException e) {
1097 }
1098 }
1099 }
1100
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001101 if (DBG) {
1102 System.out.println("======================================");
1103 System.out.println("performTraversals -- after setFrame");
1104 host.debug();
1105 }
1106 }
1107
1108 if (triggerGlobalLayoutListener) {
1109 attachInfo.mRecomputeGlobalAttributes = false;
1110 attachInfo.mTreeObserver.dispatchOnGlobalLayout();
1111 }
1112
1113 if (computesInternalInsets) {
1114 ViewTreeObserver.InternalInsetsInfo insets = attachInfo.mGivenInternalInsets;
1115 final Rect givenContent = attachInfo.mGivenInternalInsets.contentInsets;
1116 final Rect givenVisible = attachInfo.mGivenInternalInsets.visibleInsets;
1117 givenContent.left = givenContent.top = givenContent.right
1118 = givenContent.bottom = givenVisible.left = givenVisible.top
1119 = givenVisible.right = givenVisible.bottom = 0;
1120 attachInfo.mTreeObserver.dispatchOnComputeInternalInsets(insets);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001121 Rect contentInsets = insets.contentInsets;
1122 Rect visibleInsets = insets.visibleInsets;
1123 if (mTranslator != null) {
1124 contentInsets = mTranslator.getTranslatedContentInsets(contentInsets);
1125 visibleInsets = mTranslator.getTranslatedVisbileInsets(visibleInsets);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001126 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001127 if (insetsPending || !mLastGivenInsets.equals(insets)) {
1128 mLastGivenInsets.set(insets);
1129 try {
1130 sWindowSession.setInsets(mWindow, insets.mTouchableInsets,
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001131 contentInsets, visibleInsets);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001132 } catch (RemoteException e) {
1133 }
1134 }
1135 }
Romain Guy8506ab42009-06-11 17:35:47 -07001136
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001137 if (mFirst) {
1138 // handle first focus request
1139 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: mView.hasFocus()="
1140 + mView.hasFocus());
1141 if (mView != null) {
1142 if (!mView.hasFocus()) {
1143 mView.requestFocus(View.FOCUS_FORWARD);
1144 mFocusedView = mRealFocusedView = mView.findFocus();
1145 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: requested focused view="
1146 + mFocusedView);
1147 } else {
1148 mRealFocusedView = mView.findFocus();
1149 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: existing focused view="
1150 + mRealFocusedView);
1151 }
1152 }
1153 }
1154
1155 mFirst = false;
1156 mWillDrawSoon = false;
1157 mNewSurfaceNeeded = false;
1158 mViewVisibility = viewVisibility;
1159
1160 if (mAttachInfo.mHasWindowFocus) {
1161 final boolean imTarget = WindowManager.LayoutParams
1162 .mayUseInputMethod(mWindowAttributes.flags);
1163 if (imTarget != mLastWasImTarget) {
1164 mLastWasImTarget = imTarget;
1165 InputMethodManager imm = InputMethodManager.peekInstance();
1166 if (imm != null && imTarget) {
1167 imm.startGettingWindowFocus(mView);
1168 imm.onWindowFocus(mView, mView.findFocus(),
1169 mWindowAttributes.softInputMode,
1170 !mHasHadWindowFocus, mWindowAttributes.flags);
1171 }
1172 }
1173 }
Romain Guy8506ab42009-06-11 17:35:47 -07001174
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001175 boolean cancelDraw = attachInfo.mTreeObserver.dispatchOnPreDraw();
1176
1177 if (!cancelDraw && !newSurface) {
1178 mFullRedrawNeeded = false;
1179 draw(fullRedrawNeeded);
1180
1181 if ((relayoutResult&WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0
1182 || mReportNextDraw) {
1183 if (LOCAL_LOGV) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001184 Log.v(TAG, "FINISHED DRAWING: " + mWindowAttributes.getTitle());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001185 }
1186 mReportNextDraw = false;
Dianne Hackbornd76b67c2010-07-13 17:48:30 -07001187 if (mSurfaceHolder != null && mSurface.isValid()) {
1188 mSurfaceHolderCallback.surfaceRedrawNeeded(mSurfaceHolder);
1189 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
1190 if (callbacks != null) {
1191 for (SurfaceHolder.Callback c : callbacks) {
1192 if (c instanceof SurfaceHolder.Callback2) {
1193 ((SurfaceHolder.Callback2)c).surfaceRedrawNeeded(
1194 mSurfaceHolder);
1195 }
1196 }
1197 }
1198 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001199 try {
1200 sWindowSession.finishDrawing(mWindow);
1201 } catch (RemoteException e) {
1202 }
1203 }
1204 } else {
1205 // We were supposed to report when we are done drawing. Since we canceled the
1206 // draw, remember it here.
1207 if ((relayoutResult&WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0) {
1208 mReportNextDraw = true;
1209 }
1210 if (fullRedrawNeeded) {
1211 mFullRedrawNeeded = true;
1212 }
1213 // Try again
1214 scheduleTraversals();
1215 }
1216 }
1217
1218 public void requestTransparentRegion(View child) {
1219 // the test below should not fail unless someone is messing with us
1220 checkThread();
1221 if (mView == child) {
1222 mView.mPrivateFlags |= View.REQUEST_TRANSPARENT_REGIONS;
1223 // Need to make sure we re-evaluate the window attributes next
1224 // time around, to ensure the window has the correct format.
1225 mWindowAttributesChanged = true;
Mathias Agopian1bd80ad2010-11-04 17:13:39 -07001226 requestLayout();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001227 }
1228 }
1229
1230 /**
1231 * Figures out the measure spec for the root view in a window based on it's
1232 * layout params.
1233 *
1234 * @param windowSize
1235 * The available width or height of the window
1236 *
1237 * @param rootDimension
1238 * The layout params for one dimension (width or height) of the
1239 * window.
1240 *
1241 * @return The measure spec to use to measure the root view.
1242 */
1243 private int getRootMeasureSpec(int windowSize, int rootDimension) {
1244 int measureSpec;
1245 switch (rootDimension) {
1246
Romain Guy980a9382010-01-08 15:06:28 -08001247 case ViewGroup.LayoutParams.MATCH_PARENT:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001248 // Window can't resize. Force root view to be windowSize.
1249 measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.EXACTLY);
1250 break;
1251 case ViewGroup.LayoutParams.WRAP_CONTENT:
1252 // Window can resize. Set max size for root view.
1253 measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.AT_MOST);
1254 break;
1255 default:
1256 // Window wants to be an exact size. Force root view to be that size.
1257 measureSpec = MeasureSpec.makeMeasureSpec(rootDimension, MeasureSpec.EXACTLY);
1258 break;
1259 }
1260 return measureSpec;
1261 }
1262
1263 private void draw(boolean fullRedrawNeeded) {
1264 Surface surface = mSurface;
1265 if (surface == null || !surface.isValid()) {
1266 return;
1267 }
1268
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001269 if (!sFirstDrawComplete) {
1270 synchronized (sFirstDrawHandlers) {
1271 sFirstDrawComplete = true;
Romain Guy812ccbe2010-06-01 14:07:24 -07001272 final int count = sFirstDrawHandlers.size();
1273 for (int i = 0; i< count; i++) {
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001274 post(sFirstDrawHandlers.get(i));
1275 }
1276 }
1277 }
1278
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001279 scrollToRectOrFocus(null, false);
1280
1281 if (mAttachInfo.mViewScrollChanged) {
1282 mAttachInfo.mViewScrollChanged = false;
1283 mAttachInfo.mTreeObserver.dispatchOnScrollChanged();
1284 }
Romain Guy8506ab42009-06-11 17:35:47 -07001285
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001286 int yoff;
Romain Guy5bcdff42009-05-14 21:27:18 -07001287 final boolean scrolling = mScroller != null && mScroller.computeScrollOffset();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001288 if (scrolling) {
1289 yoff = mScroller.getCurrY();
1290 } else {
1291 yoff = mScrollY;
1292 }
1293 if (mCurScrollY != yoff) {
1294 mCurScrollY = yoff;
1295 fullRedrawNeeded = true;
1296 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001297 float appScale = mAttachInfo.mApplicationScale;
1298 boolean scalingRequired = mAttachInfo.mScalingRequired;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001299
1300 Rect dirty = mDirty;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001301 if (mSurfaceHolder != null) {
1302 // The app owns the surface, we won't draw.
1303 dirty.setEmpty();
1304 return;
1305 }
Romain Guy58ef7fb2010-09-13 12:52:37 -07001306
1307 if (fullRedrawNeeded) {
1308 mAttachInfo.mIgnoreDirtyState = true;
1309 dirty.union(0, 0, (int) (mWidth * appScale + 0.5f), (int) (mHeight * appScale + 0.5f));
1310 }
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001311
Romain Guyb051e892010-09-28 19:09:36 -07001312 if (mAttachInfo.mHardwareRenderer != null && mAttachInfo.mHardwareRenderer.isEnabled()) {
Romain Guyfd507262010-10-10 15:42:49 -07001313 if (!dirty.isEmpty() || mIsAnimating) {
Romain Guy101e2ae2010-10-11 12:41:21 -07001314 mIsAnimating = false;
Romain Guyfd507262010-10-10 15:42:49 -07001315 dirty.setEmpty();
Romain Guy101e2ae2010-10-11 12:41:21 -07001316 mAttachInfo.mHardwareRenderer.draw(mView, mAttachInfo, yoff);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001317 }
Romain Guy812ccbe2010-06-01 14:07:24 -07001318
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001319 if (scrolling) {
1320 mFullRedrawNeeded = true;
1321 scheduleTraversals();
1322 }
Romain Guy812ccbe2010-06-01 14:07:24 -07001323
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001324 return;
1325 }
1326
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001327 if (DEBUG_ORIENTATION || DEBUG_DRAW) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001328 Log.v(TAG, "Draw " + mView + "/"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001329 + mWindowAttributes.getTitle()
1330 + ": dirty={" + dirty.left + "," + dirty.top
1331 + "," + dirty.right + "," + dirty.bottom + "} surface="
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001332 + surface + " surface.isValid()=" + surface.isValid() + ", appScale:" +
1333 appScale + ", width=" + mWidth + ", height=" + mHeight);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001334 }
1335
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001336 if (!dirty.isEmpty() || mIsAnimating) {
1337 Canvas canvas;
1338 try {
1339 int left = dirty.left;
1340 int top = dirty.top;
1341 int right = dirty.right;
1342 int bottom = dirty.bottom;
1343 canvas = surface.lockCanvas(dirty);
Romain Guy5bcdff42009-05-14 21:27:18 -07001344
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001345 if (left != dirty.left || top != dirty.top || right != dirty.right ||
1346 bottom != dirty.bottom) {
1347 mAttachInfo.mIgnoreDirtyState = true;
1348 }
1349
1350 // TODO: Do this in native
1351 canvas.setDensity(mDensity);
1352 } catch (Surface.OutOfResourcesException e) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001353 Log.e(TAG, "OutOfResourcesException locking surface", e);
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001354 // TODO: we should ask the window manager to do something!
1355 // for now we just do nothing
1356 return;
1357 } catch (IllegalArgumentException e) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001358 Log.e(TAG, "IllegalArgumentException locking surface", e);
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001359 // TODO: we should ask the window manager to do something!
1360 // for now we just do nothing
1361 return;
Romain Guy5bcdff42009-05-14 21:27:18 -07001362 }
1363
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001364 try {
1365 if (!dirty.isEmpty() || mIsAnimating) {
1366 long startTime = 0L;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001367
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001368 if (DEBUG_ORIENTATION || DEBUG_DRAW) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001369 Log.v(TAG, "Surface " + surface + " drawing to bitmap w="
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001370 + canvas.getWidth() + ", h=" + canvas.getHeight());
1371 //canvas.drawARGB(255, 255, 0, 0);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001372 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001373
Romain Guy5429e1d2010-09-07 12:38:00 -07001374 if (ViewDebug.DEBUG_PROFILE_DRAWING) {
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001375 startTime = SystemClock.elapsedRealtime();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001376 }
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001377
1378 // If this bitmap's format includes an alpha channel, we
1379 // need to clear it before drawing so that the child will
1380 // properly re-composite its drawing on a transparent
1381 // background. This automatically respects the clip/dirty region
1382 // or
1383 // If we are applying an offset, we need to clear the area
1384 // where the offset doesn't appear to avoid having garbage
1385 // left in the blank areas.
1386 if (!canvas.isOpaque() || yoff != 0) {
1387 canvas.drawColor(0, PorterDuff.Mode.CLEAR);
1388 }
1389
1390 dirty.setEmpty();
1391 mIsAnimating = false;
1392 mAttachInfo.mDrawingTime = SystemClock.uptimeMillis();
1393 mView.mPrivateFlags |= View.DRAWN;
1394
1395 if (DEBUG_DRAW) {
1396 Context cxt = mView.getContext();
1397 Log.i(TAG, "Drawing: package:" + cxt.getPackageName() +
1398 ", metrics=" + cxt.getResources().getDisplayMetrics() +
1399 ", compatibilityInfo=" + cxt.getResources().getCompatibilityInfo());
1400 }
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001401 try {
1402 canvas.translate(0, -yoff);
1403 if (mTranslator != null) {
1404 mTranslator.translateCanvas(canvas);
1405 }
1406 canvas.setScreenDensity(scalingRequired
1407 ? DisplayMetrics.DENSITY_DEVICE : 0);
1408 mView.draw(canvas);
1409 } finally {
1410 mAttachInfo.mIgnoreDirtyState = false;
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001411 }
1412
1413 if (Config.DEBUG && ViewDebug.consistencyCheckEnabled) {
1414 mView.dispatchConsistencyCheck(ViewDebug.CONSISTENCY_DRAWING);
1415 }
1416
Romain Guy5429e1d2010-09-07 12:38:00 -07001417 if (SHOW_FPS || ViewDebug.DEBUG_SHOW_FPS) {
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001418 int now = (int)SystemClock.elapsedRealtime();
1419 if (sDrawTime != 0) {
1420 nativeShowFPS(canvas, now - sDrawTime);
1421 }
1422 sDrawTime = now;
1423 }
1424
Romain Guy5429e1d2010-09-07 12:38:00 -07001425 if (ViewDebug.DEBUG_PROFILE_DRAWING) {
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001426 EventLog.writeEvent(60000, SystemClock.elapsedRealtime() - startTime);
1427 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001428 }
1429
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001430 } finally {
1431 surface.unlockCanvasAndPost(canvas);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001432 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001433 }
1434
1435 if (LOCAL_LOGV) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001436 Log.v(TAG, "Surface " + surface + " unlockCanvasAndPost");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001437 }
Romain Guy8506ab42009-06-11 17:35:47 -07001438
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001439 if (scrolling) {
1440 mFullRedrawNeeded = true;
1441 scheduleTraversals();
1442 }
1443 }
1444
1445 boolean scrollToRectOrFocus(Rect rectangle, boolean immediate) {
1446 final View.AttachInfo attachInfo = mAttachInfo;
1447 final Rect ci = attachInfo.mContentInsets;
1448 final Rect vi = attachInfo.mVisibleInsets;
1449 int scrollY = 0;
1450 boolean handled = false;
Romain Guy8506ab42009-06-11 17:35:47 -07001451
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001452 if (vi.left > ci.left || vi.top > ci.top
1453 || vi.right > ci.right || vi.bottom > ci.bottom) {
1454 // We'll assume that we aren't going to change the scroll
1455 // offset, since we want to avoid that unless it is actually
1456 // going to make the focus visible... otherwise we scroll
1457 // all over the place.
1458 scrollY = mScrollY;
1459 // We can be called for two different situations: during a draw,
1460 // to update the scroll position if the focus has changed (in which
1461 // case 'rectangle' is null), or in response to a
1462 // requestChildRectangleOnScreen() call (in which case 'rectangle'
1463 // is non-null and we just want to scroll to whatever that
1464 // rectangle is).
1465 View focus = mRealFocusedView;
Romain Guye8b16522009-07-14 13:06:42 -07001466
1467 // When in touch mode, focus points to the previously focused view,
1468 // which may have been removed from the view hierarchy. The following
Joe Onoratob71193b2009-11-24 18:34:42 -05001469 // line checks whether the view is still in our hierarchy.
1470 if (focus == null || focus.mAttachInfo != mAttachInfo) {
Romain Guye8b16522009-07-14 13:06:42 -07001471 mRealFocusedView = null;
1472 return false;
1473 }
1474
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001475 if (focus != mLastScrolledFocus) {
1476 // If the focus has changed, then ignore any requests to scroll
1477 // to a rectangle; first we want to make sure the entire focus
1478 // view is visible.
1479 rectangle = null;
1480 }
1481 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Eval scroll: focus=" + focus
1482 + " rectangle=" + rectangle + " ci=" + ci
1483 + " vi=" + vi);
1484 if (focus == mLastScrolledFocus && !mScrollMayChange
1485 && rectangle == null) {
1486 // Optimization: if the focus hasn't changed since last
1487 // time, and no layout has happened, then just leave things
1488 // as they are.
1489 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Keeping scroll y="
1490 + mScrollY + " vi=" + vi.toShortString());
1491 } else if (focus != null) {
1492 // We need to determine if the currently focused view is
1493 // within the visible part of the window and, if not, apply
1494 // a pan so it can be seen.
1495 mLastScrolledFocus = focus;
1496 mScrollMayChange = false;
1497 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Need to scroll?");
1498 // Try to find the rectangle from the focus view.
1499 if (focus.getGlobalVisibleRect(mVisRect, null)) {
1500 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Root w="
1501 + mView.getWidth() + " h=" + mView.getHeight()
1502 + " ci=" + ci.toShortString()
1503 + " vi=" + vi.toShortString());
1504 if (rectangle == null) {
1505 focus.getFocusedRect(mTempRect);
1506 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Focus " + focus
1507 + ": focusRect=" + mTempRect.toShortString());
Dianne Hackborn1c6a8942010-03-23 16:34:20 -07001508 if (mView instanceof ViewGroup) {
1509 ((ViewGroup) mView).offsetDescendantRectToMyCoords(
1510 focus, mTempRect);
1511 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001512 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1513 "Focus in window: focusRect="
1514 + mTempRect.toShortString()
1515 + " visRect=" + mVisRect.toShortString());
1516 } else {
1517 mTempRect.set(rectangle);
1518 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1519 "Request scroll to rect: "
1520 + mTempRect.toShortString()
1521 + " visRect=" + mVisRect.toShortString());
1522 }
1523 if (mTempRect.intersect(mVisRect)) {
1524 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1525 "Focus window visible rect: "
1526 + mTempRect.toShortString());
1527 if (mTempRect.height() >
1528 (mView.getHeight()-vi.top-vi.bottom)) {
1529 // If the focus simply is not going to fit, then
1530 // best is probably just to leave things as-is.
1531 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1532 "Too tall; leaving scrollY=" + scrollY);
1533 } else if ((mTempRect.top-scrollY) < vi.top) {
1534 scrollY -= vi.top - (mTempRect.top-scrollY);
1535 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1536 "Top covered; scrollY=" + scrollY);
1537 } else if ((mTempRect.bottom-scrollY)
1538 > (mView.getHeight()-vi.bottom)) {
1539 scrollY += (mTempRect.bottom-scrollY)
1540 - (mView.getHeight()-vi.bottom);
1541 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1542 "Bottom covered; scrollY=" + scrollY);
1543 }
1544 handled = true;
1545 }
1546 }
1547 }
1548 }
Romain Guy8506ab42009-06-11 17:35:47 -07001549
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001550 if (scrollY != mScrollY) {
1551 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Pan scroll changed: old="
1552 + mScrollY + " , new=" + scrollY);
1553 if (!immediate) {
1554 if (mScroller == null) {
1555 mScroller = new Scroller(mView.getContext());
1556 }
1557 mScroller.startScroll(0, mScrollY, 0, scrollY-mScrollY);
1558 } else if (mScroller != null) {
1559 mScroller.abortAnimation();
1560 }
1561 mScrollY = scrollY;
1562 }
Romain Guy8506ab42009-06-11 17:35:47 -07001563
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001564 return handled;
1565 }
Romain Guy8506ab42009-06-11 17:35:47 -07001566
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001567 public void requestChildFocus(View child, View focused) {
1568 checkThread();
1569 if (mFocusedView != focused) {
1570 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(mFocusedView, focused);
1571 scheduleTraversals();
1572 }
1573 mFocusedView = mRealFocusedView = focused;
1574 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Request child focus: focus now "
1575 + mFocusedView);
1576 }
1577
1578 public void clearChildFocus(View child) {
1579 checkThread();
1580
1581 View oldFocus = mFocusedView;
1582
1583 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Clearing child focus");
1584 mFocusedView = mRealFocusedView = null;
1585 if (mView != null && !mView.hasFocus()) {
1586 // If a view gets the focus, the listener will be invoked from requestChildFocus()
1587 if (!mView.requestFocus(View.FOCUS_FORWARD)) {
1588 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
1589 }
1590 } else if (oldFocus != null) {
1591 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
1592 }
1593 }
1594
1595
1596 public void focusableViewAvailable(View v) {
1597 checkThread();
1598
1599 if (mView != null && !mView.hasFocus()) {
1600 v.requestFocus();
1601 } else {
1602 // the one case where will transfer focus away from the current one
1603 // is if the current view is a view group that prefers to give focus
1604 // to its children first AND the view is a descendant of it.
1605 mFocusedView = mView.findFocus();
1606 boolean descendantsHaveDibsOnFocus =
1607 (mFocusedView instanceof ViewGroup) &&
1608 (((ViewGroup) mFocusedView).getDescendantFocusability() ==
1609 ViewGroup.FOCUS_AFTER_DESCENDANTS);
1610 if (descendantsHaveDibsOnFocus && isViewDescendantOf(v, mFocusedView)) {
1611 // If a view gets the focus, the listener will be invoked from requestChildFocus()
1612 v.requestFocus();
1613 }
1614 }
1615 }
1616
1617 public void recomputeViewAttributes(View child) {
1618 checkThread();
1619 if (mView == child) {
1620 mAttachInfo.mRecomputeGlobalAttributes = true;
1621 if (!mWillDrawSoon) {
1622 scheduleTraversals();
1623 }
1624 }
1625 }
1626
1627 void dispatchDetachedFromWindow() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001628 if (mView != null) {
1629 mView.dispatchDetachedFromWindow();
1630 }
1631
1632 mView = null;
1633 mAttachInfo.mRootView = null;
Mathias Agopian5583dc62009-07-09 16:28:11 -07001634 mAttachInfo.mSurface = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001635
Romain Guy29d89972010-09-22 16:10:57 -07001636 destroyHardwareRenderer();
Romain Guy4caa4ed2010-08-25 14:46:24 -07001637
Dianne Hackborn0586a1b2009-09-06 21:08:27 -07001638 mSurface.release();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001639
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001640 if (mInputChannel != null) {
1641 if (mInputQueueCallback != null) {
1642 mInputQueueCallback.onInputQueueDestroyed(mInputQueue);
1643 mInputQueueCallback = null;
1644 } else {
1645 InputQueue.unregisterInputChannel(mInputChannel);
Jeff Brown46b9ac02010-04-22 18:58:52 -07001646 }
1647 }
1648
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001649 try {
1650 sWindowSession.remove(mWindow);
1651 } catch (RemoteException e) {
1652 }
Jeff Brown349703e2010-06-22 01:27:15 -07001653
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001654 // Dispose the input channel after removing the window so the Window Manager
1655 // doesn't interpret the input channel being closed as an abnormal termination.
1656 if (mInputChannel != null) {
1657 mInputChannel.dispose();
1658 mInputChannel = null;
Jeff Brown349703e2010-06-22 01:27:15 -07001659 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001660 }
Romain Guy8506ab42009-06-11 17:35:47 -07001661
Dianne Hackborn694f79b2010-03-17 19:44:59 -07001662 void updateConfiguration(Configuration config, boolean force) {
1663 if (DEBUG_CONFIGURATION) Log.v(TAG,
1664 "Applying new config to window "
1665 + mWindowAttributes.getTitle()
1666 + ": " + config);
1667 synchronized (sConfigCallbacks) {
1668 for (int i=sConfigCallbacks.size()-1; i>=0; i--) {
1669 sConfigCallbacks.get(i).onConfigurationChanged(config);
1670 }
1671 }
1672 if (mView != null) {
1673 // At this point the resources have been updated to
1674 // have the most recent config, whatever that is. Use
1675 // the on in them which may be newer.
1676 if (mView != null) {
1677 config = mView.getResources().getConfiguration();
1678 }
1679 if (force || mLastConfiguration.diff(config) != 0) {
1680 mLastConfiguration.setTo(config);
1681 mView.dispatchConfigurationChanged(config);
1682 }
1683 }
1684 }
1685
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001686 /**
1687 * Return true if child is an ancestor of parent, (or equal to the parent).
1688 */
1689 private static boolean isViewDescendantOf(View child, View parent) {
1690 if (child == parent) {
1691 return true;
1692 }
1693
1694 final ViewParent theParent = child.getParent();
1695 return (theParent instanceof ViewGroup) && isViewDescendantOf((View) theParent, parent);
1696 }
1697
Romain Guycdb86672010-03-18 18:54:50 -07001698 private static void forceLayout(View view) {
1699 view.forceLayout();
1700 if (view instanceof ViewGroup) {
1701 ViewGroup group = (ViewGroup) view;
1702 final int count = group.getChildCount();
1703 for (int i = 0; i < count; i++) {
1704 forceLayout(group.getChildAt(i));
1705 }
1706 }
1707 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001708
1709 public final static int DO_TRAVERSAL = 1000;
1710 public final static int DIE = 1001;
1711 public final static int RESIZED = 1002;
1712 public final static int RESIZED_REPORT = 1003;
1713 public final static int WINDOW_FOCUS_CHANGED = 1004;
1714 public final static int DISPATCH_KEY = 1005;
1715 public final static int DISPATCH_POINTER = 1006;
1716 public final static int DISPATCH_TRACKBALL = 1007;
1717 public final static int DISPATCH_APP_VISIBILITY = 1008;
1718 public final static int DISPATCH_GET_NEW_SURFACE = 1009;
1719 public final static int FINISHED_EVENT = 1010;
1720 public final static int DISPATCH_KEY_FROM_IME = 1011;
1721 public final static int FINISH_INPUT_CONNECTION = 1012;
1722 public final static int CHECK_FOCUS = 1013;
Dianne Hackbornffa42482009-09-23 22:20:11 -07001723 public final static int CLOSE_SYSTEM_DIALOGS = 1014;
Christopher Tatea53146c2010-09-07 11:57:52 -07001724 public final static int DISPATCH_DRAG_EVENT = 1015;
Chris Tate91e9bb32010-10-12 12:58:43 -07001725 public final static int DISPATCH_DRAG_LOCATION_EVENT = 1016;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001726
1727 @Override
1728 public void handleMessage(Message msg) {
1729 switch (msg.what) {
1730 case View.AttachInfo.INVALIDATE_MSG:
1731 ((View) msg.obj).invalidate();
1732 break;
1733 case View.AttachInfo.INVALIDATE_RECT_MSG:
1734 final View.AttachInfo.InvalidateInfo info = (View.AttachInfo.InvalidateInfo) msg.obj;
1735 info.target.invalidate(info.left, info.top, info.right, info.bottom);
1736 info.release();
1737 break;
1738 case DO_TRAVERSAL:
1739 if (mProfile) {
1740 Debug.startMethodTracing("ViewRoot");
1741 }
1742
1743 performTraversals();
1744
1745 if (mProfile) {
1746 Debug.stopMethodTracing();
1747 mProfile = false;
1748 }
1749 break;
1750 case FINISHED_EVENT:
1751 handleFinishedEvent(msg.arg1, msg.arg2 != 0);
1752 break;
1753 case DISPATCH_KEY:
Jeff Brown92ff1dd2010-08-11 16:16:06 -07001754 deliverKeyEvent((KeyEvent)msg.obj, msg.arg1 != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001755 break;
Jeff Brown3915bb82010-11-05 15:02:16 -07001756 case DISPATCH_POINTER:
1757 deliverPointerEvent((MotionEvent) msg.obj, msg.arg1 != 0);
1758 break;
1759 case DISPATCH_TRACKBALL:
1760 deliverTrackballEvent((MotionEvent) msg.obj, msg.arg1 != 0);
1761 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001762 case DISPATCH_APP_VISIBILITY:
1763 handleAppVisibility(msg.arg1 != 0);
1764 break;
1765 case DISPATCH_GET_NEW_SURFACE:
1766 handleGetNewSurface();
1767 break;
1768 case RESIZED:
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001769 ResizedInfo ri = (ResizedInfo)msg.obj;
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001770
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001771 if (mWinFrame.width() == msg.arg1 && mWinFrame.height() == msg.arg2
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001772 && mPendingContentInsets.equals(ri.coveredInsets)
Dianne Hackbornd49258f2010-03-26 00:44:29 -07001773 && mPendingVisibleInsets.equals(ri.visibleInsets)
1774 && ((ResizedInfo)msg.obj).newConfig == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001775 break;
1776 }
1777 // fall through...
1778 case RESIZED_REPORT:
1779 if (mAdded) {
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001780 Configuration config = ((ResizedInfo)msg.obj).newConfig;
1781 if (config != null) {
Dianne Hackborn694f79b2010-03-17 19:44:59 -07001782 updateConfiguration(config, false);
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001783 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001784 mWinFrame.left = 0;
1785 mWinFrame.right = msg.arg1;
1786 mWinFrame.top = 0;
1787 mWinFrame.bottom = msg.arg2;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001788 mPendingContentInsets.set(((ResizedInfo)msg.obj).coveredInsets);
1789 mPendingVisibleInsets.set(((ResizedInfo)msg.obj).visibleInsets);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001790 if (msg.what == RESIZED_REPORT) {
1791 mReportNextDraw = true;
1792 }
Romain Guycdb86672010-03-18 18:54:50 -07001793
1794 if (mView != null) {
1795 forceLayout(mView);
1796 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001797 requestLayout();
1798 }
1799 break;
1800 case WINDOW_FOCUS_CHANGED: {
1801 if (mAdded) {
1802 boolean hasWindowFocus = msg.arg1 != 0;
1803 mAttachInfo.mHasWindowFocus = hasWindowFocus;
1804 if (hasWindowFocus) {
1805 boolean inTouchMode = msg.arg2 != 0;
Romain Guy2d4cff62010-04-09 15:39:00 -07001806 ensureTouchModeLocally(inTouchMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001807
Romain Guyc361da82010-10-25 15:29:10 -07001808 if (mAttachInfo.mHardwareRenderer != null &&
1809 mSurface != null && mSurface.isValid()) {
Romain Guyb051e892010-09-28 19:09:36 -07001810 mAttachInfo.mHardwareRenderer.initializeIfNeeded(mWidth, mHeight,
1811 mAttachInfo, mHolder);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001812 }
1813 }
Romain Guy8506ab42009-06-11 17:35:47 -07001814
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001815 mLastWasImTarget = WindowManager.LayoutParams
1816 .mayUseInputMethod(mWindowAttributes.flags);
Romain Guy8506ab42009-06-11 17:35:47 -07001817
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001818 InputMethodManager imm = InputMethodManager.peekInstance();
1819 if (mView != null) {
1820 if (hasWindowFocus && imm != null && mLastWasImTarget) {
1821 imm.startGettingWindowFocus(mView);
1822 }
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07001823 mAttachInfo.mKeyDispatchState.reset();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001824 mView.dispatchWindowFocusChanged(hasWindowFocus);
1825 }
svetoslavganov75986cf2009-05-14 22:28:01 -07001826
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001827 // Note: must be done after the focus change callbacks,
1828 // so all of the view state is set up correctly.
1829 if (hasWindowFocus) {
1830 if (imm != null && mLastWasImTarget) {
1831 imm.onWindowFocus(mView, mView.findFocus(),
1832 mWindowAttributes.softInputMode,
1833 !mHasHadWindowFocus, mWindowAttributes.flags);
1834 }
1835 // Clear the forward bit. We can just do this directly, since
1836 // the window manager doesn't care about it.
1837 mWindowAttributes.softInputMode &=
1838 ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
1839 ((WindowManager.LayoutParams)mView.getLayoutParams())
1840 .softInputMode &=
1841 ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
1842 mHasHadWindowFocus = true;
1843 }
svetoslavganov75986cf2009-05-14 22:28:01 -07001844
1845 if (hasWindowFocus && mView != null) {
1846 sendAccessibilityEvents();
1847 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001848 }
1849 } break;
1850 case DIE:
Dianne Hackborn94d69142009-09-28 22:14:42 -07001851 doDie();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001852 break;
The Android Open Source Project10592532009-03-18 17:39:46 -07001853 case DISPATCH_KEY_FROM_IME: {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001854 if (LOCAL_LOGV) Log.v(
Jeff Brownc5ed5912010-07-14 18:48:53 -07001855 TAG, "Dispatching key "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001856 + msg.obj + " from IME to " + mView);
The Android Open Source Project10592532009-03-18 17:39:46 -07001857 KeyEvent event = (KeyEvent)msg.obj;
1858 if ((event.getFlags()&KeyEvent.FLAG_FROM_SYSTEM) != 0) {
1859 // The IME is trying to say this event is from the
1860 // system! Bad bad bad!
Romain Guy812ccbe2010-06-01 14:07:24 -07001861 event = KeyEvent.changeFlags(event, event.getFlags() & ~KeyEvent.FLAG_FROM_SYSTEM);
The Android Open Source Project10592532009-03-18 17:39:46 -07001862 }
Jeff Brown3915bb82010-11-05 15:02:16 -07001863 deliverKeyEventPostIme((KeyEvent)msg.obj, false);
The Android Open Source Project10592532009-03-18 17:39:46 -07001864 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001865 case FINISH_INPUT_CONNECTION: {
1866 InputMethodManager imm = InputMethodManager.peekInstance();
1867 if (imm != null) {
1868 imm.reportFinishInputConnection((InputConnection)msg.obj);
1869 }
1870 } break;
1871 case CHECK_FOCUS: {
1872 InputMethodManager imm = InputMethodManager.peekInstance();
1873 if (imm != null) {
1874 imm.checkFocus();
1875 }
1876 } break;
Dianne Hackbornffa42482009-09-23 22:20:11 -07001877 case CLOSE_SYSTEM_DIALOGS: {
1878 if (mView != null) {
1879 mView.onCloseSystemDialogs((String)msg.obj);
1880 }
1881 } break;
Chris Tate91e9bb32010-10-12 12:58:43 -07001882 case DISPATCH_DRAG_EVENT:
1883 case DISPATCH_DRAG_LOCATION_EVENT: {
Christopher Tatea53146c2010-09-07 11:57:52 -07001884 handleDragEvent((DragEvent)msg.obj);
1885 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001886 }
1887 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07001888
Jeff Brown3915bb82010-11-05 15:02:16 -07001889 private void startInputEvent(InputQueue.FinishedCallback finishedCallback) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07001890 if (mFinishedCallback != null) {
1891 Slog.w(TAG, "Received a new input event from the input queue but there is "
1892 + "already an unfinished input event in progress.");
1893 }
1894
1895 mFinishedCallback = finishedCallback;
1896 }
1897
Jeff Brown3915bb82010-11-05 15:02:16 -07001898 private void finishInputEvent(boolean handled) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07001899 if (LOCAL_LOGV) Log.v(TAG, "Telling window manager input event is finished");
Jeff Brown92ff1dd2010-08-11 16:16:06 -07001900
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001901 if (mFinishedCallback != null) {
Jeff Brown3915bb82010-11-05 15:02:16 -07001902 mFinishedCallback.finished(handled);
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001903 mFinishedCallback = null;
Jeff Brown92ff1dd2010-08-11 16:16:06 -07001904 } else {
Jeff Brown93ed4e32010-09-23 13:51:48 -07001905 Slog.w(TAG, "Attempted to tell the input queue that the current input event "
1906 + "is finished but there is no input event actually in progress.");
Jeff Brown46b9ac02010-04-22 18:58:52 -07001907 }
1908 }
1909
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001910 /**
1911 * Something in the current window tells us we need to change the touch mode. For
1912 * example, we are not in touch mode, and the user touches the screen.
1913 *
1914 * If the touch mode has changed, tell the window manager, and handle it locally.
1915 *
1916 * @param inTouchMode Whether we want to be in touch mode.
1917 * @return True if the touch mode changed and focus changed was changed as a result
1918 */
1919 boolean ensureTouchMode(boolean inTouchMode) {
1920 if (DBG) Log.d("touchmode", "ensureTouchMode(" + inTouchMode + "), current "
1921 + "touch mode is " + mAttachInfo.mInTouchMode);
1922 if (mAttachInfo.mInTouchMode == inTouchMode) return false;
1923
1924 // tell the window manager
1925 try {
1926 sWindowSession.setInTouchMode(inTouchMode);
1927 } catch (RemoteException e) {
1928 throw new RuntimeException(e);
1929 }
1930
1931 // handle the change
Romain Guy2d4cff62010-04-09 15:39:00 -07001932 return ensureTouchModeLocally(inTouchMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001933 }
1934
1935 /**
1936 * Ensure that the touch mode for this window is set, and if it is changing,
1937 * take the appropriate action.
1938 * @param inTouchMode Whether we want to be in touch mode.
1939 * @return True if the touch mode changed and focus changed was changed as a result
1940 */
Romain Guy2d4cff62010-04-09 15:39:00 -07001941 private boolean ensureTouchModeLocally(boolean inTouchMode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001942 if (DBG) Log.d("touchmode", "ensureTouchModeLocally(" + inTouchMode + "), current "
1943 + "touch mode is " + mAttachInfo.mInTouchMode);
1944
1945 if (mAttachInfo.mInTouchMode == inTouchMode) return false;
1946
1947 mAttachInfo.mInTouchMode = inTouchMode;
1948 mAttachInfo.mTreeObserver.dispatchOnTouchModeChanged(inTouchMode);
1949
Romain Guy2d4cff62010-04-09 15:39:00 -07001950 return (inTouchMode) ? enterTouchMode() : leaveTouchMode();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001951 }
1952
1953 private boolean enterTouchMode() {
1954 if (mView != null) {
1955 if (mView.hasFocus()) {
1956 // note: not relying on mFocusedView here because this could
1957 // be when the window is first being added, and mFocused isn't
1958 // set yet.
1959 final View focused = mView.findFocus();
1960 if (focused != null && !focused.isFocusableInTouchMode()) {
1961
1962 final ViewGroup ancestorToTakeFocus =
1963 findAncestorToTakeFocusInTouchMode(focused);
1964 if (ancestorToTakeFocus != null) {
1965 // there is an ancestor that wants focus after its descendants that
1966 // is focusable in touch mode.. give it focus
1967 return ancestorToTakeFocus.requestFocus();
1968 } else {
1969 // nothing appropriate to have focus in touch mode, clear it out
1970 mView.unFocus();
1971 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(focused, null);
1972 mFocusedView = null;
1973 return true;
1974 }
1975 }
1976 }
1977 }
1978 return false;
1979 }
1980
1981
1982 /**
1983 * Find an ancestor of focused that wants focus after its descendants and is
1984 * focusable in touch mode.
1985 * @param focused The currently focused view.
1986 * @return An appropriate view, or null if no such view exists.
1987 */
1988 private ViewGroup findAncestorToTakeFocusInTouchMode(View focused) {
1989 ViewParent parent = focused.getParent();
1990 while (parent instanceof ViewGroup) {
1991 final ViewGroup vgParent = (ViewGroup) parent;
1992 if (vgParent.getDescendantFocusability() == ViewGroup.FOCUS_AFTER_DESCENDANTS
1993 && vgParent.isFocusableInTouchMode()) {
1994 return vgParent;
1995 }
1996 if (vgParent.isRootNamespace()) {
1997 return null;
1998 } else {
1999 parent = vgParent.getParent();
2000 }
2001 }
2002 return null;
2003 }
2004
2005 private boolean leaveTouchMode() {
2006 if (mView != null) {
2007 if (mView.hasFocus()) {
2008 // i learned the hard way to not trust mFocusedView :)
2009 mFocusedView = mView.findFocus();
2010 if (!(mFocusedView instanceof ViewGroup)) {
2011 // some view has focus, let it keep it
2012 return false;
2013 } else if (((ViewGroup)mFocusedView).getDescendantFocusability() !=
2014 ViewGroup.FOCUS_AFTER_DESCENDANTS) {
2015 // some view group has focus, and doesn't prefer its children
2016 // over itself for focus, so let them keep it.
2017 return false;
2018 }
2019 }
2020
2021 // find the best view to give focus to in this brave new non-touch-mode
2022 // world
2023 final View focused = focusSearch(null, View.FOCUS_DOWN);
2024 if (focused != null) {
2025 return focused.requestFocus(View.FOCUS_DOWN);
2026 }
2027 }
2028 return false;
2029 }
2030
Jeff Brown3915bb82010-11-05 15:02:16 -07002031 private void deliverPointerEvent(MotionEvent event, boolean sendDone) {
2032 // If there is no view, then the event will not be handled.
2033 if (mView == null || !mAdded) {
2034 finishPointerEvent(event, sendDone, false);
2035 return;
2036 }
2037
2038 // Translate the pointer event for compatibility, if needed.
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002039 if (mTranslator != null) {
2040 mTranslator.translateEventInScreenToAppWindow(event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002041 }
2042
Jeff Brown3915bb82010-11-05 15:02:16 -07002043 // Enter touch mode on the down.
2044 boolean isDown = event.getAction() == MotionEvent.ACTION_DOWN;
2045 if (isDown) {
2046 ensureTouchMode(true);
2047 }
2048 if(Config.LOGV) {
2049 captureMotionLog("captureDispatchPointer", event);
2050 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002051
Jeff Brown3915bb82010-11-05 15:02:16 -07002052 // Offset the scroll position.
2053 if (mCurScrollY != 0) {
2054 event.offsetLocation(0, mCurScrollY);
2055 }
2056 if (MEASURE_LATENCY) {
2057 lt.sample("A Dispatching TouchEvents", System.nanoTime() - event.getEventTimeNano());
2058 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002059
Jeff Brown3915bb82010-11-05 15:02:16 -07002060 // Remember the touch position for possible drag-initiation.
2061 mLastTouchPoint.x = event.getRawX();
2062 mLastTouchPoint.y = event.getRawY();
2063
2064 // Dispatch touch to view hierarchy.
2065 boolean handled = mView.dispatchTouchEvent(event);
2066 if (MEASURE_LATENCY) {
2067 lt.sample("B Dispatched TouchEvents ", System.nanoTime() - event.getEventTimeNano());
2068 }
2069 if (handled) {
2070 finishPointerEvent(event, sendDone, true);
2071 return;
2072 }
2073
2074 // Apply edge slop and try again, if appropriate.
2075 final int edgeFlags = event.getEdgeFlags();
2076 if (edgeFlags != 0 && mView instanceof ViewGroup) {
2077 final int edgeSlop = mViewConfiguration.getScaledEdgeSlop();
2078 int direction = View.FOCUS_UP;
2079 int x = (int)event.getX();
2080 int y = (int)event.getY();
2081 final int[] deltas = new int[2];
2082
2083 if ((edgeFlags & MotionEvent.EDGE_TOP) != 0) {
2084 direction = View.FOCUS_DOWN;
2085 if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
2086 deltas[0] = edgeSlop;
2087 x += edgeSlop;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002088 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
Jeff Brown3915bb82010-11-05 15:02:16 -07002089 deltas[0] = -edgeSlop;
2090 x -= edgeSlop;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002091 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002092 } else if ((edgeFlags & MotionEvent.EDGE_BOTTOM) != 0) {
2093 direction = View.FOCUS_UP;
2094 if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
2095 deltas[0] = edgeSlop;
2096 x += edgeSlop;
2097 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
2098 deltas[0] = -edgeSlop;
2099 x -= edgeSlop;
2100 }
2101 } else if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
2102 direction = View.FOCUS_RIGHT;
2103 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
2104 direction = View.FOCUS_LEFT;
2105 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002106
Jeff Brown3915bb82010-11-05 15:02:16 -07002107 View nearest = FocusFinder.getInstance().findNearestTouchable(
2108 ((ViewGroup) mView), x, y, direction, deltas);
2109 if (nearest != null) {
2110 event.offsetLocation(deltas[0], deltas[1]);
2111 event.setEdgeFlags(0);
2112 if (mView.dispatchTouchEvent(event)) {
2113 finishPointerEvent(event, sendDone, true);
2114 return;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002115 }
2116 }
2117 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002118
2119 // Pointer event was unhandled.
2120 finishPointerEvent(event, sendDone, false);
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002121 }
2122
Jeff Brown3915bb82010-11-05 15:02:16 -07002123 private void finishPointerEvent(MotionEvent event, boolean sendDone, boolean handled) {
2124 event.recycle();
2125 if (sendDone) {
2126 finishInputEvent(handled);
2127 }
2128 if (LOCAL_LOGV || WATCH_POINTER) Log.i(TAG, "Done dispatching!");
2129 }
2130
2131 private void deliverTrackballEvent(MotionEvent event, boolean sendDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002132 if (DEBUG_TRACKBALL) Log.v(TAG, "Motion event:" + event);
2133
Jeff Brown3915bb82010-11-05 15:02:16 -07002134 // If there is no view, then the event will not be handled.
2135 if (mView == null || !mAdded) {
2136 finishTrackballEvent(event, sendDone, false);
2137 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002138 }
2139
Jeff Brown3915bb82010-11-05 15:02:16 -07002140 // Deliver the trackball event to the view.
2141 if (mView.dispatchTrackballEvent(event)) {
2142 // If we reach this, we delivered a trackball event to mView and
2143 // mView consumed it. Because we will not translate the trackball
2144 // event into a key event, touch mode will not exit, so we exit
2145 // touch mode here.
2146 ensureTouchMode(false);
2147
2148 finishTrackballEvent(event, sendDone, true);
2149 mLastTrackballTime = Integer.MIN_VALUE;
2150 return;
2151 }
2152
2153 // Translate the trackball event into DPAD keys and try to deliver those.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002154 final TrackballAxis x = mTrackballAxisX;
2155 final TrackballAxis y = mTrackballAxisY;
2156
2157 long curTime = SystemClock.uptimeMillis();
Jeff Brown3915bb82010-11-05 15:02:16 -07002158 if ((mLastTrackballTime + MAX_TRACKBALL_DELAY) < curTime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002159 // It has been too long since the last movement,
2160 // so restart at the beginning.
2161 x.reset(0);
2162 y.reset(0);
2163 mLastTrackballTime = curTime;
2164 }
2165
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002166 final int action = event.getAction();
2167 final int metastate = event.getMetaState();
2168 switch (action) {
2169 case MotionEvent.ACTION_DOWN:
2170 x.reset(2);
2171 y.reset(2);
2172 deliverKeyEvent(new KeyEvent(curTime, curTime,
2173 KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_CENTER,
2174 0, metastate), false);
2175 break;
2176 case MotionEvent.ACTION_UP:
2177 x.reset(2);
2178 y.reset(2);
2179 deliverKeyEvent(new KeyEvent(curTime, curTime,
2180 KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_CENTER,
2181 0, metastate), false);
2182 break;
2183 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002184
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002185 if (DEBUG_TRACKBALL) Log.v(TAG, "TB X=" + x.position + " step="
2186 + x.step + " dir=" + x.dir + " acc=" + x.acceleration
2187 + " move=" + event.getX()
2188 + " / Y=" + y.position + " step="
2189 + y.step + " dir=" + y.dir + " acc=" + y.acceleration
2190 + " move=" + event.getY());
2191 final float xOff = x.collect(event.getX(), event.getEventTime(), "X");
2192 final float yOff = y.collect(event.getY(), event.getEventTime(), "Y");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002193
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002194 // Generate DPAD events based on the trackball movement.
2195 // We pick the axis that has moved the most as the direction of
2196 // the DPAD. When we generate DPAD events for one axis, then the
2197 // other axis is reset -- we don't want to perform DPAD jumps due
2198 // to slight movements in the trackball when making major movements
2199 // along the other axis.
2200 int keycode = 0;
2201 int movement = 0;
2202 float accel = 1;
2203 if (xOff > yOff) {
2204 movement = x.generate((2/event.getXPrecision()));
2205 if (movement != 0) {
2206 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_RIGHT
2207 : KeyEvent.KEYCODE_DPAD_LEFT;
2208 accel = x.acceleration;
2209 y.reset(2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002210 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002211 } else if (yOff > 0) {
2212 movement = y.generate((2/event.getYPrecision()));
2213 if (movement != 0) {
2214 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_DOWN
2215 : KeyEvent.KEYCODE_DPAD_UP;
2216 accel = y.acceleration;
2217 x.reset(2);
2218 }
2219 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002220
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002221 if (keycode != 0) {
2222 if (movement < 0) movement = -movement;
2223 int accelMovement = (int)(movement * accel);
2224 if (DEBUG_TRACKBALL) Log.v(TAG, "Move: movement=" + movement
2225 + " accelMovement=" + accelMovement
2226 + " accel=" + accel);
2227 if (accelMovement > movement) {
2228 if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: "
2229 + keycode);
2230 movement--;
2231 deliverKeyEvent(new KeyEvent(curTime, curTime,
2232 KeyEvent.ACTION_MULTIPLE, keycode,
2233 accelMovement-movement, metastate), false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002234 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002235 while (movement > 0) {
2236 if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: "
2237 + keycode);
2238 movement--;
2239 curTime = SystemClock.uptimeMillis();
2240 deliverKeyEvent(new KeyEvent(curTime, curTime,
2241 KeyEvent.ACTION_DOWN, keycode, 0, event.getMetaState()), false);
2242 deliverKeyEvent(new KeyEvent(curTime, curTime,
2243 KeyEvent.ACTION_UP, keycode, 0, metastate), false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002244 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002245 mLastTrackballTime = curTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002246 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002247
2248 // Unfortunately we can't tell whether the application consumed the keys, so
2249 // we always consider the trackball event handled.
2250 finishTrackballEvent(event, sendDone, true);
2251 }
2252
2253 private void finishTrackballEvent(MotionEvent event, boolean sendDone, boolean handled) {
2254 event.recycle();
2255 if (sendDone) {
2256 finishInputEvent(handled);
2257 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002258 }
2259
2260 /**
2261 * @param keyCode The key code
2262 * @return True if the key is directional.
2263 */
2264 static boolean isDirectional(int keyCode) {
2265 switch (keyCode) {
2266 case KeyEvent.KEYCODE_DPAD_LEFT:
2267 case KeyEvent.KEYCODE_DPAD_RIGHT:
2268 case KeyEvent.KEYCODE_DPAD_UP:
2269 case KeyEvent.KEYCODE_DPAD_DOWN:
2270 return true;
2271 }
2272 return false;
2273 }
2274
2275 /**
2276 * Returns true if this key is a keyboard key.
2277 * @param keyEvent The key event.
2278 * @return whether this key is a keyboard key.
2279 */
2280 private static boolean isKeyboardKey(KeyEvent keyEvent) {
2281 final int convertedKey = keyEvent.getUnicodeChar();
2282 return convertedKey > 0;
2283 }
2284
2285
2286
2287 /**
2288 * See if the key event means we should leave touch mode (and leave touch
2289 * mode if so).
2290 * @param event The key event.
2291 * @return Whether this key event should be consumed (meaning the act of
2292 * leaving touch mode alone is considered the event).
2293 */
2294 private boolean checkForLeavingTouchModeAndConsume(KeyEvent event) {
Adam Powell51a6bee2010-03-15 14:07:28 -07002295 final int action = event.getAction();
2296 if (action != KeyEvent.ACTION_DOWN && action != KeyEvent.ACTION_MULTIPLE) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002297 return false;
2298 }
2299 if ((event.getFlags()&KeyEvent.FLAG_KEEP_TOUCH_MODE) != 0) {
2300 return false;
2301 }
2302
2303 // only relevant if we are in touch mode
2304 if (!mAttachInfo.mInTouchMode) {
2305 return false;
2306 }
2307
2308 // if something like an edit text has focus and the user is typing,
2309 // leave touch mode
2310 //
2311 // note: the condition of not being a keyboard key is kind of a hacky
2312 // approximation of whether we think the focused view will want the
2313 // key; if we knew for sure whether the focused view would consume
2314 // the event, that would be better.
2315 if (isKeyboardKey(event) && mView != null && mView.hasFocus()) {
2316 mFocusedView = mView.findFocus();
2317 if ((mFocusedView instanceof ViewGroup)
2318 && ((ViewGroup) mFocusedView).getDescendantFocusability() ==
2319 ViewGroup.FOCUS_AFTER_DESCENDANTS) {
2320 // something has focus, but is holding it weakly as a container
2321 return false;
2322 }
2323 if (ensureTouchMode(false)) {
2324 throw new IllegalStateException("should not have changed focus "
2325 + "when leaving touch mode while a view has focus.");
2326 }
2327 return false;
2328 }
2329
2330 if (isDirectional(event.getKeyCode())) {
2331 // no view has focus, so we leave touch mode (and find something
2332 // to give focus to). the event is consumed if we were able to
2333 // find something to give focus to.
2334 return ensureTouchMode(false);
2335 }
2336 return false;
2337 }
2338
2339 /**
Romain Guy8506ab42009-06-11 17:35:47 -07002340 * log motion events
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002341 */
2342 private static void captureMotionLog(String subTag, MotionEvent ev) {
Romain Guy8506ab42009-06-11 17:35:47 -07002343 //check dynamic switch
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002344 if (ev == null ||
2345 SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_EVENT, 0) == 0) {
2346 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002347 }
Romain Guy8506ab42009-06-11 17:35:47 -07002348
2349 StringBuilder sb = new StringBuilder(subTag + ": ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002350 sb.append(ev.getDownTime()).append(',');
2351 sb.append(ev.getEventTime()).append(',');
2352 sb.append(ev.getAction()).append(',');
Romain Guy8506ab42009-06-11 17:35:47 -07002353 sb.append(ev.getX()).append(',');
2354 sb.append(ev.getY()).append(',');
2355 sb.append(ev.getPressure()).append(',');
2356 sb.append(ev.getSize()).append(',');
2357 sb.append(ev.getMetaState()).append(',');
2358 sb.append(ev.getXPrecision()).append(',');
2359 sb.append(ev.getYPrecision()).append(',');
2360 sb.append(ev.getDeviceId()).append(',');
2361 sb.append(ev.getEdgeFlags());
2362 Log.d(TAG, sb.toString());
2363 }
2364 /**
2365 * log motion events
2366 */
2367 private static void captureKeyLog(String subTag, KeyEvent ev) {
2368 //check dynamic switch
2369 if (ev == null ||
2370 SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_EVENT, 0) == 0) {
2371 return;
2372 }
2373 StringBuilder sb = new StringBuilder(subTag + ": ");
2374 sb.append(ev.getDownTime()).append(',');
2375 sb.append(ev.getEventTime()).append(',');
2376 sb.append(ev.getAction()).append(',');
2377 sb.append(ev.getKeyCode()).append(',');
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002378 sb.append(ev.getRepeatCount()).append(',');
2379 sb.append(ev.getMetaState()).append(',');
2380 sb.append(ev.getDeviceId()).append(',');
2381 sb.append(ev.getScanCode());
Romain Guy8506ab42009-06-11 17:35:47 -07002382 Log.d(TAG, sb.toString());
2383 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002384
2385 int enqueuePendingEvent(Object event, boolean sendDone) {
2386 int seq = mPendingEventSeq+1;
2387 if (seq < 0) seq = 0;
2388 mPendingEventSeq = seq;
2389 mPendingEvents.put(seq, event);
2390 return sendDone ? seq : -seq;
2391 }
2392
2393 Object retrievePendingEvent(int seq) {
2394 if (seq < 0) seq = -seq;
2395 Object event = mPendingEvents.get(seq);
2396 if (event != null) {
2397 mPendingEvents.remove(seq);
2398 }
2399 return event;
2400 }
Romain Guy8506ab42009-06-11 17:35:47 -07002401
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002402 private void deliverKeyEvent(KeyEvent event, boolean sendDone) {
Jeff Brown3915bb82010-11-05 15:02:16 -07002403 // If there is no view, then the event will not be handled.
2404 if (mView == null || !mAdded) {
2405 finishKeyEvent(event, sendDone, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002406 return;
2407 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002408
2409 if (LOCAL_LOGV) Log.v(TAG, "Dispatching key " + event + " to " + mView);
2410
2411 // Perform predispatching before the IME.
2412 if (mView.dispatchKeyEventPreIme(event)) {
2413 finishKeyEvent(event, sendDone, true);
2414 return;
2415 }
2416
2417 // Dispatch to the IME before propagating down the view hierarchy.
2418 // The IME will eventually call back into handleFinishedEvent.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002419 if (mLastWasImTarget) {
2420 InputMethodManager imm = InputMethodManager.peekInstance();
Jeff Brown3915bb82010-11-05 15:02:16 -07002421 if (imm != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002422 int seq = enqueuePendingEvent(event, sendDone);
2423 if (DEBUG_IMF) Log.v(TAG, "Sending key event to IME: seq="
2424 + seq + " event=" + event);
Jeff Brown3915bb82010-11-05 15:02:16 -07002425 imm.dispatchKeyEvent(mView.getContext(), seq, event, mInputMethodCallback);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002426 return;
2427 }
2428 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002429
2430 // Not dispatching to IME, continue with post IME actions.
2431 deliverKeyEventPostIme(event, sendDone);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002432 }
2433
Jeff Brown3915bb82010-11-05 15:02:16 -07002434 private void handleFinishedEvent(int seq, boolean handled) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002435 final KeyEvent event = (KeyEvent)retrievePendingEvent(seq);
2436 if (DEBUG_IMF) Log.v(TAG, "IME finished event: seq=" + seq
2437 + " handled=" + handled + " event=" + event);
2438 if (event != null) {
2439 final boolean sendDone = seq >= 0;
Jeff Brown3915bb82010-11-05 15:02:16 -07002440 if (handled) {
2441 finishKeyEvent(event, sendDone, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002442 } else {
Jeff Brown3915bb82010-11-05 15:02:16 -07002443 deliverKeyEventPostIme(event, sendDone);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002444 }
2445 }
2446 }
Romain Guy8506ab42009-06-11 17:35:47 -07002447
Jeff Brown3915bb82010-11-05 15:02:16 -07002448 private void deliverKeyEventPostIme(KeyEvent event, boolean sendDone) {
2449 // If the view went away, then the event will not be handled.
2450 if (mView == null || !mAdded) {
2451 finishKeyEvent(event, sendDone, false);
2452 return;
2453 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002454
Jeff Brown3915bb82010-11-05 15:02:16 -07002455 // If the key's purpose is to exit touch mode then we consume it and consider it handled.
2456 if (checkForLeavingTouchModeAndConsume(event)) {
2457 finishKeyEvent(event, sendDone, true);
2458 return;
2459 }
Romain Guy8506ab42009-06-11 17:35:47 -07002460
Jeff Brown3915bb82010-11-05 15:02:16 -07002461 if (Config.LOGV) {
2462 captureKeyLog("captureDispatchKeyEvent", event);
2463 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002464
Jeff Brown3915bb82010-11-05 15:02:16 -07002465 // Deliver the key to the view hierarchy.
2466 if (mView.dispatchKeyEvent(event)) {
2467 finishKeyEvent(event, sendDone, true);
2468 return;
2469 }
Joe Onorato86f67862010-11-05 18:57:34 -07002470
Jeff Brown3915bb82010-11-05 15:02:16 -07002471 // Apply the fallback event policy.
2472 if (mFallbackEventHandler.dispatchKeyEvent(event)) {
2473 finishKeyEvent(event, sendDone, true);
2474 return;
2475 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002476
Jeff Brown3915bb82010-11-05 15:02:16 -07002477 // Handle automatic focus changes.
2478 if (event.getAction() == KeyEvent.ACTION_DOWN) {
2479 int direction = 0;
2480 switch (event.getKeyCode()) {
2481 case KeyEvent.KEYCODE_DPAD_LEFT:
2482 direction = View.FOCUS_LEFT;
2483 break;
2484 case KeyEvent.KEYCODE_DPAD_RIGHT:
2485 direction = View.FOCUS_RIGHT;
2486 break;
2487 case KeyEvent.KEYCODE_DPAD_UP:
2488 direction = View.FOCUS_UP;
2489 break;
2490 case KeyEvent.KEYCODE_DPAD_DOWN:
2491 direction = View.FOCUS_DOWN;
2492 break;
2493 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002494
Jeff Brown3915bb82010-11-05 15:02:16 -07002495 if (direction != 0) {
2496 View focused = mView != null ? mView.findFocus() : null;
2497 if (focused != null) {
2498 View v = focused.focusSearch(direction);
2499 if (v != null && v != focused) {
2500 // do the math the get the interesting rect
2501 // of previous focused into the coord system of
2502 // newly focused view
2503 focused.getFocusedRect(mTempRect);
2504 if (mView instanceof ViewGroup) {
2505 ((ViewGroup) mView).offsetDescendantRectToMyCoords(
2506 focused, mTempRect);
2507 ((ViewGroup) mView).offsetRectIntoDescendantCoords(
2508 v, mTempRect);
2509 }
2510 if (v.requestFocus(direction, mTempRect)) {
2511 playSoundEffect(
2512 SoundEffectConstants.getContantForFocusDirection(direction));
2513 finishKeyEvent(event, sendDone, true);
2514 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002515 }
2516 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002517
2518 // Give the focused view a last chance to handle the dpad key.
2519 if (mView.dispatchUnhandledMove(focused, direction)) {
2520 finishKeyEvent(event, sendDone, true);
2521 return;
2522 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002523 }
2524 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002525 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002526
Jeff Brown3915bb82010-11-05 15:02:16 -07002527 // Key was unhandled.
2528 finishKeyEvent(event, sendDone, false);
2529 }
2530
2531 private void finishKeyEvent(KeyEvent event, boolean sendDone, boolean handled) {
2532 if (sendDone) {
2533 finishInputEvent(handled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002534 }
2535 }
2536
Christopher Tatea53146c2010-09-07 11:57:52 -07002537 /* drag/drop */
2538 private void handleDragEvent(DragEvent event) {
2539 // From the root, only drag start/end/location are dispatched. entered/exited
2540 // are determined and dispatched by the viewgroup hierarchy, who then report
2541 // that back here for ultimate reporting back to the framework.
2542 if (mView != null && mAdded) {
2543 final int what = event.mAction;
2544
2545 if (what == DragEvent.ACTION_DRAG_EXITED) {
2546 // A direct EXITED event means that the window manager knows we've just crossed
2547 // a window boundary, so the current drag target within this one must have
2548 // just been exited. Send it the usual notifications and then we're done
2549 // for now.
Chris Tate9d1ab882010-11-02 15:55:39 -07002550 mView.dispatchDragEvent(event);
Christopher Tatea53146c2010-09-07 11:57:52 -07002551 } else {
2552 // Cache the drag description when the operation starts, then fill it in
2553 // on subsequent calls as a convenience
2554 if (what == DragEvent.ACTION_DRAG_STARTED) {
Chris Tate9d1ab882010-11-02 15:55:39 -07002555 mCurrentDragView = null; // Start the current-recipient tracking
Christopher Tatea53146c2010-09-07 11:57:52 -07002556 mDragDescription = event.mClipDescription;
2557 } else {
2558 event.mClipDescription = mDragDescription;
2559 }
2560
2561 // For events with a [screen] location, translate into window coordinates
2562 if ((what == DragEvent.ACTION_DRAG_LOCATION) || (what == DragEvent.ACTION_DROP)) {
2563 mDragPoint.set(event.mX, event.mY);
2564 if (mTranslator != null) {
2565 mTranslator.translatePointInScreenToAppWindow(mDragPoint);
2566 }
2567
2568 if (mCurScrollY != 0) {
2569 mDragPoint.offset(0, mCurScrollY);
2570 }
2571
2572 event.mX = mDragPoint.x;
2573 event.mY = mDragPoint.y;
2574 }
2575
2576 // Remember who the current drag target is pre-dispatch
2577 final View prevDragView = mCurrentDragView;
2578
2579 // Now dispatch the drag/drop event
Chris Tated4533f12010-10-19 15:15:08 -07002580 boolean result = mView.dispatchDragEvent(event);
Christopher Tatea53146c2010-09-07 11:57:52 -07002581
2582 // If we changed apparent drag target, tell the OS about it
2583 if (prevDragView != mCurrentDragView) {
2584 try {
2585 if (prevDragView != null) {
2586 sWindowSession.dragRecipientExited(mWindow);
2587 }
2588 if (mCurrentDragView != null) {
2589 sWindowSession.dragRecipientEntered(mWindow);
2590 }
2591 } catch (RemoteException e) {
2592 Slog.e(TAG, "Unable to note drag target change");
2593 }
Christopher Tatea53146c2010-09-07 11:57:52 -07002594 }
Chris Tated4533f12010-10-19 15:15:08 -07002595
2596 // Report the drop result if necessary
2597 if (what == DragEvent.ACTION_DROP) {
2598 try {
2599 Log.i(TAG, "Reporting drop result: " + result);
2600 sWindowSession.reportDropResult(mWindow, result);
2601 } catch (RemoteException e) {
2602 Log.e(TAG, "Unable to report drop result");
2603 }
2604 }
Christopher Tatea53146c2010-09-07 11:57:52 -07002605 }
2606 }
2607 event.recycle();
2608 }
2609
Christopher Tate2c095f32010-10-04 14:13:40 -07002610 public void getLastTouchPoint(Point outLocation) {
2611 outLocation.x = (int) mLastTouchPoint.x;
2612 outLocation.y = (int) mLastTouchPoint.y;
2613 }
2614
Chris Tate9d1ab882010-11-02 15:55:39 -07002615 public void setDragFocus(View newDragTarget) {
Christopher Tatea53146c2010-09-07 11:57:52 -07002616 if (mCurrentDragView != newDragTarget) {
Chris Tate048691c2010-10-12 17:39:18 -07002617 mCurrentDragView = newDragTarget;
Christopher Tatea53146c2010-09-07 11:57:52 -07002618 }
Christopher Tatea53146c2010-09-07 11:57:52 -07002619 }
2620
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002621 private AudioManager getAudioManager() {
2622 if (mView == null) {
2623 throw new IllegalStateException("getAudioManager called when there is no mView");
2624 }
2625 if (mAudioManager == null) {
2626 mAudioManager = (AudioManager) mView.getContext().getSystemService(Context.AUDIO_SERVICE);
2627 }
2628 return mAudioManager;
2629 }
2630
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002631 private int relayoutWindow(WindowManager.LayoutParams params, int viewVisibility,
2632 boolean insetsPending) throws RemoteException {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002633
2634 float appScale = mAttachInfo.mApplicationScale;
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002635 boolean restore = false;
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002636 if (params != null && mTranslator != null) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07002637 restore = true;
2638 params.backup();
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002639 mTranslator.translateWindowLayout(params);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002640 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002641 if (params != null) {
2642 if (DBG) Log.d(TAG, "WindowLayout in layoutWindow:" + params);
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002643 }
Dianne Hackborn694f79b2010-03-17 19:44:59 -07002644 mPendingConfiguration.seq = 0;
Dianne Hackbornf123e492010-09-24 11:16:23 -07002645 //Log.d(TAG, ">>>>>> CALLING relayout");
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002646 int relayoutResult = sWindowSession.relayout(
2647 mWindow, params,
Mitsuru Oshima61324e52009-07-21 15:40:36 -07002648 (int) (mView.mMeasuredWidth * appScale + 0.5f),
2649 (int) (mView.mMeasuredHeight * appScale + 0.5f),
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002650 viewVisibility, insetsPending, mWinFrame,
Dianne Hackborn694f79b2010-03-17 19:44:59 -07002651 mPendingContentInsets, mPendingVisibleInsets,
2652 mPendingConfiguration, mSurface);
Dianne Hackbornf123e492010-09-24 11:16:23 -07002653 //Log.d(TAG, "<<<<<< BACK FROM relayout");
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002654 if (restore) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07002655 params.restore();
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002656 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002657
2658 if (mTranslator != null) {
2659 mTranslator.translateRectInScreenToAppWinFrame(mWinFrame);
2660 mTranslator.translateRectInScreenToAppWindow(mPendingContentInsets);
2661 mTranslator.translateRectInScreenToAppWindow(mPendingVisibleInsets);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002662 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002663 return relayoutResult;
2664 }
Romain Guy8506ab42009-06-11 17:35:47 -07002665
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002666 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002667 * {@inheritDoc}
2668 */
2669 public void playSoundEffect(int effectId) {
2670 checkThread();
2671
Jean-Michel Trivi13b18fd2010-05-05 09:18:15 -07002672 try {
2673 final AudioManager audioManager = getAudioManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002674
Jean-Michel Trivi13b18fd2010-05-05 09:18:15 -07002675 switch (effectId) {
2676 case SoundEffectConstants.CLICK:
2677 audioManager.playSoundEffect(AudioManager.FX_KEY_CLICK);
2678 return;
2679 case SoundEffectConstants.NAVIGATION_DOWN:
2680 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_DOWN);
2681 return;
2682 case SoundEffectConstants.NAVIGATION_LEFT:
2683 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_LEFT);
2684 return;
2685 case SoundEffectConstants.NAVIGATION_RIGHT:
2686 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_RIGHT);
2687 return;
2688 case SoundEffectConstants.NAVIGATION_UP:
2689 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_UP);
2690 return;
2691 default:
2692 throw new IllegalArgumentException("unknown effect id " + effectId +
2693 " not defined in " + SoundEffectConstants.class.getCanonicalName());
2694 }
2695 } catch (IllegalStateException e) {
2696 // Exception thrown by getAudioManager() when mView is null
2697 Log.e(TAG, "FATAL EXCEPTION when attempting to play sound effect: " + e);
2698 e.printStackTrace();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002699 }
2700 }
2701
2702 /**
2703 * {@inheritDoc}
2704 */
2705 public boolean performHapticFeedback(int effectId, boolean always) {
2706 try {
2707 return sWindowSession.performHapticFeedback(mWindow, effectId, always);
2708 } catch (RemoteException e) {
2709 return false;
2710 }
2711 }
2712
2713 /**
2714 * {@inheritDoc}
2715 */
2716 public View focusSearch(View focused, int direction) {
2717 checkThread();
2718 if (!(mView instanceof ViewGroup)) {
2719 return null;
2720 }
2721 return FocusFinder.getInstance().findNextFocus((ViewGroup) mView, focused, direction);
2722 }
2723
2724 public void debug() {
2725 mView.debug();
2726 }
2727
2728 public void die(boolean immediate) {
Dianne Hackborn94d69142009-09-28 22:14:42 -07002729 if (immediate) {
2730 doDie();
2731 } else {
2732 sendEmptyMessage(DIE);
2733 }
2734 }
2735
2736 void doDie() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002737 checkThread();
Jeff Brownb75fa302010-07-15 23:47:29 -07002738 if (LOCAL_LOGV) Log.v(TAG, "DIE in " + this + " of " + mSurface);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002739 synchronized (this) {
2740 if (mAdded && !mFirst) {
Romain Guy29d89972010-09-22 16:10:57 -07002741 destroyHardwareRenderer();
2742
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002743 int viewVisibility = mView.getVisibility();
2744 boolean viewVisibilityChanged = mViewVisibility != viewVisibility;
2745 if (mWindowAttributesChanged || viewVisibilityChanged) {
2746 // If layout params have been changed, first give them
2747 // to the window manager to make sure it has the correct
2748 // animation info.
2749 try {
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002750 if ((relayoutWindow(mWindowAttributes, viewVisibility, false)
2751 & WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002752 sWindowSession.finishDrawing(mWindow);
2753 }
2754 } catch (RemoteException e) {
2755 }
2756 }
2757
Dianne Hackborn0586a1b2009-09-06 21:08:27 -07002758 mSurface.release();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002759 }
2760 if (mAdded) {
2761 mAdded = false;
Dianne Hackborn94d69142009-09-28 22:14:42 -07002762 dispatchDetachedFromWindow();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002763 }
2764 }
2765 }
2766
Romain Guy29d89972010-09-22 16:10:57 -07002767 private void destroyHardwareRenderer() {
Romain Guyb051e892010-09-28 19:09:36 -07002768 if (mAttachInfo.mHardwareRenderer != null) {
2769 mAttachInfo.mHardwareRenderer.destroy(true);
2770 mAttachInfo.mHardwareRenderer = null;
Romain Guy29d89972010-09-22 16:10:57 -07002771 mAttachInfo.mHardwareAccelerated = false;
2772 }
2773 }
2774
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002775 public void dispatchFinishedEvent(int seq, boolean handled) {
2776 Message msg = obtainMessage(FINISHED_EVENT);
2777 msg.arg1 = seq;
2778 msg.arg2 = handled ? 1 : 0;
2779 sendMessage(msg);
2780 }
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002781
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002782 public void dispatchResized(int w, int h, Rect coveredInsets,
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002783 Rect visibleInsets, boolean reportDraw, Configuration newConfig) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002784 if (DEBUG_LAYOUT) Log.v(TAG, "Resizing " + this + ": w=" + w
2785 + " h=" + h + " coveredInsets=" + coveredInsets.toShortString()
2786 + " visibleInsets=" + visibleInsets.toShortString()
2787 + " reportDraw=" + reportDraw);
2788 Message msg = obtainMessage(reportDraw ? RESIZED_REPORT :RESIZED);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002789 if (mTranslator != null) {
2790 mTranslator.translateRectInScreenToAppWindow(coveredInsets);
2791 mTranslator.translateRectInScreenToAppWindow(visibleInsets);
2792 w *= mTranslator.applicationInvertedScale;
2793 h *= mTranslator.applicationInvertedScale;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002794 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002795 msg.arg1 = w;
2796 msg.arg2 = h;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002797 ResizedInfo ri = new ResizedInfo();
2798 ri.coveredInsets = new Rect(coveredInsets);
2799 ri.visibleInsets = new Rect(visibleInsets);
2800 ri.newConfig = newConfig;
2801 msg.obj = ri;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002802 sendMessage(msg);
2803 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002804
Jeff Brown3915bb82010-11-05 15:02:16 -07002805 private InputQueue.FinishedCallback mFinishedCallback;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002806
2807 private final InputHandler mInputHandler = new InputHandler() {
Jeff Brown3915bb82010-11-05 15:02:16 -07002808 public void handleKey(KeyEvent event, InputQueue.FinishedCallback finishedCallback) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07002809 startInputEvent(finishedCallback);
Jeff Brown92ff1dd2010-08-11 16:16:06 -07002810 dispatchKey(event, true);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002811 }
2812
Jeff Brown3915bb82010-11-05 15:02:16 -07002813 public void handleMotion(MotionEvent event, InputQueue.FinishedCallback finishedCallback) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07002814 startInputEvent(finishedCallback);
2815 dispatchMotion(event, true);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002816 }
2817 };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002818
2819 public void dispatchKey(KeyEvent event) {
Jeff Brown92ff1dd2010-08-11 16:16:06 -07002820 dispatchKey(event, false);
2821 }
2822
2823 private void dispatchKey(KeyEvent event, boolean sendDone) {
2824 //noinspection ConstantConditions
2825 if (false && event.getAction() == KeyEvent.ACTION_DOWN) {
2826 if (event.getKeyCode() == KeyEvent.KEYCODE_CAMERA) {
Romain Guy812ccbe2010-06-01 14:07:24 -07002827 if (DBG) Log.d("keydisp", "===================================================");
2828 if (DBG) Log.d("keydisp", "Focused view Hierarchy is:");
2829
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002830 debug();
2831
Romain Guy812ccbe2010-06-01 14:07:24 -07002832 if (DBG) Log.d("keydisp", "===================================================");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002833 }
2834 }
2835
2836 Message msg = obtainMessage(DISPATCH_KEY);
2837 msg.obj = event;
Jeff Brown92ff1dd2010-08-11 16:16:06 -07002838 msg.arg1 = sendDone ? 1 : 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002839
2840 if (LOCAL_LOGV) Log.v(
Jeff Brownc5ed5912010-07-14 18:48:53 -07002841 TAG, "sending key " + event + " to " + mView);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002842
2843 sendMessageAtTime(msg, event.getEventTime());
2844 }
Jeff Brownc5ed5912010-07-14 18:48:53 -07002845
2846 public void dispatchMotion(MotionEvent event) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07002847 dispatchMotion(event, false);
2848 }
2849
2850 private void dispatchMotion(MotionEvent event, boolean sendDone) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07002851 int source = event.getSource();
2852 if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07002853 dispatchPointer(event, sendDone);
Jeff Brownc5ed5912010-07-14 18:48:53 -07002854 } else if ((source & InputDevice.SOURCE_CLASS_TRACKBALL) != 0) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07002855 dispatchTrackball(event, sendDone);
Jeff Brownc5ed5912010-07-14 18:48:53 -07002856 } else {
2857 // TODO
2858 Log.v(TAG, "Dropping unsupported motion event (unimplemented): " + event);
Jeff Brown93ed4e32010-09-23 13:51:48 -07002859 if (sendDone) {
Jeff Brown3915bb82010-11-05 15:02:16 -07002860 finishInputEvent(false);
Jeff Brown93ed4e32010-09-23 13:51:48 -07002861 }
Jeff Brownc5ed5912010-07-14 18:48:53 -07002862 }
2863 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002864
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002865 public void dispatchPointer(MotionEvent event) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07002866 dispatchPointer(event, false);
2867 }
2868
2869 private void dispatchPointer(MotionEvent event, boolean sendDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002870 Message msg = obtainMessage(DISPATCH_POINTER);
2871 msg.obj = event;
Jeff Brown93ed4e32010-09-23 13:51:48 -07002872 msg.arg1 = sendDone ? 1 : 0;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002873 sendMessageAtTime(msg, event.getEventTime());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002874 }
2875
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002876 public void dispatchTrackball(MotionEvent event) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07002877 dispatchTrackball(event, false);
2878 }
2879
2880 private void dispatchTrackball(MotionEvent event, boolean sendDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002881 Message msg = obtainMessage(DISPATCH_TRACKBALL);
2882 msg.obj = event;
Jeff Brown93ed4e32010-09-23 13:51:48 -07002883 msg.arg1 = sendDone ? 1 : 0;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002884 sendMessageAtTime(msg, event.getEventTime());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002885 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002886
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002887 public void dispatchAppVisibility(boolean visible) {
2888 Message msg = obtainMessage(DISPATCH_APP_VISIBILITY);
2889 msg.arg1 = visible ? 1 : 0;
2890 sendMessage(msg);
2891 }
2892
2893 public void dispatchGetNewSurface() {
2894 Message msg = obtainMessage(DISPATCH_GET_NEW_SURFACE);
2895 sendMessage(msg);
2896 }
2897
2898 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
2899 Message msg = Message.obtain();
2900 msg.what = WINDOW_FOCUS_CHANGED;
2901 msg.arg1 = hasFocus ? 1 : 0;
2902 msg.arg2 = inTouchMode ? 1 : 0;
2903 sendMessage(msg);
2904 }
2905
Dianne Hackbornffa42482009-09-23 22:20:11 -07002906 public void dispatchCloseSystemDialogs(String reason) {
2907 Message msg = Message.obtain();
2908 msg.what = CLOSE_SYSTEM_DIALOGS;
2909 msg.obj = reason;
2910 sendMessage(msg);
2911 }
Christopher Tatea53146c2010-09-07 11:57:52 -07002912
2913 public void dispatchDragEvent(DragEvent event) {
Chris Tate91e9bb32010-10-12 12:58:43 -07002914 final int what;
2915 if (event.getAction() == DragEvent.ACTION_DRAG_LOCATION) {
2916 what = DISPATCH_DRAG_LOCATION_EVENT;
2917 removeMessages(what);
2918 } else {
2919 what = DISPATCH_DRAG_EVENT;
2920 }
2921 Message msg = obtainMessage(what, event);
Christopher Tatea53146c2010-09-07 11:57:52 -07002922 sendMessage(msg);
2923 }
2924
svetoslavganov75986cf2009-05-14 22:28:01 -07002925 /**
2926 * The window is getting focus so if there is anything focused/selected
2927 * send an {@link AccessibilityEvent} to announce that.
2928 */
2929 private void sendAccessibilityEvents() {
2930 if (!AccessibilityManager.getInstance(mView.getContext()).isEnabled()) {
2931 return;
2932 }
2933 mView.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
2934 View focusedView = mView.findFocus();
2935 if (focusedView != null && focusedView != mView) {
2936 focusedView.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
2937 }
2938 }
2939
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002940 public boolean showContextMenuForChild(View originalView) {
2941 return false;
2942 }
2943
Adam Powell6e346362010-07-23 10:18:23 -07002944 public ActionMode startActionModeForChild(View originalView, ActionMode.Callback callback) {
2945 return null;
2946 }
2947
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002948 public void createContextMenu(ContextMenu menu) {
2949 }
2950
2951 public void childDrawableStateChanged(View child) {
2952 }
2953
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002954 void checkThread() {
2955 if (mThread != Thread.currentThread()) {
2956 throw new CalledFromWrongThreadException(
2957 "Only the original thread that created a view hierarchy can touch its views.");
2958 }
2959 }
2960
2961 public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
2962 // ViewRoot never intercepts touch event, so this can be a no-op
2963 }
2964
2965 public boolean requestChildRectangleOnScreen(View child, Rect rectangle,
2966 boolean immediate) {
2967 return scrollToRectOrFocus(rectangle, immediate);
2968 }
Romain Guy8506ab42009-06-11 17:35:47 -07002969
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07002970 class TakenSurfaceHolder extends BaseSurfaceHolder {
2971 @Override
2972 public boolean onAllowLockCanvas() {
2973 return mDrawingAllowed;
2974 }
2975
2976 @Override
2977 public void onRelayoutContainer() {
2978 // Not currently interesting -- from changing between fixed and layout size.
2979 }
2980
2981 public void setFormat(int format) {
2982 ((RootViewSurfaceTaker)mView).setSurfaceFormat(format);
2983 }
2984
2985 public void setType(int type) {
2986 ((RootViewSurfaceTaker)mView).setSurfaceType(type);
2987 }
2988
2989 @Override
2990 public void onUpdateSurface() {
2991 // We take care of format and type changes on our own.
2992 throw new IllegalStateException("Shouldn't be here");
2993 }
2994
2995 public boolean isCreating() {
2996 return mIsCreating;
2997 }
2998
2999 @Override
3000 public void setFixedSize(int width, int height) {
3001 throw new UnsupportedOperationException(
3002 "Currently only support sizing from layout");
3003 }
3004
3005 public void setKeepScreenOn(boolean screenOn) {
3006 ((RootViewSurfaceTaker)mView).setSurfaceKeepScreenOn(screenOn);
3007 }
3008 }
3009
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003010 static class InputMethodCallback extends IInputMethodCallback.Stub {
3011 private WeakReference<ViewRoot> mViewRoot;
3012
3013 public InputMethodCallback(ViewRoot viewRoot) {
3014 mViewRoot = new WeakReference<ViewRoot>(viewRoot);
3015 }
Romain Guy8506ab42009-06-11 17:35:47 -07003016
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003017 public void finishedEvent(int seq, boolean handled) {
3018 final ViewRoot viewRoot = mViewRoot.get();
3019 if (viewRoot != null) {
3020 viewRoot.dispatchFinishedEvent(seq, handled);
3021 }
3022 }
3023
3024 public void sessionCreated(IInputMethodSession session) throws RemoteException {
3025 // Stub -- not for use in the client.
3026 }
3027 }
Romain Guy8506ab42009-06-11 17:35:47 -07003028
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003029 static class W extends IWindow.Stub {
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07003030 private final WeakReference<ViewRoot> mViewRoot;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003031
Romain Guyfb8b7632010-08-23 21:05:08 -07003032 W(ViewRoot viewRoot) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003033 mViewRoot = new WeakReference<ViewRoot>(viewRoot);
3034 }
3035
Romain Guyfb8b7632010-08-23 21:05:08 -07003036 public void resized(int w, int h, Rect coveredInsets, Rect visibleInsets,
3037 boolean reportDraw, Configuration newConfig) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003038 final ViewRoot viewRoot = mViewRoot.get();
3039 if (viewRoot != null) {
Romain Guyfb8b7632010-08-23 21:05:08 -07003040 viewRoot.dispatchResized(w, h, coveredInsets, visibleInsets, reportDraw, newConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003041 }
3042 }
3043
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003044 public void dispatchAppVisibility(boolean visible) {
3045 final ViewRoot viewRoot = mViewRoot.get();
3046 if (viewRoot != null) {
3047 viewRoot.dispatchAppVisibility(visible);
3048 }
3049 }
3050
3051 public void dispatchGetNewSurface() {
3052 final ViewRoot viewRoot = mViewRoot.get();
3053 if (viewRoot != null) {
3054 viewRoot.dispatchGetNewSurface();
3055 }
3056 }
3057
3058 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
3059 final ViewRoot viewRoot = mViewRoot.get();
3060 if (viewRoot != null) {
3061 viewRoot.windowFocusChanged(hasFocus, inTouchMode);
3062 }
3063 }
3064
3065 private static int checkCallingPermission(String permission) {
3066 if (!Process.supportsProcesses()) {
3067 return PackageManager.PERMISSION_GRANTED;
3068 }
3069
3070 try {
3071 return ActivityManagerNative.getDefault().checkPermission(
3072 permission, Binder.getCallingPid(), Binder.getCallingUid());
3073 } catch (RemoteException e) {
3074 return PackageManager.PERMISSION_DENIED;
3075 }
3076 }
3077
3078 public void executeCommand(String command, String parameters, ParcelFileDescriptor out) {
3079 final ViewRoot viewRoot = mViewRoot.get();
3080 if (viewRoot != null) {
3081 final View view = viewRoot.mView;
3082 if (view != null) {
3083 if (checkCallingPermission(Manifest.permission.DUMP) !=
3084 PackageManager.PERMISSION_GRANTED) {
3085 throw new SecurityException("Insufficient permissions to invoke"
3086 + " executeCommand() from pid=" + Binder.getCallingPid()
3087 + ", uid=" + Binder.getCallingUid());
3088 }
3089
3090 OutputStream clientStream = null;
3091 try {
3092 clientStream = new ParcelFileDescriptor.AutoCloseOutputStream(out);
3093 ViewDebug.dispatchCommand(view, command, parameters, clientStream);
3094 } catch (IOException e) {
3095 e.printStackTrace();
3096 } finally {
3097 if (clientStream != null) {
3098 try {
3099 clientStream.close();
3100 } catch (IOException e) {
3101 e.printStackTrace();
3102 }
3103 }
3104 }
3105 }
3106 }
3107 }
Dianne Hackborn72c82ab2009-08-11 21:13:54 -07003108
Dianne Hackbornffa42482009-09-23 22:20:11 -07003109 public void closeSystemDialogs(String reason) {
3110 final ViewRoot viewRoot = mViewRoot.get();
3111 if (viewRoot != null) {
3112 viewRoot.dispatchCloseSystemDialogs(reason);
3113 }
3114 }
3115
Marco Nelissenbf6956b2009-11-09 15:21:13 -08003116 public void dispatchWallpaperOffsets(float x, float y, float xStep, float yStep,
3117 boolean sync) {
Dianne Hackborn19382ac2009-09-11 21:13:37 -07003118 if (sync) {
3119 try {
3120 sWindowSession.wallpaperOffsetsComplete(asBinder());
3121 } catch (RemoteException e) {
3122 }
3123 }
Dianne Hackborn72c82ab2009-08-11 21:13:54 -07003124 }
Dianne Hackborn75804932009-10-20 20:15:20 -07003125
3126 public void dispatchWallpaperCommand(String action, int x, int y,
3127 int z, Bundle extras, boolean sync) {
3128 if (sync) {
3129 try {
3130 sWindowSession.wallpaperCommandComplete(asBinder(), null);
3131 } catch (RemoteException e) {
3132 }
3133 }
3134 }
Christopher Tatea53146c2010-09-07 11:57:52 -07003135
3136 /* Drag/drop */
3137 public void dispatchDragEvent(DragEvent event) {
3138 final ViewRoot viewRoot = mViewRoot.get();
3139 if (viewRoot != null) {
3140 viewRoot.dispatchDragEvent(event);
3141 }
3142 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003143 }
3144
3145 /**
3146 * Maintains state information for a single trackball axis, generating
3147 * discrete (DPAD) movements based on raw trackball motion.
3148 */
3149 static final class TrackballAxis {
3150 /**
3151 * The maximum amount of acceleration we will apply.
3152 */
3153 static final float MAX_ACCELERATION = 20;
Romain Guy8506ab42009-06-11 17:35:47 -07003154
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003155 /**
3156 * The maximum amount of time (in milliseconds) between events in order
3157 * for us to consider the user to be doing fast trackball movements,
3158 * and thus apply an acceleration.
3159 */
3160 static final long FAST_MOVE_TIME = 150;
Romain Guy8506ab42009-06-11 17:35:47 -07003161
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003162 /**
3163 * Scaling factor to the time (in milliseconds) between events to how
3164 * much to multiple/divide the current acceleration. When movement
3165 * is < FAST_MOVE_TIME this multiplies the acceleration; when >
3166 * FAST_MOVE_TIME it divides it.
3167 */
3168 static final float ACCEL_MOVE_SCALING_FACTOR = (1.0f/40);
Romain Guy8506ab42009-06-11 17:35:47 -07003169
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003170 float position;
3171 float absPosition;
3172 float acceleration = 1;
3173 long lastMoveTime = 0;
3174 int step;
3175 int dir;
3176 int nonAccelMovement;
3177
3178 void reset(int _step) {
3179 position = 0;
3180 acceleration = 1;
3181 lastMoveTime = 0;
3182 step = _step;
3183 dir = 0;
3184 }
3185
3186 /**
3187 * Add trackball movement into the state. If the direction of movement
3188 * has been reversed, the state is reset before adding the
3189 * movement (so that you don't have to compensate for any previously
3190 * collected movement before see the result of the movement in the
3191 * new direction).
3192 *
3193 * @return Returns the absolute value of the amount of movement
3194 * collected so far.
3195 */
3196 float collect(float off, long time, String axis) {
3197 long normTime;
3198 if (off > 0) {
3199 normTime = (long)(off * FAST_MOVE_TIME);
3200 if (dir < 0) {
3201 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to positive!");
3202 position = 0;
3203 step = 0;
3204 acceleration = 1;
3205 lastMoveTime = 0;
3206 }
3207 dir = 1;
3208 } else if (off < 0) {
3209 normTime = (long)((-off) * FAST_MOVE_TIME);
3210 if (dir > 0) {
3211 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to negative!");
3212 position = 0;
3213 step = 0;
3214 acceleration = 1;
3215 lastMoveTime = 0;
3216 }
3217 dir = -1;
3218 } else {
3219 normTime = 0;
3220 }
Romain Guy8506ab42009-06-11 17:35:47 -07003221
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003222 // The number of milliseconds between each movement that is
3223 // considered "normal" and will not result in any acceleration
3224 // or deceleration, scaled by the offset we have here.
3225 if (normTime > 0) {
3226 long delta = time - lastMoveTime;
3227 lastMoveTime = time;
3228 float acc = acceleration;
3229 if (delta < normTime) {
3230 // The user is scrolling rapidly, so increase acceleration.
3231 float scale = (normTime-delta) * ACCEL_MOVE_SCALING_FACTOR;
3232 if (scale > 1) acc *= scale;
3233 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " accelerate: off="
3234 + off + " normTime=" + normTime + " delta=" + delta
3235 + " scale=" + scale + " acc=" + acc);
3236 acceleration = acc < MAX_ACCELERATION ? acc : MAX_ACCELERATION;
3237 } else {
3238 // The user is scrolling slowly, so decrease acceleration.
3239 float scale = (delta-normTime) * ACCEL_MOVE_SCALING_FACTOR;
3240 if (scale > 1) acc /= scale;
3241 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " deccelerate: off="
3242 + off + " normTime=" + normTime + " delta=" + delta
3243 + " scale=" + scale + " acc=" + acc);
3244 acceleration = acc > 1 ? acc : 1;
3245 }
3246 }
3247 position += off;
3248 return (absPosition = Math.abs(position));
3249 }
3250
3251 /**
3252 * Generate the number of discrete movement events appropriate for
3253 * the currently collected trackball movement.
3254 *
3255 * @param precision The minimum movement required to generate the
3256 * first discrete movement.
3257 *
3258 * @return Returns the number of discrete movements, either positive
3259 * or negative, or 0 if there is not enough trackball movement yet
3260 * for a discrete movement.
3261 */
3262 int generate(float precision) {
3263 int movement = 0;
3264 nonAccelMovement = 0;
3265 do {
3266 final int dir = position >= 0 ? 1 : -1;
3267 switch (step) {
3268 // If we are going to execute the first step, then we want
3269 // to do this as soon as possible instead of waiting for
3270 // a full movement, in order to make things look responsive.
3271 case 0:
3272 if (absPosition < precision) {
3273 return movement;
3274 }
3275 movement += dir;
3276 nonAccelMovement += dir;
3277 step = 1;
3278 break;
3279 // If we have generated the first movement, then we need
3280 // to wait for the second complete trackball motion before
3281 // generating the second discrete movement.
3282 case 1:
3283 if (absPosition < 2) {
3284 return movement;
3285 }
3286 movement += dir;
3287 nonAccelMovement += dir;
3288 position += dir > 0 ? -2 : 2;
3289 absPosition = Math.abs(position);
3290 step = 2;
3291 break;
3292 // After the first two, we generate discrete movements
3293 // consistently with the trackball, applying an acceleration
3294 // if the trackball is moving quickly. This is a simple
3295 // acceleration on top of what we already compute based
3296 // on how quickly the wheel is being turned, to apply
3297 // a longer increasing acceleration to continuous movement
3298 // in one direction.
3299 default:
3300 if (absPosition < 1) {
3301 return movement;
3302 }
3303 movement += dir;
3304 position += dir >= 0 ? -1 : 1;
3305 absPosition = Math.abs(position);
3306 float acc = acceleration;
3307 acc *= 1.1f;
3308 acceleration = acc < MAX_ACCELERATION ? acc : acceleration;
3309 break;
3310 }
3311 } while (true);
3312 }
3313 }
3314
3315 public static final class CalledFromWrongThreadException extends AndroidRuntimeException {
3316 public CalledFromWrongThreadException(String msg) {
3317 super(msg);
3318 }
3319 }
3320
3321 private SurfaceHolder mHolder = new SurfaceHolder() {
3322 // we only need a SurfaceHolder for opengl. it would be nice
3323 // to implement everything else though, especially the callback
3324 // support (opengl doesn't make use of it right now, but eventually
3325 // will).
3326 public Surface getSurface() {
3327 return mSurface;
3328 }
3329
3330 public boolean isCreating() {
3331 return false;
3332 }
3333
3334 public void addCallback(Callback callback) {
3335 }
3336
3337 public void removeCallback(Callback callback) {
3338 }
3339
3340 public void setFixedSize(int width, int height) {
3341 }
3342
3343 public void setSizeFromLayout() {
3344 }
3345
3346 public void setFormat(int format) {
3347 }
3348
3349 public void setType(int type) {
3350 }
3351
3352 public void setKeepScreenOn(boolean screenOn) {
3353 }
3354
3355 public Canvas lockCanvas() {
3356 return null;
3357 }
3358
3359 public Canvas lockCanvas(Rect dirty) {
3360 return null;
3361 }
3362
3363 public void unlockCanvasAndPost(Canvas canvas) {
3364 }
3365 public Rect getSurfaceFrame() {
3366 return null;
3367 }
3368 };
3369
3370 static RunQueue getRunQueue() {
3371 RunQueue rq = sRunQueues.get();
3372 if (rq != null) {
3373 return rq;
3374 }
3375 rq = new RunQueue();
3376 sRunQueues.set(rq);
3377 return rq;
3378 }
Romain Guy8506ab42009-06-11 17:35:47 -07003379
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003380 /**
3381 * @hide
3382 */
3383 static final class RunQueue {
3384 private final ArrayList<HandlerAction> mActions = new ArrayList<HandlerAction>();
3385
3386 void post(Runnable action) {
3387 postDelayed(action, 0);
3388 }
3389
3390 void postDelayed(Runnable action, long delayMillis) {
3391 HandlerAction handlerAction = new HandlerAction();
3392 handlerAction.action = action;
3393 handlerAction.delay = delayMillis;
3394
3395 synchronized (mActions) {
3396 mActions.add(handlerAction);
3397 }
3398 }
3399
3400 void removeCallbacks(Runnable action) {
3401 final HandlerAction handlerAction = new HandlerAction();
3402 handlerAction.action = action;
3403
3404 synchronized (mActions) {
3405 final ArrayList<HandlerAction> actions = mActions;
3406
3407 while (actions.remove(handlerAction)) {
3408 // Keep going
3409 }
3410 }
3411 }
3412
3413 void executeActions(Handler handler) {
3414 synchronized (mActions) {
3415 final ArrayList<HandlerAction> actions = mActions;
3416 final int count = actions.size();
3417
3418 for (int i = 0; i < count; i++) {
3419 final HandlerAction handlerAction = actions.get(i);
3420 handler.postDelayed(handlerAction.action, handlerAction.delay);
3421 }
3422
Romain Guy15df6702009-08-17 20:17:30 -07003423 actions.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003424 }
3425 }
3426
3427 private static class HandlerAction {
3428 Runnable action;
3429 long delay;
3430
3431 @Override
3432 public boolean equals(Object o) {
3433 if (this == o) return true;
3434 if (o == null || getClass() != o.getClass()) return false;
3435
3436 HandlerAction that = (HandlerAction) o;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003437 return !(action != null ? !action.equals(that.action) : that.action != null);
3438
3439 }
3440
3441 @Override
3442 public int hashCode() {
3443 int result = action != null ? action.hashCode() : 0;
3444 result = 31 * result + (int) (delay ^ (delay >>> 32));
3445 return result;
3446 }
3447 }
3448 }
3449
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003450 private static native void nativeShowFPS(Canvas canvas, int durationMillis);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003451}