blob: 761c5d90f617820146a50799a3e27cbed0747367 [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;
Dianne Hackborn711e62a2010-11-29 16:38:22 -080056import android.util.TypedValue;
Jeff Brown3915bb82010-11-05 15:02:16 -070057import android.view.InputQueue.FinishedCallback;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080058import android.view.View.MeasureSpec;
svetoslavganov75986cf2009-05-14 22:28:01 -070059import android.view.accessibility.AccessibilityEvent;
60import android.view.accessibility.AccessibilityManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080061import android.view.inputmethod.InputConnection;
62import android.view.inputmethod.InputMethodManager;
63import android.widget.Scroller;
Joe Onorato86f67862010-11-05 18:57:34 -070064import com.android.internal.policy.PolicyManager;
Romain Guy6b7bd242010-10-06 19:49:23 -070065import com.android.internal.view.BaseSurfaceHolder;
66import com.android.internal.view.IInputMethodCallback;
67import com.android.internal.view.IInputMethodSession;
68import com.android.internal.view.RootViewSurfaceTaker;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080069
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080070import java.io.IOException;
71import java.io.OutputStream;
Romain Guy6b7bd242010-10-06 19:49:23 -070072import java.lang.ref.WeakReference;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080073import java.util.ArrayList;
74
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080075/**
76 * The top of a view hierarchy, implementing the needed protocol between View
77 * and the WindowManager. This is for the most part an internal implementation
78 * detail of {@link WindowManagerImpl}.
79 *
80 * {@hide}
81 */
Romain Guy812ccbe2010-06-01 14:07:24 -070082@SuppressWarnings({"EmptyCatchBlock", "PointlessBooleanExpression"})
83public final class ViewRoot extends Handler implements ViewParent, View.AttachInfo.Callbacks {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080084 private static final String TAG = "ViewRoot";
85 private static final boolean DBG = false;
Mike Reedfd716532009-10-12 14:42:56 -040086 private static final boolean SHOW_FPS = false;
Romain Guy812ccbe2010-06-01 14:07:24 -070087 private static final boolean LOCAL_LOGV = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080088 /** @noinspection PointlessBooleanExpression*/
89 private static final boolean DEBUG_DRAW = false || LOCAL_LOGV;
90 private static final boolean DEBUG_LAYOUT = false || LOCAL_LOGV;
Dianne Hackborn711e62a2010-11-29 16:38:22 -080091 private static final boolean DEBUG_DIALOG = false || LOCAL_LOGV;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080092 private static final boolean DEBUG_INPUT_RESIZE = false || LOCAL_LOGV;
93 private static final boolean DEBUG_ORIENTATION = false || LOCAL_LOGV;
94 private static final boolean DEBUG_TRACKBALL = false || LOCAL_LOGV;
95 private static final boolean DEBUG_IMF = false || LOCAL_LOGV;
Dianne Hackborn694f79b2010-03-17 19:44:59 -070096 private static final boolean DEBUG_CONFIGURATION = false || LOCAL_LOGV;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080097 private static final boolean WATCH_POINTER = false;
98
Michael Chan53071d62009-05-13 17:29:48 -070099 private static final boolean MEASURE_LATENCY = false;
100 private static LatencyTimer lt;
101
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800102 /**
103 * Maximum time we allow the user to roll the trackball enough to generate
104 * a key event, before resetting the counters.
105 */
106 static final int MAX_TRACKBALL_DELAY = 250;
107
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800108 static IWindowSession sWindowSession;
109
110 static final Object mStaticInit = new Object();
111 static boolean mInitialized = false;
112
113 static final ThreadLocal<RunQueue> sRunQueues = new ThreadLocal<RunQueue>();
114
Dianne Hackborn2a9094d2010-02-03 19:20:09 -0800115 static final ArrayList<Runnable> sFirstDrawHandlers = new ArrayList<Runnable>();
116 static boolean sFirstDrawComplete = false;
117
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800118 static final ArrayList<ComponentCallbacks> sConfigCallbacks
119 = new ArrayList<ComponentCallbacks>();
120
Romain Guy8506ab42009-06-11 17:35:47 -0700121 private static int sDrawTime;
Romain Guy13922e02009-05-12 17:56:14 -0700122
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800123 long mLastTrackballTime = 0;
124 final TrackballAxis mTrackballAxisX = new TrackballAxis();
125 final TrackballAxis mTrackballAxisY = new TrackballAxis();
126
127 final int[] mTmpLocation = new int[2];
Romain Guy8506ab42009-06-11 17:35:47 -0700128
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800129 final TypedValue mTmpValue = new TypedValue();
130
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800131 final InputMethodCallback mInputMethodCallback;
132 final SparseArray<Object> mPendingEvents = new SparseArray<Object>();
133 int mPendingEventSeq = 0;
Romain Guy8506ab42009-06-11 17:35:47 -0700134
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800135 final Thread mThread;
136
137 final WindowLeaked mLocation;
138
139 final WindowManager.LayoutParams mWindowAttributes = new WindowManager.LayoutParams();
140
141 final W mWindow;
142
143 View mView;
144 View mFocusedView;
145 View mRealFocusedView; // this is not set to null in touch mode
146 int mViewVisibility;
147 boolean mAppVisible = true;
148
Dianne Hackbornd76b67c2010-07-13 17:48:30 -0700149 SurfaceHolder.Callback2 mSurfaceHolderCallback;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700150 BaseSurfaceHolder mSurfaceHolder;
151 boolean mIsCreating;
152 boolean mDrawingAllowed;
153
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800154 final Region mTransparentRegion;
155 final Region mPreviousTransparentRegion;
156
157 int mWidth;
158 int mHeight;
159 Rect mDirty; // will be a graphics.Region soon
Romain Guybb93d552009-03-24 21:04:15 -0700160 boolean mIsAnimating;
Romain Guy8506ab42009-06-11 17:35:47 -0700161
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700162 CompatibilityInfo.Translator mTranslator;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800163
164 final View.AttachInfo mAttachInfo;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700165 InputChannel mInputChannel;
Dianne Hackborn1e4b9f32010-06-23 14:10:57 -0700166 InputQueue.Callback mInputQueueCallback;
167 InputQueue mInputQueue;
Joe Onorato86f67862010-11-05 18:57:34 -0700168 FallbackEventHandler mFallbackEventHandler;
Dianne Hackborna95e4cb2010-06-18 18:09:33 -0700169
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800170 final Rect mTempRect; // used in the transaction to not thrash the heap.
171 final Rect mVisRect; // used to retrieve visible rect of focused view.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800172
173 boolean mTraversalScheduled;
174 boolean mWillDrawSoon;
175 boolean mLayoutRequested;
176 boolean mFirst;
177 boolean mReportNextDraw;
178 boolean mFullRedrawNeeded;
179 boolean mNewSurfaceNeeded;
180 boolean mHasHadWindowFocus;
181 boolean mLastWasImTarget;
182
183 boolean mWindowAttributesChanged = false;
184
185 // These can be accessed by any thread, must be protected with a lock.
Mathias Agopian5583dc62009-07-09 16:28:11 -0700186 // Surface can never be reassigned or cleared (use Surface.clear()).
187 private final Surface mSurface = new Surface();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800188
189 boolean mAdded;
190 boolean mAddedTouchMode;
191
192 /*package*/ int mAddNesting;
193
194 // These are accessed by multiple threads.
195 final Rect mWinFrame; // frame given by window manager.
196
197 final Rect mPendingVisibleInsets = new Rect();
198 final Rect mPendingContentInsets = new Rect();
199 final ViewTreeObserver.InternalInsetsInfo mLastGivenInsets
200 = new ViewTreeObserver.InternalInsetsInfo();
201
Dianne Hackborn694f79b2010-03-17 19:44:59 -0700202 final Configuration mLastConfiguration = new Configuration();
203 final Configuration mPendingConfiguration = new Configuration();
204
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800205 class ResizedInfo {
206 Rect coveredInsets;
207 Rect visibleInsets;
208 Configuration newConfig;
209 }
210
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800211 boolean mScrollMayChange;
212 int mSoftInputMode;
213 View mLastScrolledFocus;
214 int mScrollY;
215 int mCurScrollY;
216 Scroller mScroller;
Romain Guy8506ab42009-06-11 17:35:47 -0700217
Romain Guy8506ab42009-06-11 17:35:47 -0700218 final ViewConfiguration mViewConfiguration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800219
Christopher Tatea53146c2010-09-07 11:57:52 -0700220 /* Drag/drop */
221 ClipDescription mDragDescription;
222 View mCurrentDragView;
223 final PointF mDragPoint = new PointF();
Christopher Tate2c095f32010-10-04 14:13:40 -0700224 final PointF mLastTouchPoint = new PointF();
Christopher Tatea53146c2010-09-07 11:57:52 -0700225
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800226 /**
227 * see {@link #playSoundEffect(int)}
228 */
229 AudioManager mAudioManager;
230
Dianne Hackborn11ea3342009-07-22 21:48:55 -0700231 private final int mDensity;
Adam Powellb08013c2010-09-16 16:28:11 -0700232
Dianne Hackborn4c62fc02009-08-08 20:40:27 -0700233 public static IWindowSession getWindowSession(Looper mainLooper) {
234 synchronized (mStaticInit) {
235 if (!mInitialized) {
236 try {
237 InputMethodManager imm = InputMethodManager.getInstance(mainLooper);
238 sWindowSession = IWindowManager.Stub.asInterface(
239 ServiceManager.getService("window"))
240 .openSession(imm.getClient(), imm.getInputContext());
241 mInitialized = true;
242 } catch (RemoteException e) {
243 }
244 }
245 return sWindowSession;
246 }
247 }
248
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800249 public ViewRoot(Context context) {
250 super();
251
Romain Guy812ccbe2010-06-01 14:07:24 -0700252 if (MEASURE_LATENCY) {
253 if (lt == null) {
254 lt = new LatencyTimer(100, 1000);
255 }
Michael Chan53071d62009-05-13 17:29:48 -0700256 }
257
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800258 // Initialize the statics when this class is first instantiated. This is
259 // done here instead of in the static block because Zygote does not
260 // allow the spawning of threads.
Dianne Hackborn4c62fc02009-08-08 20:40:27 -0700261 getWindowSession(context.getMainLooper());
262
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800263 mThread = Thread.currentThread();
264 mLocation = new WindowLeaked(null);
265 mLocation.fillInStackTrace();
266 mWidth = -1;
267 mHeight = -1;
268 mDirty = new Rect();
269 mTempRect = new Rect();
270 mVisRect = new Rect();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800271 mWinFrame = new Rect();
Romain Guyfb8b7632010-08-23 21:05:08 -0700272 mWindow = new W(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800273 mInputMethodCallback = new InputMethodCallback(this);
274 mViewVisibility = View.GONE;
275 mTransparentRegion = new Region();
276 mPreviousTransparentRegion = new Region();
277 mFirst = true; // true for the first time the view is added
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800278 mAdded = false;
279 mAttachInfo = new View.AttachInfo(sWindowSession, mWindow, this, this);
280 mViewConfiguration = ViewConfiguration.get(context);
Dianne Hackborn11ea3342009-07-22 21:48:55 -0700281 mDensity = context.getResources().getDisplayMetrics().densityDpi;
Joe Onorato86f67862010-11-05 18:57:34 -0700282 mFallbackEventHandler = PolicyManager.makeNewFallbackEventHandler(context);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800283 }
284
Dianne Hackborn2a9094d2010-02-03 19:20:09 -0800285 public static void addFirstDrawHandler(Runnable callback) {
286 synchronized (sFirstDrawHandlers) {
287 if (!sFirstDrawComplete) {
288 sFirstDrawHandlers.add(callback);
289 }
290 }
291 }
292
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800293 public static void addConfigCallback(ComponentCallbacks callback) {
294 synchronized (sConfigCallbacks) {
295 sConfigCallbacks.add(callback);
296 }
297 }
298
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800299 // FIXME for perf testing only
300 private boolean mProfile = false;
301
302 /**
303 * Call this to profile the next traversal call.
304 * FIXME for perf testing only. Remove eventually
305 */
306 public void profile() {
307 mProfile = true;
308 }
309
310 /**
311 * Indicates whether we are in touch mode. Calling this method triggers an IPC
312 * call and should be avoided whenever possible.
313 *
314 * @return True, if the device is in touch mode, false otherwise.
315 *
316 * @hide
317 */
318 static boolean isInTouchMode() {
319 if (mInitialized) {
320 try {
321 return sWindowSession.getInTouchMode();
322 } catch (RemoteException e) {
323 }
324 }
325 return false;
326 }
327
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800328 /**
329 * We have one child
330 */
Romain Guye4d01122010-06-16 18:44:05 -0700331 public void setView(View view, WindowManager.LayoutParams attrs, View panelParentView) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800332 synchronized (this) {
333 if (mView == null) {
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700334 mView = view;
Joe Onorato86f67862010-11-05 18:57:34 -0700335 mFallbackEventHandler.setView(view);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700336 mWindowAttributes.copyFrom(attrs);
Mitsuru Oshima1ecf5d22009-07-06 17:20:38 -0700337 attrs = mWindowAttributes;
Romain Guye4d01122010-06-16 18:44:05 -0700338
Romain Guy529b60a2010-08-03 18:05:47 -0700339 enableHardwareAcceleration(attrs);
Romain Guye4d01122010-06-16 18:44:05 -0700340
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700341 if (view instanceof RootViewSurfaceTaker) {
342 mSurfaceHolderCallback =
343 ((RootViewSurfaceTaker)view).willYouTakeTheSurface();
344 if (mSurfaceHolderCallback != null) {
345 mSurfaceHolder = new TakenSurfaceHolder();
Dianne Hackborn289b9b62010-07-09 11:44:11 -0700346 mSurfaceHolder.setFormat(PixelFormat.UNKNOWN);
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700347 }
348 }
Mitsuru Oshima38ed7d772009-07-21 14:39:34 -0700349 Resources resources = mView.getContext().getResources();
350 CompatibilityInfo compatibilityInfo = resources.getCompatibilityInfo();
Mitsuru Oshima589cebe2009-07-22 20:38:58 -0700351 mTranslator = compatibilityInfo.getTranslator();
Mitsuru Oshima38ed7d772009-07-21 14:39:34 -0700352
353 if (mTranslator != null || !compatibilityInfo.supportsScreen()) {
Mitsuru Oshima240f8a72009-07-22 20:39:14 -0700354 mSurface.setCompatibleDisplayMetrics(resources.getDisplayMetrics(),
355 mTranslator);
Mitsuru Oshima38ed7d772009-07-21 14:39:34 -0700356 }
357
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -0700358 boolean restore = false;
Romain Guy35b38ce2009-10-07 13:38:55 -0700359 if (mTranslator != null) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -0700360 restore = true;
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700361 attrs.backup();
362 mTranslator.translateWindowLayout(attrs);
Mitsuru Oshima3d914922009-05-13 22:29:15 -0700363 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700364 if (DEBUG_LAYOUT) Log.d(TAG, "WindowLayout in setView:" + attrs);
365
Mitsuru Oshima1ecf5d22009-07-06 17:20:38 -0700366 if (!compatibilityInfo.supportsScreen()) {
367 attrs.flags |= WindowManager.LayoutParams.FLAG_COMPATIBLE_WINDOW;
368 }
369
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800370 mSoftInputMode = attrs.softInputMode;
371 mWindowAttributesChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800372 mAttachInfo.mRootView = view;
Romain Guy35b38ce2009-10-07 13:38:55 -0700373 mAttachInfo.mScalingRequired = mTranslator != null;
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700374 mAttachInfo.mApplicationScale =
375 mTranslator == null ? 1.0f : mTranslator.applicationScale;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800376 if (panelParentView != null) {
377 mAttachInfo.mPanelParentWindowToken
378 = panelParentView.getApplicationWindowToken();
379 }
380 mAdded = true;
381 int res; /* = WindowManagerImpl.ADD_OKAY; */
Romain Guy8506ab42009-06-11 17:35:47 -0700382
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800383 // Schedule the first layout -before- adding to the window
384 // manager, to make sure we do the relayout before receiving
385 // any other events from the system.
386 requestLayout();
Jeff Brown46b9ac02010-04-22 18:58:52 -0700387 mInputChannel = new InputChannel();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800388 try {
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700389 res = sWindowSession.add(mWindow, mWindowAttributes,
Jeff Brown46b9ac02010-04-22 18:58:52 -0700390 getHostVisibility(), mAttachInfo.mContentInsets,
391 mInputChannel);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800392 } catch (RemoteException e) {
393 mAdded = false;
394 mView = null;
395 mAttachInfo.mRootView = null;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700396 mInputChannel = null;
Joe Onorato86f67862010-11-05 18:57:34 -0700397 mFallbackEventHandler.setView(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800398 unscheduleTraversals();
399 throw new RuntimeException("Adding window failed", e);
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700400 } finally {
401 if (restore) {
402 attrs.restore();
403 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800404 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700405
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700406 if (mTranslator != null) {
407 mTranslator.translateRectInScreenToAppWindow(mAttachInfo.mContentInsets);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700408 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800409 mPendingContentInsets.set(mAttachInfo.mContentInsets);
410 mPendingVisibleInsets.set(0, 0, 0, 0);
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800411 if (DEBUG_LAYOUT) Log.v(TAG, "Added window " + mWindow);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800412 if (res < WindowManagerImpl.ADD_OKAY) {
413 mView = null;
414 mAttachInfo.mRootView = null;
415 mAdded = false;
Joe Onorato86f67862010-11-05 18:57:34 -0700416 mFallbackEventHandler.setView(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800417 unscheduleTraversals();
418 switch (res) {
419 case WindowManagerImpl.ADD_BAD_APP_TOKEN:
420 case WindowManagerImpl.ADD_BAD_SUBWINDOW_TOKEN:
421 throw new WindowManagerImpl.BadTokenException(
422 "Unable to add window -- token " + attrs.token
423 + " is not valid; is your activity running?");
424 case WindowManagerImpl.ADD_NOT_APP_TOKEN:
425 throw new WindowManagerImpl.BadTokenException(
426 "Unable to add window -- token " + attrs.token
427 + " is not for an application");
428 case WindowManagerImpl.ADD_APP_EXITING:
429 throw new WindowManagerImpl.BadTokenException(
430 "Unable to add window -- app for token " + attrs.token
431 + " is exiting");
432 case WindowManagerImpl.ADD_DUPLICATE_ADD:
433 throw new WindowManagerImpl.BadTokenException(
434 "Unable to add window -- window " + mWindow
435 + " has already been added");
436 case WindowManagerImpl.ADD_STARTING_NOT_NEEDED:
437 // Silently ignore -- we would have just removed it
438 // right away, anyway.
439 return;
440 case WindowManagerImpl.ADD_MULTIPLE_SINGLETON:
441 throw new WindowManagerImpl.BadTokenException(
442 "Unable to add window " + mWindow +
443 " -- another window of this type already exists");
444 case WindowManagerImpl.ADD_PERMISSION_DENIED:
445 throw new WindowManagerImpl.BadTokenException(
446 "Unable to add window " + mWindow +
447 " -- permission denied for this window type");
448 }
449 throw new RuntimeException(
450 "Unable to add window -- unknown error code " + res);
451 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700452
Jeff Brown00fa7bd2010-07-02 15:37:36 -0700453 if (view instanceof RootViewSurfaceTaker) {
454 mInputQueueCallback =
455 ((RootViewSurfaceTaker)view).willYouTakeTheInputQueue();
456 }
457 if (mInputQueueCallback != null) {
458 mInputQueue = new InputQueue(mInputChannel);
459 mInputQueueCallback.onInputQueueCreated(mInputQueue);
460 } else {
461 InputQueue.registerInputChannel(mInputChannel, mInputHandler,
462 Looper.myQueue());
Jeff Brown46b9ac02010-04-22 18:58:52 -0700463 }
464
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800465 view.assignParent(this);
466 mAddedTouchMode = (res&WindowManagerImpl.ADD_FLAG_IN_TOUCH_MODE) != 0;
467 mAppVisible = (res&WindowManagerImpl.ADD_FLAG_APP_VISIBLE) != 0;
468 }
469 }
470 }
471
Romain Guy529b60a2010-08-03 18:05:47 -0700472 private void enableHardwareAcceleration(WindowManager.LayoutParams attrs) {
Dianne Hackborn7eec10e2010-11-12 18:03:47 -0800473 mAttachInfo.mHardwareAccelerated = false;
474 mAttachInfo.mHardwareAccelerationRequested = false;
475
476 // Try to enable hardware acceleration if requested
477 if (attrs != null &&
478 (attrs.flags & WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED) != 0) {
479 // Only enable hardware acceleration if we are not in the system process
480 // The window manager creates ViewRoots to display animated preview windows
481 // of launching apps and we don't want those to be hardware accelerated
482 if (!HardwareRenderer.sRendererDisabled) {
Romain Guye4d01122010-06-16 18:44:05 -0700483 final boolean translucent = attrs.format != PixelFormat.OPAQUE;
Romain Guyb051e892010-09-28 19:09:36 -0700484 if (mAttachInfo.mHardwareRenderer != null) {
485 mAttachInfo.mHardwareRenderer.destroy(true);
Romain Guy4caa4ed2010-08-25 14:46:24 -0700486 }
Romain Guyb051e892010-09-28 19:09:36 -0700487 mAttachInfo.mHardwareRenderer = HardwareRenderer.createGlRenderer(2, translucent);
Dianne Hackborn7eec10e2010-11-12 18:03:47 -0800488 mAttachInfo.mHardwareAccelerated = mAttachInfo.mHardwareAccelerationRequested
489 = mAttachInfo.mHardwareRenderer != null;
490 } else if (HardwareRenderer.isAvailable()) {
491 mAttachInfo.mHardwareAccelerationRequested = true;
Romain Guye4d01122010-06-16 18:44:05 -0700492 }
493 }
494 }
495
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800496 public View getView() {
497 return mView;
498 }
499
500 final WindowLeaked getLocation() {
501 return mLocation;
502 }
503
504 void setLayoutParams(WindowManager.LayoutParams attrs, boolean newView) {
505 synchronized (this) {
The Android Open Source Project10592532009-03-18 17:39:46 -0700506 int oldSoftInputMode = mWindowAttributes.softInputMode;
Mitsuru Oshima5a2b91d2009-07-16 16:30:02 -0700507 // preserve compatible window flag if exists.
508 int compatibleWindowFlag =
509 mWindowAttributes.flags & WindowManager.LayoutParams.FLAG_COMPATIBLE_WINDOW;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800510 mWindowAttributes.copyFrom(attrs);
Mitsuru Oshima5a2b91d2009-07-16 16:30:02 -0700511 mWindowAttributes.flags |= compatibleWindowFlag;
512
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800513 if (newView) {
514 mSoftInputMode = attrs.softInputMode;
515 requestLayout();
516 }
The Android Open Source Project10592532009-03-18 17:39:46 -0700517 // Don't lose the mode we last auto-computed.
518 if ((attrs.softInputMode&WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST)
519 == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED) {
520 mWindowAttributes.softInputMode = (mWindowAttributes.softInputMode
521 & ~WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST)
522 | (oldSoftInputMode
523 & WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST);
524 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800525 mWindowAttributesChanged = true;
526 scheduleTraversals();
527 }
528 }
529
530 void handleAppVisibility(boolean visible) {
531 if (mAppVisible != visible) {
532 mAppVisible = visible;
533 scheduleTraversals();
534 }
535 }
536
537 void handleGetNewSurface() {
538 mNewSurfaceNeeded = true;
539 mFullRedrawNeeded = true;
540 scheduleTraversals();
541 }
542
543 /**
544 * {@inheritDoc}
545 */
546 public void requestLayout() {
547 checkThread();
548 mLayoutRequested = true;
549 scheduleTraversals();
550 }
551
552 /**
553 * {@inheritDoc}
554 */
555 public boolean isLayoutRequested() {
556 return mLayoutRequested;
557 }
558
559 public void invalidateChild(View child, Rect dirty) {
560 checkThread();
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700561 if (DEBUG_DRAW) Log.v(TAG, "Invalidate child: " + dirty);
Chet Haase70d4ba12010-10-06 09:46:45 -0700562 if (dirty == null) {
563 // Fast invalidation for GL-enabled applications; GL must redraw everything
564 invalidate();
565 return;
566 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700567 if (mCurScrollY != 0 || mTranslator != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800568 mTempRect.set(dirty);
Romain Guy1e095972009-07-07 11:22:45 -0700569 dirty = mTempRect;
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700570 if (mCurScrollY != 0) {
Romain Guy1e095972009-07-07 11:22:45 -0700571 dirty.offset(0, -mCurScrollY);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700572 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700573 if (mTranslator != null) {
Romain Guy1e095972009-07-07 11:22:45 -0700574 mTranslator.translateRectInAppWindowToScreen(dirty);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700575 }
Romain Guy1e095972009-07-07 11:22:45 -0700576 if (mAttachInfo.mScalingRequired) {
577 dirty.inset(-1, -1);
578 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800579 }
580 mDirty.union(dirty);
581 if (!mWillDrawSoon) {
582 scheduleTraversals();
583 }
584 }
Romain Guy0d9275e2010-10-26 14:22:30 -0700585
586 void invalidate() {
587 mDirty.set(0, 0, mWidth, mHeight);
588 scheduleTraversals();
589 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800590
591 public ViewParent getParent() {
592 return null;
593 }
594
595 public ViewParent invalidateChildInParent(final int[] location, final Rect dirty) {
596 invalidateChild(null, dirty);
597 return null;
598 }
599
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700600 public boolean getChildVisibleRect(View child, Rect r, android.graphics.Point offset) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800601 if (child != mView) {
602 throw new RuntimeException("child is not mine, honest!");
603 }
604 // Note: don't apply scroll offset, because we want to know its
605 // visibility in the virtual canvas being given to the view hierarchy.
606 return r.intersect(0, 0, mWidth, mHeight);
607 }
608
609 public void bringChildToFront(View child) {
610 }
611
612 public void scheduleTraversals() {
613 if (!mTraversalScheduled) {
614 mTraversalScheduled = true;
615 sendEmptyMessage(DO_TRAVERSAL);
616 }
617 }
618
619 public void unscheduleTraversals() {
620 if (mTraversalScheduled) {
621 mTraversalScheduled = false;
622 removeMessages(DO_TRAVERSAL);
623 }
624 }
625
626 int getHostVisibility() {
627 return mAppVisible ? mView.getVisibility() : View.GONE;
628 }
Romain Guy8506ab42009-06-11 17:35:47 -0700629
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800630 private void performTraversals() {
631 // cache mView since it is used so much below...
632 final View host = mView;
633
634 if (DBG) {
635 System.out.println("======================================");
636 System.out.println("performTraversals");
637 host.debug();
638 }
639
640 if (host == null || !mAdded)
641 return;
642
643 mTraversalScheduled = false;
644 mWillDrawSoon = true;
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800645 boolean windowSizeMayChange = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800646 boolean fullRedrawNeeded = mFullRedrawNeeded;
647 boolean newSurface = false;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700648 boolean surfaceChanged = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800649 WindowManager.LayoutParams lp = mWindowAttributes;
650
651 int desiredWindowWidth;
652 int desiredWindowHeight;
653 int childWidthMeasureSpec;
654 int childHeightMeasureSpec;
655
656 final View.AttachInfo attachInfo = mAttachInfo;
657
658 final int viewVisibility = getHostVisibility();
659 boolean viewVisibilityChanged = mViewVisibility != viewVisibility
660 || mNewSurfaceNeeded;
661
662 WindowManager.LayoutParams params = null;
663 if (mWindowAttributesChanged) {
664 mWindowAttributesChanged = false;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700665 surfaceChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800666 params = lp;
667 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700668 Rect frame = mWinFrame;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800669 if (mFirst) {
670 fullRedrawNeeded = true;
671 mLayoutRequested = true;
672
Romain Guy8506ab42009-06-11 17:35:47 -0700673 DisplayMetrics packageMetrics =
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700674 mView.getContext().getResources().getDisplayMetrics();
675 desiredWindowWidth = packageMetrics.widthPixels;
676 desiredWindowHeight = packageMetrics.heightPixels;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800677
678 // For the very first time, tell the view hierarchy that it
679 // is attached to the window. Note that at this point the surface
680 // object is not initialized to its backing store, but soon it
681 // will be (assuming the window is visible).
682 attachInfo.mSurface = mSurface;
Adam Powell26153a32010-11-08 15:22:27 -0800683 attachInfo.mUse32BitDrawingCache = PixelFormat.formatHasAlpha(lp.format) ||
684 lp.format == PixelFormat.RGBX_8888;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800685 attachInfo.mHasWindowFocus = false;
686 attachInfo.mWindowVisibility = viewVisibility;
687 attachInfo.mRecomputeGlobalAttributes = false;
688 attachInfo.mKeepScreenOn = false;
689 viewVisibilityChanged = false;
Dianne Hackborn694f79b2010-03-17 19:44:59 -0700690 mLastConfiguration.setTo(host.getResources().getConfiguration());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800691 host.dispatchAttachedToWindow(attachInfo, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800692 //Log.i(TAG, "Screen on initialized: " + attachInfo.mKeepScreenOn);
svetoslavganov75986cf2009-05-14 22:28:01 -0700693
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800694 } else {
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700695 desiredWindowWidth = frame.width();
696 desiredWindowHeight = frame.height();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800697 if (desiredWindowWidth != mWidth || desiredWindowHeight != mHeight) {
Jeff Brownc5ed5912010-07-14 18:48:53 -0700698 if (DEBUG_ORIENTATION) Log.v(TAG,
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700699 "View " + host + " resized to: " + frame);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800700 fullRedrawNeeded = true;
701 mLayoutRequested = true;
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800702 windowSizeMayChange = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800703 }
704 }
705
706 if (viewVisibilityChanged) {
707 attachInfo.mWindowVisibility = viewVisibility;
708 host.dispatchWindowVisibilityChanged(viewVisibility);
709 if (viewVisibility != View.VISIBLE || mNewSurfaceNeeded) {
Romain Guyb051e892010-09-28 19:09:36 -0700710 if (mAttachInfo.mHardwareRenderer != null) {
711 mAttachInfo.mHardwareRenderer.destroy(false);
Romain Guy4caa4ed2010-08-25 14:46:24 -0700712 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800713 }
714 if (viewVisibility == View.GONE) {
715 // After making a window gone, we will count it as being
716 // shown for the first time the next time it gets focus.
717 mHasHadWindowFocus = false;
718 }
719 }
720
721 boolean insetsChanged = false;
Romain Guy8506ab42009-06-11 17:35:47 -0700722
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800723 if (mLayoutRequested) {
Romain Guy15df6702009-08-17 20:17:30 -0700724 // Execute enqueued actions on every layout in case a view that was detached
725 // enqueued an action after being detached
726 getRunQueue().executeActions(attachInfo.mHandler);
727
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800728 final Resources res = mView.getContext().getResources();
729
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800730 if (mFirst) {
731 host.fitSystemWindows(mAttachInfo.mContentInsets);
732 // make sure touch mode code executes by setting cached value
733 // to opposite of the added touch mode.
734 mAttachInfo.mInTouchMode = !mAddedTouchMode;
Romain Guy2d4cff62010-04-09 15:39:00 -0700735 ensureTouchModeLocally(mAddedTouchMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800736 } else {
737 if (!mAttachInfo.mContentInsets.equals(mPendingContentInsets)) {
738 mAttachInfo.mContentInsets.set(mPendingContentInsets);
739 host.fitSystemWindows(mAttachInfo.mContentInsets);
740 insetsChanged = true;
741 if (DEBUG_LAYOUT) Log.v(TAG, "Content insets changing to: "
742 + mAttachInfo.mContentInsets);
743 }
744 if (!mAttachInfo.mVisibleInsets.equals(mPendingVisibleInsets)) {
745 mAttachInfo.mVisibleInsets.set(mPendingVisibleInsets);
746 if (DEBUG_LAYOUT) Log.v(TAG, "Visible insets changing to: "
747 + mAttachInfo.mVisibleInsets);
748 }
749 if (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT
750 || lp.height == ViewGroup.LayoutParams.WRAP_CONTENT) {
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800751 windowSizeMayChange = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800752
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800753 DisplayMetrics packageMetrics = res.getDisplayMetrics();
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700754 desiredWindowWidth = packageMetrics.widthPixels;
755 desiredWindowHeight = packageMetrics.heightPixels;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800756 }
757 }
758
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800759 // Ask host how big it wants to be
Jeff Brownc5ed5912010-07-14 18:48:53 -0700760 if (DEBUG_ORIENTATION || DEBUG_LAYOUT) Log.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800761 "Measuring " + host + " in display " + desiredWindowWidth
762 + "x" + desiredWindowHeight + "...");
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800763
764 boolean goodMeasure = false;
765 if (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT
766 || lp.height == ViewGroup.LayoutParams.WRAP_CONTENT) {
767 // On large screens, we don't want to allow dialogs to just
768 // stretch to fill the entire width of the screen to display
769 // one line of text. First try doing the layout at a smaller
770 // size to see if it will fit.
771 final DisplayMetrics packageMetrics = res.getDisplayMetrics();
772 res.getValue(com.android.internal.R.dimen.config_prefDialogWidth, mTmpValue, true);
773 int baseSize = 0;
774 if (mTmpValue.type == TypedValue.TYPE_DIMENSION) {
775 baseSize = (int)mTmpValue.getDimension(packageMetrics);
776 }
777 if (DEBUG_DIALOG) Log.v(TAG, "Window " + mView + ": baseSize=" + baseSize);
778 if (desiredWindowWidth > baseSize) {
779 int maxHeight = (desiredWindowHeight*2)/3;
780 childWidthMeasureSpec = getRootMeasureSpec(baseSize, lp.width);
781 childHeightMeasureSpec = getRootMeasureSpec(desiredWindowHeight, lp.height);
782 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
783 if (DEBUG_DIALOG) Log.v(TAG, "Window " + mView + ": measured ("
784 + host.getWidth() + "," + host.getHeight() + ")");
785 // Note: for now we are not taking into account height, since we
786 // can't distinguish between places where it would be useful to
787 // increase the width (text) vs. where it would not (a list).
788 // Maybe we can just try the next size up, and see if that reduces
789 // the height?
790 if (host.getWidth() <= baseSize /*&& host.getHeight() <= maxHeight*/) {
791 Log.v(TAG, "Good!");
792 goodMeasure = true;
793 } else {
794 // Didn't fit in that size... try expanding a bit.
795 baseSize = (baseSize+desiredWindowWidth)/2;
796 if (DEBUG_DIALOG) Log.v(TAG, "Window " + mView + ": next baseSize="
797 + baseSize);
798 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
799 if (DEBUG_DIALOG) Log.v(TAG, "Window " + mView + ": measured ("
800 + host.getWidth() + "," + host.getHeight() + ")");
801 if (host.getWidth() <= baseSize /*&& host.getHeight() <= maxHeight*/) {
802 if (DEBUG_DIALOG) Log.v(TAG, "Good!");
803 goodMeasure = true;
804 }
805 }
806 }
807 }
808
809 if (!goodMeasure) {
810 childWidthMeasureSpec = getRootMeasureSpec(desiredWindowWidth, lp.width);
811 childHeightMeasureSpec = getRootMeasureSpec(desiredWindowHeight, lp.height);
812 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
813 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800814
815 if (DBG) {
816 System.out.println("======================================");
817 System.out.println("performTraversals -- after measure");
818 host.debug();
819 }
820 }
821
822 if (attachInfo.mRecomputeGlobalAttributes) {
823 //Log.i(TAG, "Computing screen on!");
824 attachInfo.mRecomputeGlobalAttributes = false;
825 boolean oldVal = attachInfo.mKeepScreenOn;
826 attachInfo.mKeepScreenOn = false;
827 host.dispatchCollectViewAttributes(0);
828 if (attachInfo.mKeepScreenOn != oldVal) {
829 params = lp;
830 //Log.i(TAG, "Keep screen on changed: " + attachInfo.mKeepScreenOn);
831 }
832 }
833
834 if (mFirst || attachInfo.mViewVisibilityChanged) {
835 attachInfo.mViewVisibilityChanged = false;
836 int resizeMode = mSoftInputMode &
837 WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST;
838 // If we are in auto resize mode, then we need to determine
839 // what mode to use now.
840 if (resizeMode == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED) {
841 final int N = attachInfo.mScrollContainers.size();
842 for (int i=0; i<N; i++) {
843 if (attachInfo.mScrollContainers.get(i).isShown()) {
844 resizeMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE;
845 }
846 }
847 if (resizeMode == 0) {
848 resizeMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN;
849 }
850 if ((lp.softInputMode &
851 WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) != resizeMode) {
852 lp.softInputMode = (lp.softInputMode &
853 ~WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) |
854 resizeMode;
855 params = lp;
856 }
857 }
858 }
Romain Guy8506ab42009-06-11 17:35:47 -0700859
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800860 if (params != null && (host.mPrivateFlags & View.REQUEST_TRANSPARENT_REGIONS) != 0) {
861 if (!PixelFormat.formatHasAlpha(params.format)) {
862 params.format = PixelFormat.TRANSLUCENT;
863 }
864 }
865
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800866 boolean windowShouldResize = mLayoutRequested && windowSizeMayChange
Romain Guy2e4f4262010-04-06 11:07:52 -0700867 && ((mWidth != host.mMeasuredWidth || mHeight != host.mMeasuredHeight)
868 || (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT &&
869 frame.width() < desiredWindowWidth && frame.width() != mWidth)
870 || (lp.height == ViewGroup.LayoutParams.WRAP_CONTENT &&
871 frame.height() < desiredWindowHeight && frame.height() != mHeight));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800872
873 final boolean computesInternalInsets =
874 attachInfo.mTreeObserver.hasComputeInternalInsetsListeners();
Romain Guy812ccbe2010-06-01 14:07:24 -0700875
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800876 boolean insetsPending = false;
877 int relayoutResult = 0;
Romain Guy812ccbe2010-06-01 14:07:24 -0700878
879 if (mFirst || windowShouldResize || insetsChanged ||
880 viewVisibilityChanged || params != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800881
882 if (viewVisibility == View.VISIBLE) {
883 // If this window is giving internal insets to the window
884 // manager, and it is being added or changing its visibility,
885 // then we want to first give the window manager "fake"
886 // insets to cause it to effectively ignore the content of
887 // the window during layout. This avoids it briefly causing
888 // other windows to resize/move based on the raw frame of the
889 // window, waiting until we can finish laying out this window
890 // and get back to the window manager with the ultimately
891 // computed insets.
Romain Guy812ccbe2010-06-01 14:07:24 -0700892 insetsPending = computesInternalInsets && (mFirst || viewVisibilityChanged);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800893 }
894
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700895 if (mSurfaceHolder != null) {
896 mSurfaceHolder.mSurfaceLock.lock();
897 mDrawingAllowed = true;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700898 }
Romain Guy812ccbe2010-06-01 14:07:24 -0700899
Romain Guyc361da82010-10-25 15:29:10 -0700900 boolean hwInitialized = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800901 boolean contentInsetsChanged = false;
Romain Guy13922e02009-05-12 17:56:14 -0700902 boolean visibleInsetsChanged;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700903 boolean hadSurface = mSurface.isValid();
Romain Guy812ccbe2010-06-01 14:07:24 -0700904
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800905 try {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800906 int fl = 0;
907 if (params != null) {
908 fl = params.flags;
909 if (attachInfo.mKeepScreenOn) {
910 params.flags |= WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
911 }
912 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700913 if (DEBUG_LAYOUT) {
914 Log.i(TAG, "host=w:" + host.mMeasuredWidth + ", h:" +
915 host.mMeasuredHeight + ", params=" + params);
916 }
917 relayoutResult = relayoutWindow(params, viewVisibility, insetsPending);
918
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800919 if (params != null) {
920 params.flags = fl;
921 }
922
923 if (DEBUG_LAYOUT) Log.v(TAG, "relayout: frame=" + frame.toShortString()
924 + " content=" + mPendingContentInsets.toShortString()
925 + " visible=" + mPendingVisibleInsets.toShortString()
926 + " surface=" + mSurface);
Romain Guy8506ab42009-06-11 17:35:47 -0700927
Dianne Hackborn694f79b2010-03-17 19:44:59 -0700928 if (mPendingConfiguration.seq != 0) {
929 if (DEBUG_CONFIGURATION) Log.v(TAG, "Visible with new config: "
930 + mPendingConfiguration);
931 updateConfiguration(mPendingConfiguration, !mFirst);
932 mPendingConfiguration.seq = 0;
933 }
934
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800935 contentInsetsChanged = !mPendingContentInsets.equals(
936 mAttachInfo.mContentInsets);
937 visibleInsetsChanged = !mPendingVisibleInsets.equals(
938 mAttachInfo.mVisibleInsets);
939 if (contentInsetsChanged) {
940 mAttachInfo.mContentInsets.set(mPendingContentInsets);
941 host.fitSystemWindows(mAttachInfo.mContentInsets);
942 if (DEBUG_LAYOUT) Log.v(TAG, "Content insets changing to: "
943 + mAttachInfo.mContentInsets);
944 }
945 if (visibleInsetsChanged) {
946 mAttachInfo.mVisibleInsets.set(mPendingVisibleInsets);
947 if (DEBUG_LAYOUT) Log.v(TAG, "Visible insets changing to: "
948 + mAttachInfo.mVisibleInsets);
949 }
950
951 if (!hadSurface) {
952 if (mSurface.isValid()) {
953 // If we are creating a new surface, then we need to
954 // completely redraw it. Also, when we get to the
955 // point of drawing it we will hold off and schedule
956 // a new traversal instead. This is so we can tell the
957 // window manager about all of the windows being displayed
958 // before actually drawing them, so it can display then
959 // all at once.
960 newSurface = true;
961 fullRedrawNeeded = true;
Jack Palevich61a6e682009-10-09 17:37:50 -0700962 mPreviousTransparentRegion.setEmpty();
Romain Guy8506ab42009-06-11 17:35:47 -0700963
Romain Guyb051e892010-09-28 19:09:36 -0700964 if (mAttachInfo.mHardwareRenderer != null) {
Romain Guyc361da82010-10-25 15:29:10 -0700965 hwInitialized = mAttachInfo.mHardwareRenderer.initialize(mHolder);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800966 }
967 }
968 } else if (!mSurface.isValid()) {
969 // If the surface has been removed, then reset the scroll
970 // positions.
971 mLastScrolledFocus = null;
972 mScrollY = mCurScrollY = 0;
973 if (mScroller != null) {
974 mScroller.abortAnimation();
975 }
976 }
977 } catch (RemoteException e) {
978 }
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700979
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800980 if (DEBUG_ORIENTATION) Log.v(
Jeff Brownc5ed5912010-07-14 18:48:53 -0700981 TAG, "Relayout returned: frame=" + frame + ", surface=" + mSurface);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800982
983 attachInfo.mWindowLeft = frame.left;
984 attachInfo.mWindowTop = frame.top;
985
986 // !!FIXME!! This next section handles the case where we did not get the
987 // window size we asked for. We should avoid this by getting a maximum size from
988 // the window session beforehand.
989 mWidth = frame.width();
990 mHeight = frame.height();
991
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700992 if (mSurfaceHolder != null) {
993 // The app owns the surface; tell it about what is going on.
994 if (mSurface.isValid()) {
995 // XXX .copyFrom() doesn't work!
996 //mSurfaceHolder.mSurface.copyFrom(mSurface);
997 mSurfaceHolder.mSurface = mSurface;
998 }
999 mSurfaceHolder.mSurfaceLock.unlock();
1000 if (mSurface.isValid()) {
1001 if (!hadSurface) {
1002 mSurfaceHolder.ungetCallbacks();
1003
1004 mIsCreating = true;
1005 mSurfaceHolderCallback.surfaceCreated(mSurfaceHolder);
1006 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
1007 if (callbacks != null) {
1008 for (SurfaceHolder.Callback c : callbacks) {
1009 c.surfaceCreated(mSurfaceHolder);
1010 }
1011 }
1012 surfaceChanged = true;
Romain Guyc361da82010-10-25 15:29:10 -07001013
1014 if (mAttachInfo.mHardwareRenderer != null) {
1015 // This will bail out early if already initialized
1016 mAttachInfo.mHardwareRenderer.initialize(mHolder);
1017 }
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001018 }
1019 if (surfaceChanged) {
1020 mSurfaceHolderCallback.surfaceChanged(mSurfaceHolder,
1021 lp.format, mWidth, mHeight);
1022 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
1023 if (callbacks != null) {
1024 for (SurfaceHolder.Callback c : callbacks) {
1025 c.surfaceChanged(mSurfaceHolder, lp.format,
1026 mWidth, mHeight);
1027 }
1028 }
1029 }
1030 mIsCreating = false;
1031 } else if (hadSurface) {
1032 mSurfaceHolder.ungetCallbacks();
1033 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
1034 mSurfaceHolderCallback.surfaceDestroyed(mSurfaceHolder);
1035 if (callbacks != null) {
1036 for (SurfaceHolder.Callback c : callbacks) {
1037 c.surfaceDestroyed(mSurfaceHolder);
1038 }
1039 }
1040 mSurfaceHolder.mSurfaceLock.lock();
1041 // Make surface invalid.
1042 //mSurfaceHolder.mSurface.copyFrom(mSurface);
1043 mSurfaceHolder.mSurface = new Surface();
1044 mSurfaceHolder.mSurfaceLock.unlock();
1045 }
1046 }
Romain Guy53389bd2010-09-07 17:16:32 -07001047
Romain Guyc361da82010-10-25 15:29:10 -07001048 if (hwInitialized || (windowShouldResize && mAttachInfo.mHardwareRenderer != null)) {
Romain Guyb051e892010-09-28 19:09:36 -07001049 mAttachInfo.mHardwareRenderer.setup(mWidth, mHeight);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001050 }
1051
1052 boolean focusChangedDueToTouchMode = ensureTouchModeLocally(
Romain Guy2d4cff62010-04-09 15:39:00 -07001053 (relayoutResult&WindowManagerImpl.RELAYOUT_IN_TOUCH_MODE) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001054 if (focusChangedDueToTouchMode || mWidth != host.mMeasuredWidth
1055 || mHeight != host.mMeasuredHeight || contentInsetsChanged) {
1056 childWidthMeasureSpec = getRootMeasureSpec(mWidth, lp.width);
1057 childHeightMeasureSpec = getRootMeasureSpec(mHeight, lp.height);
1058
1059 if (DEBUG_LAYOUT) Log.v(TAG, "Ooops, something changed! mWidth="
1060 + mWidth + " measuredWidth=" + host.mMeasuredWidth
1061 + " mHeight=" + mHeight
1062 + " measuredHeight" + host.mMeasuredHeight
1063 + " coveredInsetsChanged=" + contentInsetsChanged);
Romain Guy8506ab42009-06-11 17:35:47 -07001064
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001065 // Ask host how big it wants to be
1066 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
1067
1068 // Implementation of weights from WindowManager.LayoutParams
1069 // We just grow the dimensions as needed and re-measure if
1070 // needs be
1071 int width = host.mMeasuredWidth;
1072 int height = host.mMeasuredHeight;
1073 boolean measureAgain = false;
1074
1075 if (lp.horizontalWeight > 0.0f) {
1076 width += (int) ((mWidth - width) * lp.horizontalWeight);
1077 childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(width,
1078 MeasureSpec.EXACTLY);
1079 measureAgain = true;
1080 }
1081 if (lp.verticalWeight > 0.0f) {
1082 height += (int) ((mHeight - height) * lp.verticalWeight);
1083 childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(height,
1084 MeasureSpec.EXACTLY);
1085 measureAgain = true;
1086 }
1087
1088 if (measureAgain) {
1089 if (DEBUG_LAYOUT) Log.v(TAG,
1090 "And hey let's measure once more: width=" + width
1091 + " height=" + height);
1092 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
1093 }
1094
1095 mLayoutRequested = true;
1096 }
1097 }
1098
1099 final boolean didLayout = mLayoutRequested;
1100 boolean triggerGlobalLayoutListener = didLayout
1101 || attachInfo.mRecomputeGlobalAttributes;
1102 if (didLayout) {
1103 mLayoutRequested = false;
1104 mScrollMayChange = true;
1105 if (DEBUG_ORIENTATION || DEBUG_LAYOUT) Log.v(
Jeff Brownc5ed5912010-07-14 18:48:53 -07001106 TAG, "Laying out " + host + " to (" +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001107 host.mMeasuredWidth + ", " + host.mMeasuredHeight + ")");
Romain Guy13922e02009-05-12 17:56:14 -07001108 long startTime = 0L;
Romain Guy5429e1d2010-09-07 12:38:00 -07001109 if (ViewDebug.DEBUG_PROFILE_LAYOUT) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001110 startTime = SystemClock.elapsedRealtime();
1111 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001112 host.layout(0, 0, host.mMeasuredWidth, host.mMeasuredHeight);
1113
Romain Guy13922e02009-05-12 17:56:14 -07001114 if (Config.DEBUG && ViewDebug.consistencyCheckEnabled) {
1115 if (!host.dispatchConsistencyCheck(ViewDebug.CONSISTENCY_LAYOUT)) {
1116 throw new IllegalStateException("The view hierarchy is an inconsistent state,"
1117 + "please refer to the logs with the tag "
1118 + ViewDebug.CONSISTENCY_LOG_TAG + " for more infomation.");
1119 }
1120 }
1121
Romain Guy5429e1d2010-09-07 12:38:00 -07001122 if (ViewDebug.DEBUG_PROFILE_LAYOUT) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001123 EventLog.writeEvent(60001, SystemClock.elapsedRealtime() - startTime);
1124 }
1125
1126 // By this point all views have been sized and positionned
1127 // We can compute the transparent area
1128
1129 if ((host.mPrivateFlags & View.REQUEST_TRANSPARENT_REGIONS) != 0) {
1130 // start out transparent
1131 // TODO: AVOID THAT CALL BY CACHING THE RESULT?
1132 host.getLocationInWindow(mTmpLocation);
1133 mTransparentRegion.set(mTmpLocation[0], mTmpLocation[1],
1134 mTmpLocation[0] + host.mRight - host.mLeft,
1135 mTmpLocation[1] + host.mBottom - host.mTop);
1136
1137 host.gatherTransparentRegion(mTransparentRegion);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001138 if (mTranslator != null) {
1139 mTranslator.translateRegionInWindowToScreen(mTransparentRegion);
1140 }
1141
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001142 if (!mTransparentRegion.equals(mPreviousTransparentRegion)) {
1143 mPreviousTransparentRegion.set(mTransparentRegion);
1144 // reconfigure window manager
1145 try {
1146 sWindowSession.setTransparentRegion(mWindow, mTransparentRegion);
1147 } catch (RemoteException e) {
1148 }
1149 }
1150 }
1151
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001152 if (DBG) {
1153 System.out.println("======================================");
1154 System.out.println("performTraversals -- after setFrame");
1155 host.debug();
1156 }
1157 }
1158
1159 if (triggerGlobalLayoutListener) {
1160 attachInfo.mRecomputeGlobalAttributes = false;
1161 attachInfo.mTreeObserver.dispatchOnGlobalLayout();
1162 }
1163
1164 if (computesInternalInsets) {
1165 ViewTreeObserver.InternalInsetsInfo insets = attachInfo.mGivenInternalInsets;
1166 final Rect givenContent = attachInfo.mGivenInternalInsets.contentInsets;
1167 final Rect givenVisible = attachInfo.mGivenInternalInsets.visibleInsets;
1168 givenContent.left = givenContent.top = givenContent.right
1169 = givenContent.bottom = givenVisible.left = givenVisible.top
1170 = givenVisible.right = givenVisible.bottom = 0;
1171 attachInfo.mTreeObserver.dispatchOnComputeInternalInsets(insets);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001172 Rect contentInsets = insets.contentInsets;
1173 Rect visibleInsets = insets.visibleInsets;
1174 if (mTranslator != null) {
1175 contentInsets = mTranslator.getTranslatedContentInsets(contentInsets);
1176 visibleInsets = mTranslator.getTranslatedVisbileInsets(visibleInsets);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001177 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001178 if (insetsPending || !mLastGivenInsets.equals(insets)) {
1179 mLastGivenInsets.set(insets);
1180 try {
1181 sWindowSession.setInsets(mWindow, insets.mTouchableInsets,
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001182 contentInsets, visibleInsets);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001183 } catch (RemoteException e) {
1184 }
1185 }
1186 }
Romain Guy8506ab42009-06-11 17:35:47 -07001187
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001188 if (mFirst) {
1189 // handle first focus request
1190 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: mView.hasFocus()="
1191 + mView.hasFocus());
1192 if (mView != null) {
1193 if (!mView.hasFocus()) {
1194 mView.requestFocus(View.FOCUS_FORWARD);
1195 mFocusedView = mRealFocusedView = mView.findFocus();
1196 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: requested focused view="
1197 + mFocusedView);
1198 } else {
1199 mRealFocusedView = mView.findFocus();
1200 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: existing focused view="
1201 + mRealFocusedView);
1202 }
1203 }
1204 }
1205
1206 mFirst = false;
1207 mWillDrawSoon = false;
1208 mNewSurfaceNeeded = false;
1209 mViewVisibility = viewVisibility;
1210
1211 if (mAttachInfo.mHasWindowFocus) {
1212 final boolean imTarget = WindowManager.LayoutParams
1213 .mayUseInputMethod(mWindowAttributes.flags);
1214 if (imTarget != mLastWasImTarget) {
1215 mLastWasImTarget = imTarget;
1216 InputMethodManager imm = InputMethodManager.peekInstance();
1217 if (imm != null && imTarget) {
1218 imm.startGettingWindowFocus(mView);
1219 imm.onWindowFocus(mView, mView.findFocus(),
1220 mWindowAttributes.softInputMode,
1221 !mHasHadWindowFocus, mWindowAttributes.flags);
1222 }
1223 }
1224 }
Romain Guy8506ab42009-06-11 17:35:47 -07001225
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001226 boolean cancelDraw = attachInfo.mTreeObserver.dispatchOnPreDraw();
1227
1228 if (!cancelDraw && !newSurface) {
1229 mFullRedrawNeeded = false;
1230 draw(fullRedrawNeeded);
1231
1232 if ((relayoutResult&WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0
1233 || mReportNextDraw) {
1234 if (LOCAL_LOGV) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001235 Log.v(TAG, "FINISHED DRAWING: " + mWindowAttributes.getTitle());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001236 }
1237 mReportNextDraw = false;
Dianne Hackbornd76b67c2010-07-13 17:48:30 -07001238 if (mSurfaceHolder != null && mSurface.isValid()) {
1239 mSurfaceHolderCallback.surfaceRedrawNeeded(mSurfaceHolder);
1240 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
1241 if (callbacks != null) {
1242 for (SurfaceHolder.Callback c : callbacks) {
1243 if (c instanceof SurfaceHolder.Callback2) {
1244 ((SurfaceHolder.Callback2)c).surfaceRedrawNeeded(
1245 mSurfaceHolder);
1246 }
1247 }
1248 }
1249 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001250 try {
1251 sWindowSession.finishDrawing(mWindow);
1252 } catch (RemoteException e) {
1253 }
1254 }
1255 } else {
1256 // We were supposed to report when we are done drawing. Since we canceled the
1257 // draw, remember it here.
1258 if ((relayoutResult&WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0) {
1259 mReportNextDraw = true;
1260 }
1261 if (fullRedrawNeeded) {
1262 mFullRedrawNeeded = true;
1263 }
1264 // Try again
1265 scheduleTraversals();
1266 }
1267 }
1268
1269 public void requestTransparentRegion(View child) {
1270 // the test below should not fail unless someone is messing with us
1271 checkThread();
1272 if (mView == child) {
1273 mView.mPrivateFlags |= View.REQUEST_TRANSPARENT_REGIONS;
1274 // Need to make sure we re-evaluate the window attributes next
1275 // time around, to ensure the window has the correct format.
1276 mWindowAttributesChanged = true;
Mathias Agopian1bd80ad2010-11-04 17:13:39 -07001277 requestLayout();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001278 }
1279 }
1280
1281 /**
1282 * Figures out the measure spec for the root view in a window based on it's
1283 * layout params.
1284 *
1285 * @param windowSize
1286 * The available width or height of the window
1287 *
1288 * @param rootDimension
1289 * The layout params for one dimension (width or height) of the
1290 * window.
1291 *
1292 * @return The measure spec to use to measure the root view.
1293 */
1294 private int getRootMeasureSpec(int windowSize, int rootDimension) {
1295 int measureSpec;
1296 switch (rootDimension) {
1297
Romain Guy980a9382010-01-08 15:06:28 -08001298 case ViewGroup.LayoutParams.MATCH_PARENT:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001299 // Window can't resize. Force root view to be windowSize.
1300 measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.EXACTLY);
1301 break;
1302 case ViewGroup.LayoutParams.WRAP_CONTENT:
1303 // Window can resize. Set max size for root view.
1304 measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.AT_MOST);
1305 break;
1306 default:
1307 // Window wants to be an exact size. Force root view to be that size.
1308 measureSpec = MeasureSpec.makeMeasureSpec(rootDimension, MeasureSpec.EXACTLY);
1309 break;
1310 }
1311 return measureSpec;
1312 }
1313
1314 private void draw(boolean fullRedrawNeeded) {
1315 Surface surface = mSurface;
1316 if (surface == null || !surface.isValid()) {
1317 return;
1318 }
1319
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001320 if (!sFirstDrawComplete) {
1321 synchronized (sFirstDrawHandlers) {
1322 sFirstDrawComplete = true;
Romain Guy812ccbe2010-06-01 14:07:24 -07001323 final int count = sFirstDrawHandlers.size();
1324 for (int i = 0; i< count; i++) {
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001325 post(sFirstDrawHandlers.get(i));
1326 }
1327 }
1328 }
1329
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001330 scrollToRectOrFocus(null, false);
1331
1332 if (mAttachInfo.mViewScrollChanged) {
1333 mAttachInfo.mViewScrollChanged = false;
1334 mAttachInfo.mTreeObserver.dispatchOnScrollChanged();
1335 }
Romain Guy8506ab42009-06-11 17:35:47 -07001336
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001337 int yoff;
Romain Guy5bcdff42009-05-14 21:27:18 -07001338 final boolean scrolling = mScroller != null && mScroller.computeScrollOffset();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001339 if (scrolling) {
1340 yoff = mScroller.getCurrY();
1341 } else {
1342 yoff = mScrollY;
1343 }
1344 if (mCurScrollY != yoff) {
1345 mCurScrollY = yoff;
1346 fullRedrawNeeded = true;
1347 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001348 float appScale = mAttachInfo.mApplicationScale;
1349 boolean scalingRequired = mAttachInfo.mScalingRequired;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001350
1351 Rect dirty = mDirty;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001352 if (mSurfaceHolder != null) {
1353 // The app owns the surface, we won't draw.
1354 dirty.setEmpty();
1355 return;
1356 }
Romain Guy58ef7fb2010-09-13 12:52:37 -07001357
1358 if (fullRedrawNeeded) {
1359 mAttachInfo.mIgnoreDirtyState = true;
1360 dirty.union(0, 0, (int) (mWidth * appScale + 0.5f), (int) (mHeight * appScale + 0.5f));
1361 }
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001362
Romain Guyb051e892010-09-28 19:09:36 -07001363 if (mAttachInfo.mHardwareRenderer != null && mAttachInfo.mHardwareRenderer.isEnabled()) {
Romain Guyfd507262010-10-10 15:42:49 -07001364 if (!dirty.isEmpty() || mIsAnimating) {
Romain Guy101e2ae2010-10-11 12:41:21 -07001365 mIsAnimating = false;
Romain Guyfd507262010-10-10 15:42:49 -07001366 dirty.setEmpty();
Romain Guy101e2ae2010-10-11 12:41:21 -07001367 mAttachInfo.mHardwareRenderer.draw(mView, mAttachInfo, yoff);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001368 }
Romain Guy812ccbe2010-06-01 14:07:24 -07001369
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001370 if (scrolling) {
1371 mFullRedrawNeeded = true;
1372 scheduleTraversals();
1373 }
Romain Guy812ccbe2010-06-01 14:07:24 -07001374
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001375 return;
1376 }
1377
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001378 if (DEBUG_ORIENTATION || DEBUG_DRAW) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001379 Log.v(TAG, "Draw " + mView + "/"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001380 + mWindowAttributes.getTitle()
1381 + ": dirty={" + dirty.left + "," + dirty.top
1382 + "," + dirty.right + "," + dirty.bottom + "} surface="
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001383 + surface + " surface.isValid()=" + surface.isValid() + ", appScale:" +
1384 appScale + ", width=" + mWidth + ", height=" + mHeight);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001385 }
1386
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001387 if (!dirty.isEmpty() || mIsAnimating) {
1388 Canvas canvas;
1389 try {
1390 int left = dirty.left;
1391 int top = dirty.top;
1392 int right = dirty.right;
1393 int bottom = dirty.bottom;
1394 canvas = surface.lockCanvas(dirty);
Romain Guy5bcdff42009-05-14 21:27:18 -07001395
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001396 if (left != dirty.left || top != dirty.top || right != dirty.right ||
1397 bottom != dirty.bottom) {
1398 mAttachInfo.mIgnoreDirtyState = true;
1399 }
1400
1401 // TODO: Do this in native
1402 canvas.setDensity(mDensity);
1403 } catch (Surface.OutOfResourcesException e) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001404 Log.e(TAG, "OutOfResourcesException locking surface", e);
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001405 // TODO: we should ask the window manager to do something!
1406 // for now we just do nothing
1407 return;
1408 } catch (IllegalArgumentException e) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001409 Log.e(TAG, "IllegalArgumentException locking surface", e);
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001410 // TODO: we should ask the window manager to do something!
1411 // for now we just do nothing
1412 return;
Romain Guy5bcdff42009-05-14 21:27:18 -07001413 }
1414
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001415 try {
1416 if (!dirty.isEmpty() || mIsAnimating) {
1417 long startTime = 0L;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001418
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001419 if (DEBUG_ORIENTATION || DEBUG_DRAW) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001420 Log.v(TAG, "Surface " + surface + " drawing to bitmap w="
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001421 + canvas.getWidth() + ", h=" + canvas.getHeight());
1422 //canvas.drawARGB(255, 255, 0, 0);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001423 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001424
Romain Guy5429e1d2010-09-07 12:38:00 -07001425 if (ViewDebug.DEBUG_PROFILE_DRAWING) {
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001426 startTime = SystemClock.elapsedRealtime();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001427 }
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001428
1429 // If this bitmap's format includes an alpha channel, we
1430 // need to clear it before drawing so that the child will
1431 // properly re-composite its drawing on a transparent
1432 // background. This automatically respects the clip/dirty region
1433 // or
1434 // If we are applying an offset, we need to clear the area
1435 // where the offset doesn't appear to avoid having garbage
1436 // left in the blank areas.
1437 if (!canvas.isOpaque() || yoff != 0) {
1438 canvas.drawColor(0, PorterDuff.Mode.CLEAR);
1439 }
1440
1441 dirty.setEmpty();
1442 mIsAnimating = false;
1443 mAttachInfo.mDrawingTime = SystemClock.uptimeMillis();
1444 mView.mPrivateFlags |= View.DRAWN;
1445
1446 if (DEBUG_DRAW) {
1447 Context cxt = mView.getContext();
1448 Log.i(TAG, "Drawing: package:" + cxt.getPackageName() +
1449 ", metrics=" + cxt.getResources().getDisplayMetrics() +
1450 ", compatibilityInfo=" + cxt.getResources().getCompatibilityInfo());
1451 }
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001452 try {
1453 canvas.translate(0, -yoff);
1454 if (mTranslator != null) {
1455 mTranslator.translateCanvas(canvas);
1456 }
1457 canvas.setScreenDensity(scalingRequired
1458 ? DisplayMetrics.DENSITY_DEVICE : 0);
1459 mView.draw(canvas);
1460 } finally {
1461 mAttachInfo.mIgnoreDirtyState = false;
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001462 }
1463
1464 if (Config.DEBUG && ViewDebug.consistencyCheckEnabled) {
1465 mView.dispatchConsistencyCheck(ViewDebug.CONSISTENCY_DRAWING);
1466 }
1467
Romain Guy5429e1d2010-09-07 12:38:00 -07001468 if (SHOW_FPS || ViewDebug.DEBUG_SHOW_FPS) {
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001469 int now = (int)SystemClock.elapsedRealtime();
1470 if (sDrawTime != 0) {
1471 nativeShowFPS(canvas, now - sDrawTime);
1472 }
1473 sDrawTime = now;
1474 }
1475
Romain Guy5429e1d2010-09-07 12:38:00 -07001476 if (ViewDebug.DEBUG_PROFILE_DRAWING) {
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001477 EventLog.writeEvent(60000, SystemClock.elapsedRealtime() - startTime);
1478 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001479 }
1480
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001481 } finally {
1482 surface.unlockCanvasAndPost(canvas);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001483 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001484 }
1485
1486 if (LOCAL_LOGV) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001487 Log.v(TAG, "Surface " + surface + " unlockCanvasAndPost");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001488 }
Romain Guy8506ab42009-06-11 17:35:47 -07001489
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001490 if (scrolling) {
1491 mFullRedrawNeeded = true;
1492 scheduleTraversals();
1493 }
1494 }
1495
1496 boolean scrollToRectOrFocus(Rect rectangle, boolean immediate) {
1497 final View.AttachInfo attachInfo = mAttachInfo;
1498 final Rect ci = attachInfo.mContentInsets;
1499 final Rect vi = attachInfo.mVisibleInsets;
1500 int scrollY = 0;
1501 boolean handled = false;
Romain Guy8506ab42009-06-11 17:35:47 -07001502
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001503 if (vi.left > ci.left || vi.top > ci.top
1504 || vi.right > ci.right || vi.bottom > ci.bottom) {
1505 // We'll assume that we aren't going to change the scroll
1506 // offset, since we want to avoid that unless it is actually
1507 // going to make the focus visible... otherwise we scroll
1508 // all over the place.
1509 scrollY = mScrollY;
1510 // We can be called for two different situations: during a draw,
1511 // to update the scroll position if the focus has changed (in which
1512 // case 'rectangle' is null), or in response to a
1513 // requestChildRectangleOnScreen() call (in which case 'rectangle'
1514 // is non-null and we just want to scroll to whatever that
1515 // rectangle is).
1516 View focus = mRealFocusedView;
Romain Guye8b16522009-07-14 13:06:42 -07001517
1518 // When in touch mode, focus points to the previously focused view,
1519 // which may have been removed from the view hierarchy. The following
Joe Onoratob71193b2009-11-24 18:34:42 -05001520 // line checks whether the view is still in our hierarchy.
1521 if (focus == null || focus.mAttachInfo != mAttachInfo) {
Romain Guye8b16522009-07-14 13:06:42 -07001522 mRealFocusedView = null;
1523 return false;
1524 }
1525
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001526 if (focus != mLastScrolledFocus) {
1527 // If the focus has changed, then ignore any requests to scroll
1528 // to a rectangle; first we want to make sure the entire focus
1529 // view is visible.
1530 rectangle = null;
1531 }
1532 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Eval scroll: focus=" + focus
1533 + " rectangle=" + rectangle + " ci=" + ci
1534 + " vi=" + vi);
1535 if (focus == mLastScrolledFocus && !mScrollMayChange
1536 && rectangle == null) {
1537 // Optimization: if the focus hasn't changed since last
1538 // time, and no layout has happened, then just leave things
1539 // as they are.
1540 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Keeping scroll y="
1541 + mScrollY + " vi=" + vi.toShortString());
1542 } else if (focus != null) {
1543 // We need to determine if the currently focused view is
1544 // within the visible part of the window and, if not, apply
1545 // a pan so it can be seen.
1546 mLastScrolledFocus = focus;
1547 mScrollMayChange = false;
1548 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Need to scroll?");
1549 // Try to find the rectangle from the focus view.
1550 if (focus.getGlobalVisibleRect(mVisRect, null)) {
1551 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Root w="
1552 + mView.getWidth() + " h=" + mView.getHeight()
1553 + " ci=" + ci.toShortString()
1554 + " vi=" + vi.toShortString());
1555 if (rectangle == null) {
1556 focus.getFocusedRect(mTempRect);
1557 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Focus " + focus
1558 + ": focusRect=" + mTempRect.toShortString());
Dianne Hackborn1c6a8942010-03-23 16:34:20 -07001559 if (mView instanceof ViewGroup) {
1560 ((ViewGroup) mView).offsetDescendantRectToMyCoords(
1561 focus, mTempRect);
1562 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001563 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1564 "Focus in window: focusRect="
1565 + mTempRect.toShortString()
1566 + " visRect=" + mVisRect.toShortString());
1567 } else {
1568 mTempRect.set(rectangle);
1569 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1570 "Request scroll to rect: "
1571 + mTempRect.toShortString()
1572 + " visRect=" + mVisRect.toShortString());
1573 }
1574 if (mTempRect.intersect(mVisRect)) {
1575 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1576 "Focus window visible rect: "
1577 + mTempRect.toShortString());
1578 if (mTempRect.height() >
1579 (mView.getHeight()-vi.top-vi.bottom)) {
1580 // If the focus simply is not going to fit, then
1581 // best is probably just to leave things as-is.
1582 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1583 "Too tall; leaving scrollY=" + scrollY);
1584 } else if ((mTempRect.top-scrollY) < vi.top) {
1585 scrollY -= vi.top - (mTempRect.top-scrollY);
1586 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1587 "Top covered; scrollY=" + scrollY);
1588 } else if ((mTempRect.bottom-scrollY)
1589 > (mView.getHeight()-vi.bottom)) {
1590 scrollY += (mTempRect.bottom-scrollY)
1591 - (mView.getHeight()-vi.bottom);
1592 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1593 "Bottom covered; scrollY=" + scrollY);
1594 }
1595 handled = true;
1596 }
1597 }
1598 }
1599 }
Romain Guy8506ab42009-06-11 17:35:47 -07001600
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001601 if (scrollY != mScrollY) {
1602 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Pan scroll changed: old="
1603 + mScrollY + " , new=" + scrollY);
1604 if (!immediate) {
1605 if (mScroller == null) {
1606 mScroller = new Scroller(mView.getContext());
1607 }
1608 mScroller.startScroll(0, mScrollY, 0, scrollY-mScrollY);
1609 } else if (mScroller != null) {
1610 mScroller.abortAnimation();
1611 }
1612 mScrollY = scrollY;
1613 }
Romain Guy8506ab42009-06-11 17:35:47 -07001614
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001615 return handled;
1616 }
Romain Guy8506ab42009-06-11 17:35:47 -07001617
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001618 public void requestChildFocus(View child, View focused) {
1619 checkThread();
1620 if (mFocusedView != focused) {
1621 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(mFocusedView, focused);
1622 scheduleTraversals();
1623 }
1624 mFocusedView = mRealFocusedView = focused;
1625 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Request child focus: focus now "
1626 + mFocusedView);
1627 }
1628
1629 public void clearChildFocus(View child) {
1630 checkThread();
1631
1632 View oldFocus = mFocusedView;
1633
1634 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Clearing child focus");
1635 mFocusedView = mRealFocusedView = null;
1636 if (mView != null && !mView.hasFocus()) {
1637 // If a view gets the focus, the listener will be invoked from requestChildFocus()
1638 if (!mView.requestFocus(View.FOCUS_FORWARD)) {
1639 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
1640 }
1641 } else if (oldFocus != null) {
1642 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
1643 }
1644 }
1645
1646
1647 public void focusableViewAvailable(View v) {
1648 checkThread();
1649
1650 if (mView != null && !mView.hasFocus()) {
1651 v.requestFocus();
1652 } else {
1653 // the one case where will transfer focus away from the current one
1654 // is if the current view is a view group that prefers to give focus
1655 // to its children first AND the view is a descendant of it.
1656 mFocusedView = mView.findFocus();
1657 boolean descendantsHaveDibsOnFocus =
1658 (mFocusedView instanceof ViewGroup) &&
1659 (((ViewGroup) mFocusedView).getDescendantFocusability() ==
1660 ViewGroup.FOCUS_AFTER_DESCENDANTS);
1661 if (descendantsHaveDibsOnFocus && isViewDescendantOf(v, mFocusedView)) {
1662 // If a view gets the focus, the listener will be invoked from requestChildFocus()
1663 v.requestFocus();
1664 }
1665 }
1666 }
1667
1668 public void recomputeViewAttributes(View child) {
1669 checkThread();
1670 if (mView == child) {
1671 mAttachInfo.mRecomputeGlobalAttributes = true;
1672 if (!mWillDrawSoon) {
1673 scheduleTraversals();
1674 }
1675 }
1676 }
1677
1678 void dispatchDetachedFromWindow() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001679 if (mView != null) {
1680 mView.dispatchDetachedFromWindow();
1681 }
1682
1683 mView = null;
1684 mAttachInfo.mRootView = null;
Mathias Agopian5583dc62009-07-09 16:28:11 -07001685 mAttachInfo.mSurface = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001686
Romain Guy29d89972010-09-22 16:10:57 -07001687 destroyHardwareRenderer();
Romain Guy4caa4ed2010-08-25 14:46:24 -07001688
Dianne Hackborn0586a1b2009-09-06 21:08:27 -07001689 mSurface.release();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001690
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001691 if (mInputChannel != null) {
1692 if (mInputQueueCallback != null) {
1693 mInputQueueCallback.onInputQueueDestroyed(mInputQueue);
1694 mInputQueueCallback = null;
1695 } else {
1696 InputQueue.unregisterInputChannel(mInputChannel);
Jeff Brown46b9ac02010-04-22 18:58:52 -07001697 }
1698 }
1699
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001700 try {
1701 sWindowSession.remove(mWindow);
1702 } catch (RemoteException e) {
1703 }
Jeff Brown349703e2010-06-22 01:27:15 -07001704
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001705 // Dispose the input channel after removing the window so the Window Manager
1706 // doesn't interpret the input channel being closed as an abnormal termination.
1707 if (mInputChannel != null) {
1708 mInputChannel.dispose();
1709 mInputChannel = null;
Jeff Brown349703e2010-06-22 01:27:15 -07001710 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001711 }
Romain Guy8506ab42009-06-11 17:35:47 -07001712
Dianne Hackborn694f79b2010-03-17 19:44:59 -07001713 void updateConfiguration(Configuration config, boolean force) {
1714 if (DEBUG_CONFIGURATION) Log.v(TAG,
1715 "Applying new config to window "
1716 + mWindowAttributes.getTitle()
1717 + ": " + config);
1718 synchronized (sConfigCallbacks) {
1719 for (int i=sConfigCallbacks.size()-1; i>=0; i--) {
1720 sConfigCallbacks.get(i).onConfigurationChanged(config);
1721 }
1722 }
1723 if (mView != null) {
1724 // At this point the resources have been updated to
1725 // have the most recent config, whatever that is. Use
1726 // the on in them which may be newer.
1727 if (mView != null) {
1728 config = mView.getResources().getConfiguration();
1729 }
1730 if (force || mLastConfiguration.diff(config) != 0) {
1731 mLastConfiguration.setTo(config);
1732 mView.dispatchConfigurationChanged(config);
1733 }
1734 }
1735 }
1736
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001737 /**
1738 * Return true if child is an ancestor of parent, (or equal to the parent).
1739 */
1740 private static boolean isViewDescendantOf(View child, View parent) {
1741 if (child == parent) {
1742 return true;
1743 }
1744
1745 final ViewParent theParent = child.getParent();
1746 return (theParent instanceof ViewGroup) && isViewDescendantOf((View) theParent, parent);
1747 }
1748
Romain Guycdb86672010-03-18 18:54:50 -07001749 private static void forceLayout(View view) {
1750 view.forceLayout();
1751 if (view instanceof ViewGroup) {
1752 ViewGroup group = (ViewGroup) view;
1753 final int count = group.getChildCount();
1754 for (int i = 0; i < count; i++) {
1755 forceLayout(group.getChildAt(i));
1756 }
1757 }
1758 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001759
1760 public final static int DO_TRAVERSAL = 1000;
1761 public final static int DIE = 1001;
1762 public final static int RESIZED = 1002;
1763 public final static int RESIZED_REPORT = 1003;
1764 public final static int WINDOW_FOCUS_CHANGED = 1004;
1765 public final static int DISPATCH_KEY = 1005;
1766 public final static int DISPATCH_POINTER = 1006;
1767 public final static int DISPATCH_TRACKBALL = 1007;
1768 public final static int DISPATCH_APP_VISIBILITY = 1008;
1769 public final static int DISPATCH_GET_NEW_SURFACE = 1009;
1770 public final static int FINISHED_EVENT = 1010;
1771 public final static int DISPATCH_KEY_FROM_IME = 1011;
1772 public final static int FINISH_INPUT_CONNECTION = 1012;
1773 public final static int CHECK_FOCUS = 1013;
Dianne Hackbornffa42482009-09-23 22:20:11 -07001774 public final static int CLOSE_SYSTEM_DIALOGS = 1014;
Christopher Tatea53146c2010-09-07 11:57:52 -07001775 public final static int DISPATCH_DRAG_EVENT = 1015;
Chris Tate91e9bb32010-10-12 12:58:43 -07001776 public final static int DISPATCH_DRAG_LOCATION_EVENT = 1016;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001777
1778 @Override
1779 public void handleMessage(Message msg) {
1780 switch (msg.what) {
1781 case View.AttachInfo.INVALIDATE_MSG:
1782 ((View) msg.obj).invalidate();
1783 break;
1784 case View.AttachInfo.INVALIDATE_RECT_MSG:
1785 final View.AttachInfo.InvalidateInfo info = (View.AttachInfo.InvalidateInfo) msg.obj;
1786 info.target.invalidate(info.left, info.top, info.right, info.bottom);
1787 info.release();
1788 break;
1789 case DO_TRAVERSAL:
1790 if (mProfile) {
1791 Debug.startMethodTracing("ViewRoot");
1792 }
1793
1794 performTraversals();
1795
1796 if (mProfile) {
1797 Debug.stopMethodTracing();
1798 mProfile = false;
1799 }
1800 break;
1801 case FINISHED_EVENT:
1802 handleFinishedEvent(msg.arg1, msg.arg2 != 0);
1803 break;
1804 case DISPATCH_KEY:
Jeff Brown92ff1dd2010-08-11 16:16:06 -07001805 deliverKeyEvent((KeyEvent)msg.obj, msg.arg1 != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001806 break;
Jeff Brown3915bb82010-11-05 15:02:16 -07001807 case DISPATCH_POINTER:
1808 deliverPointerEvent((MotionEvent) msg.obj, msg.arg1 != 0);
1809 break;
1810 case DISPATCH_TRACKBALL:
1811 deliverTrackballEvent((MotionEvent) msg.obj, msg.arg1 != 0);
1812 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001813 case DISPATCH_APP_VISIBILITY:
1814 handleAppVisibility(msg.arg1 != 0);
1815 break;
1816 case DISPATCH_GET_NEW_SURFACE:
1817 handleGetNewSurface();
1818 break;
1819 case RESIZED:
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001820 ResizedInfo ri = (ResizedInfo)msg.obj;
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001821
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001822 if (mWinFrame.width() == msg.arg1 && mWinFrame.height() == msg.arg2
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001823 && mPendingContentInsets.equals(ri.coveredInsets)
Dianne Hackbornd49258f2010-03-26 00:44:29 -07001824 && mPendingVisibleInsets.equals(ri.visibleInsets)
1825 && ((ResizedInfo)msg.obj).newConfig == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001826 break;
1827 }
1828 // fall through...
1829 case RESIZED_REPORT:
1830 if (mAdded) {
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001831 Configuration config = ((ResizedInfo)msg.obj).newConfig;
1832 if (config != null) {
Dianne Hackborn694f79b2010-03-17 19:44:59 -07001833 updateConfiguration(config, false);
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001834 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001835 mWinFrame.left = 0;
1836 mWinFrame.right = msg.arg1;
1837 mWinFrame.top = 0;
1838 mWinFrame.bottom = msg.arg2;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001839 mPendingContentInsets.set(((ResizedInfo)msg.obj).coveredInsets);
1840 mPendingVisibleInsets.set(((ResizedInfo)msg.obj).visibleInsets);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001841 if (msg.what == RESIZED_REPORT) {
1842 mReportNextDraw = true;
1843 }
Romain Guycdb86672010-03-18 18:54:50 -07001844
1845 if (mView != null) {
1846 forceLayout(mView);
1847 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001848 requestLayout();
1849 }
1850 break;
1851 case WINDOW_FOCUS_CHANGED: {
1852 if (mAdded) {
1853 boolean hasWindowFocus = msg.arg1 != 0;
1854 mAttachInfo.mHasWindowFocus = hasWindowFocus;
1855 if (hasWindowFocus) {
1856 boolean inTouchMode = msg.arg2 != 0;
Romain Guy2d4cff62010-04-09 15:39:00 -07001857 ensureTouchModeLocally(inTouchMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001858
Romain Guyc361da82010-10-25 15:29:10 -07001859 if (mAttachInfo.mHardwareRenderer != null &&
1860 mSurface != null && mSurface.isValid()) {
Romain Guyb051e892010-09-28 19:09:36 -07001861 mAttachInfo.mHardwareRenderer.initializeIfNeeded(mWidth, mHeight,
1862 mAttachInfo, mHolder);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001863 }
1864 }
Romain Guy8506ab42009-06-11 17:35:47 -07001865
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001866 mLastWasImTarget = WindowManager.LayoutParams
1867 .mayUseInputMethod(mWindowAttributes.flags);
Romain Guy8506ab42009-06-11 17:35:47 -07001868
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001869 InputMethodManager imm = InputMethodManager.peekInstance();
1870 if (mView != null) {
1871 if (hasWindowFocus && imm != null && mLastWasImTarget) {
1872 imm.startGettingWindowFocus(mView);
1873 }
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07001874 mAttachInfo.mKeyDispatchState.reset();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001875 mView.dispatchWindowFocusChanged(hasWindowFocus);
1876 }
svetoslavganov75986cf2009-05-14 22:28:01 -07001877
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001878 // Note: must be done after the focus change callbacks,
1879 // so all of the view state is set up correctly.
1880 if (hasWindowFocus) {
1881 if (imm != null && mLastWasImTarget) {
1882 imm.onWindowFocus(mView, mView.findFocus(),
1883 mWindowAttributes.softInputMode,
1884 !mHasHadWindowFocus, mWindowAttributes.flags);
1885 }
1886 // Clear the forward bit. We can just do this directly, since
1887 // the window manager doesn't care about it.
1888 mWindowAttributes.softInputMode &=
1889 ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
1890 ((WindowManager.LayoutParams)mView.getLayoutParams())
1891 .softInputMode &=
1892 ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
1893 mHasHadWindowFocus = true;
1894 }
svetoslavganov75986cf2009-05-14 22:28:01 -07001895
1896 if (hasWindowFocus && mView != null) {
1897 sendAccessibilityEvents();
1898 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001899 }
1900 } break;
1901 case DIE:
Dianne Hackborn94d69142009-09-28 22:14:42 -07001902 doDie();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001903 break;
The Android Open Source Project10592532009-03-18 17:39:46 -07001904 case DISPATCH_KEY_FROM_IME: {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001905 if (LOCAL_LOGV) Log.v(
Jeff Brownc5ed5912010-07-14 18:48:53 -07001906 TAG, "Dispatching key "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001907 + msg.obj + " from IME to " + mView);
The Android Open Source Project10592532009-03-18 17:39:46 -07001908 KeyEvent event = (KeyEvent)msg.obj;
1909 if ((event.getFlags()&KeyEvent.FLAG_FROM_SYSTEM) != 0) {
1910 // The IME is trying to say this event is from the
1911 // system! Bad bad bad!
Romain Guy812ccbe2010-06-01 14:07:24 -07001912 event = KeyEvent.changeFlags(event, event.getFlags() & ~KeyEvent.FLAG_FROM_SYSTEM);
The Android Open Source Project10592532009-03-18 17:39:46 -07001913 }
Jeff Brown3915bb82010-11-05 15:02:16 -07001914 deliverKeyEventPostIme((KeyEvent)msg.obj, false);
The Android Open Source Project10592532009-03-18 17:39:46 -07001915 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001916 case FINISH_INPUT_CONNECTION: {
1917 InputMethodManager imm = InputMethodManager.peekInstance();
1918 if (imm != null) {
1919 imm.reportFinishInputConnection((InputConnection)msg.obj);
1920 }
1921 } break;
1922 case CHECK_FOCUS: {
1923 InputMethodManager imm = InputMethodManager.peekInstance();
1924 if (imm != null) {
1925 imm.checkFocus();
1926 }
1927 } break;
Dianne Hackbornffa42482009-09-23 22:20:11 -07001928 case CLOSE_SYSTEM_DIALOGS: {
1929 if (mView != null) {
1930 mView.onCloseSystemDialogs((String)msg.obj);
1931 }
1932 } break;
Chris Tate91e9bb32010-10-12 12:58:43 -07001933 case DISPATCH_DRAG_EVENT:
1934 case DISPATCH_DRAG_LOCATION_EVENT: {
Christopher Tatea53146c2010-09-07 11:57:52 -07001935 handleDragEvent((DragEvent)msg.obj);
1936 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001937 }
1938 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07001939
Jeff Brown3915bb82010-11-05 15:02:16 -07001940 private void startInputEvent(InputQueue.FinishedCallback finishedCallback) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07001941 if (mFinishedCallback != null) {
1942 Slog.w(TAG, "Received a new input event from the input queue but there is "
1943 + "already an unfinished input event in progress.");
1944 }
1945
1946 mFinishedCallback = finishedCallback;
1947 }
1948
Jeff Brown3915bb82010-11-05 15:02:16 -07001949 private void finishInputEvent(boolean handled) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07001950 if (LOCAL_LOGV) Log.v(TAG, "Telling window manager input event is finished");
Jeff Brown92ff1dd2010-08-11 16:16:06 -07001951
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001952 if (mFinishedCallback != null) {
Jeff Brown3915bb82010-11-05 15:02:16 -07001953 mFinishedCallback.finished(handled);
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001954 mFinishedCallback = null;
Jeff Brown92ff1dd2010-08-11 16:16:06 -07001955 } else {
Jeff Brown93ed4e32010-09-23 13:51:48 -07001956 Slog.w(TAG, "Attempted to tell the input queue that the current input event "
1957 + "is finished but there is no input event actually in progress.");
Jeff Brown46b9ac02010-04-22 18:58:52 -07001958 }
1959 }
1960
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001961 /**
1962 * Something in the current window tells us we need to change the touch mode. For
1963 * example, we are not in touch mode, and the user touches the screen.
1964 *
1965 * If the touch mode has changed, tell the window manager, and handle it locally.
1966 *
1967 * @param inTouchMode Whether we want to be in touch mode.
1968 * @return True if the touch mode changed and focus changed was changed as a result
1969 */
1970 boolean ensureTouchMode(boolean inTouchMode) {
1971 if (DBG) Log.d("touchmode", "ensureTouchMode(" + inTouchMode + "), current "
1972 + "touch mode is " + mAttachInfo.mInTouchMode);
1973 if (mAttachInfo.mInTouchMode == inTouchMode) return false;
1974
1975 // tell the window manager
1976 try {
1977 sWindowSession.setInTouchMode(inTouchMode);
1978 } catch (RemoteException e) {
1979 throw new RuntimeException(e);
1980 }
1981
1982 // handle the change
Romain Guy2d4cff62010-04-09 15:39:00 -07001983 return ensureTouchModeLocally(inTouchMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001984 }
1985
1986 /**
1987 * Ensure that the touch mode for this window is set, and if it is changing,
1988 * take the appropriate action.
1989 * @param inTouchMode Whether we want to be in touch mode.
1990 * @return True if the touch mode changed and focus changed was changed as a result
1991 */
Romain Guy2d4cff62010-04-09 15:39:00 -07001992 private boolean ensureTouchModeLocally(boolean inTouchMode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001993 if (DBG) Log.d("touchmode", "ensureTouchModeLocally(" + inTouchMode + "), current "
1994 + "touch mode is " + mAttachInfo.mInTouchMode);
1995
1996 if (mAttachInfo.mInTouchMode == inTouchMode) return false;
1997
1998 mAttachInfo.mInTouchMode = inTouchMode;
1999 mAttachInfo.mTreeObserver.dispatchOnTouchModeChanged(inTouchMode);
2000
Romain Guy2d4cff62010-04-09 15:39:00 -07002001 return (inTouchMode) ? enterTouchMode() : leaveTouchMode();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002002 }
2003
2004 private boolean enterTouchMode() {
2005 if (mView != null) {
2006 if (mView.hasFocus()) {
2007 // note: not relying on mFocusedView here because this could
2008 // be when the window is first being added, and mFocused isn't
2009 // set yet.
2010 final View focused = mView.findFocus();
2011 if (focused != null && !focused.isFocusableInTouchMode()) {
2012
2013 final ViewGroup ancestorToTakeFocus =
2014 findAncestorToTakeFocusInTouchMode(focused);
2015 if (ancestorToTakeFocus != null) {
2016 // there is an ancestor that wants focus after its descendants that
2017 // is focusable in touch mode.. give it focus
2018 return ancestorToTakeFocus.requestFocus();
2019 } else {
2020 // nothing appropriate to have focus in touch mode, clear it out
2021 mView.unFocus();
2022 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(focused, null);
2023 mFocusedView = null;
2024 return true;
2025 }
2026 }
2027 }
2028 }
2029 return false;
2030 }
2031
2032
2033 /**
2034 * Find an ancestor of focused that wants focus after its descendants and is
2035 * focusable in touch mode.
2036 * @param focused The currently focused view.
2037 * @return An appropriate view, or null if no such view exists.
2038 */
2039 private ViewGroup findAncestorToTakeFocusInTouchMode(View focused) {
2040 ViewParent parent = focused.getParent();
2041 while (parent instanceof ViewGroup) {
2042 final ViewGroup vgParent = (ViewGroup) parent;
2043 if (vgParent.getDescendantFocusability() == ViewGroup.FOCUS_AFTER_DESCENDANTS
2044 && vgParent.isFocusableInTouchMode()) {
2045 return vgParent;
2046 }
2047 if (vgParent.isRootNamespace()) {
2048 return null;
2049 } else {
2050 parent = vgParent.getParent();
2051 }
2052 }
2053 return null;
2054 }
2055
2056 private boolean leaveTouchMode() {
2057 if (mView != null) {
2058 if (mView.hasFocus()) {
2059 // i learned the hard way to not trust mFocusedView :)
2060 mFocusedView = mView.findFocus();
2061 if (!(mFocusedView instanceof ViewGroup)) {
2062 // some view has focus, let it keep it
2063 return false;
2064 } else if (((ViewGroup)mFocusedView).getDescendantFocusability() !=
2065 ViewGroup.FOCUS_AFTER_DESCENDANTS) {
2066 // some view group has focus, and doesn't prefer its children
2067 // over itself for focus, so let them keep it.
2068 return false;
2069 }
2070 }
2071
2072 // find the best view to give focus to in this brave new non-touch-mode
2073 // world
2074 final View focused = focusSearch(null, View.FOCUS_DOWN);
2075 if (focused != null) {
2076 return focused.requestFocus(View.FOCUS_DOWN);
2077 }
2078 }
2079 return false;
2080 }
2081
Jeff Brown3915bb82010-11-05 15:02:16 -07002082 private void deliverPointerEvent(MotionEvent event, boolean sendDone) {
2083 // If there is no view, then the event will not be handled.
2084 if (mView == null || !mAdded) {
2085 finishPointerEvent(event, sendDone, false);
2086 return;
2087 }
2088
2089 // Translate the pointer event for compatibility, if needed.
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002090 if (mTranslator != null) {
2091 mTranslator.translateEventInScreenToAppWindow(event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002092 }
2093
Jeff Brown3915bb82010-11-05 15:02:16 -07002094 // Enter touch mode on the down.
2095 boolean isDown = event.getAction() == MotionEvent.ACTION_DOWN;
2096 if (isDown) {
2097 ensureTouchMode(true);
2098 }
2099 if(Config.LOGV) {
2100 captureMotionLog("captureDispatchPointer", event);
2101 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002102
Jeff Brown3915bb82010-11-05 15:02:16 -07002103 // Offset the scroll position.
2104 if (mCurScrollY != 0) {
2105 event.offsetLocation(0, mCurScrollY);
2106 }
2107 if (MEASURE_LATENCY) {
2108 lt.sample("A Dispatching TouchEvents", System.nanoTime() - event.getEventTimeNano());
2109 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002110
Jeff Brown3915bb82010-11-05 15:02:16 -07002111 // Remember the touch position for possible drag-initiation.
2112 mLastTouchPoint.x = event.getRawX();
2113 mLastTouchPoint.y = event.getRawY();
2114
2115 // Dispatch touch to view hierarchy.
2116 boolean handled = mView.dispatchTouchEvent(event);
2117 if (MEASURE_LATENCY) {
2118 lt.sample("B Dispatched TouchEvents ", System.nanoTime() - event.getEventTimeNano());
2119 }
2120 if (handled) {
2121 finishPointerEvent(event, sendDone, true);
2122 return;
2123 }
2124
2125 // Apply edge slop and try again, if appropriate.
2126 final int edgeFlags = event.getEdgeFlags();
2127 if (edgeFlags != 0 && mView instanceof ViewGroup) {
2128 final int edgeSlop = mViewConfiguration.getScaledEdgeSlop();
2129 int direction = View.FOCUS_UP;
2130 int x = (int)event.getX();
2131 int y = (int)event.getY();
2132 final int[] deltas = new int[2];
2133
2134 if ((edgeFlags & MotionEvent.EDGE_TOP) != 0) {
2135 direction = View.FOCUS_DOWN;
2136 if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
2137 deltas[0] = edgeSlop;
2138 x += edgeSlop;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002139 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
Jeff Brown3915bb82010-11-05 15:02:16 -07002140 deltas[0] = -edgeSlop;
2141 x -= edgeSlop;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002142 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002143 } else if ((edgeFlags & MotionEvent.EDGE_BOTTOM) != 0) {
2144 direction = View.FOCUS_UP;
2145 if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
2146 deltas[0] = edgeSlop;
2147 x += edgeSlop;
2148 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
2149 deltas[0] = -edgeSlop;
2150 x -= edgeSlop;
2151 }
2152 } else if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
2153 direction = View.FOCUS_RIGHT;
2154 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
2155 direction = View.FOCUS_LEFT;
2156 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002157
Jeff Brown3915bb82010-11-05 15:02:16 -07002158 View nearest = FocusFinder.getInstance().findNearestTouchable(
2159 ((ViewGroup) mView), x, y, direction, deltas);
2160 if (nearest != null) {
2161 event.offsetLocation(deltas[0], deltas[1]);
2162 event.setEdgeFlags(0);
2163 if (mView.dispatchTouchEvent(event)) {
2164 finishPointerEvent(event, sendDone, true);
2165 return;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002166 }
2167 }
2168 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002169
2170 // Pointer event was unhandled.
2171 finishPointerEvent(event, sendDone, false);
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002172 }
2173
Jeff Brown3915bb82010-11-05 15:02:16 -07002174 private void finishPointerEvent(MotionEvent event, boolean sendDone, boolean handled) {
2175 event.recycle();
2176 if (sendDone) {
2177 finishInputEvent(handled);
2178 }
2179 if (LOCAL_LOGV || WATCH_POINTER) Log.i(TAG, "Done dispatching!");
2180 }
2181
2182 private void deliverTrackballEvent(MotionEvent event, boolean sendDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002183 if (DEBUG_TRACKBALL) Log.v(TAG, "Motion event:" + event);
2184
Jeff Brown3915bb82010-11-05 15:02:16 -07002185 // If there is no view, then the event will not be handled.
2186 if (mView == null || !mAdded) {
2187 finishTrackballEvent(event, sendDone, false);
2188 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002189 }
2190
Jeff Brown3915bb82010-11-05 15:02:16 -07002191 // Deliver the trackball event to the view.
2192 if (mView.dispatchTrackballEvent(event)) {
2193 // If we reach this, we delivered a trackball event to mView and
2194 // mView consumed it. Because we will not translate the trackball
2195 // event into a key event, touch mode will not exit, so we exit
2196 // touch mode here.
2197 ensureTouchMode(false);
2198
2199 finishTrackballEvent(event, sendDone, true);
2200 mLastTrackballTime = Integer.MIN_VALUE;
2201 return;
2202 }
2203
2204 // Translate the trackball event into DPAD keys and try to deliver those.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002205 final TrackballAxis x = mTrackballAxisX;
2206 final TrackballAxis y = mTrackballAxisY;
2207
2208 long curTime = SystemClock.uptimeMillis();
Jeff Brown3915bb82010-11-05 15:02:16 -07002209 if ((mLastTrackballTime + MAX_TRACKBALL_DELAY) < curTime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002210 // It has been too long since the last movement,
2211 // so restart at the beginning.
2212 x.reset(0);
2213 y.reset(0);
2214 mLastTrackballTime = curTime;
2215 }
2216
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002217 final int action = event.getAction();
2218 final int metastate = event.getMetaState();
2219 switch (action) {
2220 case MotionEvent.ACTION_DOWN:
2221 x.reset(2);
2222 y.reset(2);
2223 deliverKeyEvent(new KeyEvent(curTime, curTime,
2224 KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_CENTER,
2225 0, metastate), false);
2226 break;
2227 case MotionEvent.ACTION_UP:
2228 x.reset(2);
2229 y.reset(2);
2230 deliverKeyEvent(new KeyEvent(curTime, curTime,
2231 KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_CENTER,
2232 0, metastate), false);
2233 break;
2234 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002235
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002236 if (DEBUG_TRACKBALL) Log.v(TAG, "TB X=" + x.position + " step="
2237 + x.step + " dir=" + x.dir + " acc=" + x.acceleration
2238 + " move=" + event.getX()
2239 + " / Y=" + y.position + " step="
2240 + y.step + " dir=" + y.dir + " acc=" + y.acceleration
2241 + " move=" + event.getY());
2242 final float xOff = x.collect(event.getX(), event.getEventTime(), "X");
2243 final float yOff = y.collect(event.getY(), event.getEventTime(), "Y");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002244
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002245 // Generate DPAD events based on the trackball movement.
2246 // We pick the axis that has moved the most as the direction of
2247 // the DPAD. When we generate DPAD events for one axis, then the
2248 // other axis is reset -- we don't want to perform DPAD jumps due
2249 // to slight movements in the trackball when making major movements
2250 // along the other axis.
2251 int keycode = 0;
2252 int movement = 0;
2253 float accel = 1;
2254 if (xOff > yOff) {
2255 movement = x.generate((2/event.getXPrecision()));
2256 if (movement != 0) {
2257 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_RIGHT
2258 : KeyEvent.KEYCODE_DPAD_LEFT;
2259 accel = x.acceleration;
2260 y.reset(2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002261 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002262 } else if (yOff > 0) {
2263 movement = y.generate((2/event.getYPrecision()));
2264 if (movement != 0) {
2265 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_DOWN
2266 : KeyEvent.KEYCODE_DPAD_UP;
2267 accel = y.acceleration;
2268 x.reset(2);
2269 }
2270 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002271
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002272 if (keycode != 0) {
2273 if (movement < 0) movement = -movement;
2274 int accelMovement = (int)(movement * accel);
2275 if (DEBUG_TRACKBALL) Log.v(TAG, "Move: movement=" + movement
2276 + " accelMovement=" + accelMovement
2277 + " accel=" + accel);
2278 if (accelMovement > movement) {
2279 if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: "
2280 + keycode);
2281 movement--;
2282 deliverKeyEvent(new KeyEvent(curTime, curTime,
2283 KeyEvent.ACTION_MULTIPLE, keycode,
2284 accelMovement-movement, metastate), false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002285 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002286 while (movement > 0) {
2287 if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: "
2288 + keycode);
2289 movement--;
2290 curTime = SystemClock.uptimeMillis();
2291 deliverKeyEvent(new KeyEvent(curTime, curTime,
2292 KeyEvent.ACTION_DOWN, keycode, 0, event.getMetaState()), false);
2293 deliverKeyEvent(new KeyEvent(curTime, curTime,
2294 KeyEvent.ACTION_UP, keycode, 0, metastate), false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002295 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002296 mLastTrackballTime = curTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002297 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002298
2299 // Unfortunately we can't tell whether the application consumed the keys, so
2300 // we always consider the trackball event handled.
2301 finishTrackballEvent(event, sendDone, true);
2302 }
2303
2304 private void finishTrackballEvent(MotionEvent event, boolean sendDone, boolean handled) {
2305 event.recycle();
2306 if (sendDone) {
2307 finishInputEvent(handled);
2308 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002309 }
2310
2311 /**
2312 * @param keyCode The key code
2313 * @return True if the key is directional.
2314 */
2315 static boolean isDirectional(int keyCode) {
2316 switch (keyCode) {
2317 case KeyEvent.KEYCODE_DPAD_LEFT:
2318 case KeyEvent.KEYCODE_DPAD_RIGHT:
2319 case KeyEvent.KEYCODE_DPAD_UP:
2320 case KeyEvent.KEYCODE_DPAD_DOWN:
2321 return true;
2322 }
2323 return false;
2324 }
2325
2326 /**
2327 * Returns true if this key is a keyboard key.
2328 * @param keyEvent The key event.
2329 * @return whether this key is a keyboard key.
2330 */
2331 private static boolean isKeyboardKey(KeyEvent keyEvent) {
2332 final int convertedKey = keyEvent.getUnicodeChar();
2333 return convertedKey > 0;
2334 }
2335
2336
2337
2338 /**
2339 * See if the key event means we should leave touch mode (and leave touch
2340 * mode if so).
2341 * @param event The key event.
2342 * @return Whether this key event should be consumed (meaning the act of
2343 * leaving touch mode alone is considered the event).
2344 */
2345 private boolean checkForLeavingTouchModeAndConsume(KeyEvent event) {
Adam Powell51a6bee2010-03-15 14:07:28 -07002346 final int action = event.getAction();
2347 if (action != KeyEvent.ACTION_DOWN && action != KeyEvent.ACTION_MULTIPLE) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002348 return false;
2349 }
2350 if ((event.getFlags()&KeyEvent.FLAG_KEEP_TOUCH_MODE) != 0) {
2351 return false;
2352 }
2353
2354 // only relevant if we are in touch mode
2355 if (!mAttachInfo.mInTouchMode) {
2356 return false;
2357 }
2358
2359 // if something like an edit text has focus and the user is typing,
2360 // leave touch mode
2361 //
2362 // note: the condition of not being a keyboard key is kind of a hacky
2363 // approximation of whether we think the focused view will want the
2364 // key; if we knew for sure whether the focused view would consume
2365 // the event, that would be better.
2366 if (isKeyboardKey(event) && mView != null && mView.hasFocus()) {
2367 mFocusedView = mView.findFocus();
2368 if ((mFocusedView instanceof ViewGroup)
2369 && ((ViewGroup) mFocusedView).getDescendantFocusability() ==
2370 ViewGroup.FOCUS_AFTER_DESCENDANTS) {
2371 // something has focus, but is holding it weakly as a container
2372 return false;
2373 }
2374 if (ensureTouchMode(false)) {
2375 throw new IllegalStateException("should not have changed focus "
2376 + "when leaving touch mode while a view has focus.");
2377 }
2378 return false;
2379 }
2380
2381 if (isDirectional(event.getKeyCode())) {
2382 // no view has focus, so we leave touch mode (and find something
2383 // to give focus to). the event is consumed if we were able to
2384 // find something to give focus to.
2385 return ensureTouchMode(false);
2386 }
2387 return false;
2388 }
2389
2390 /**
Romain Guy8506ab42009-06-11 17:35:47 -07002391 * log motion events
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002392 */
2393 private static void captureMotionLog(String subTag, MotionEvent ev) {
Romain Guy8506ab42009-06-11 17:35:47 -07002394 //check dynamic switch
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002395 if (ev == null ||
2396 SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_EVENT, 0) == 0) {
2397 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002398 }
Romain Guy8506ab42009-06-11 17:35:47 -07002399
2400 StringBuilder sb = new StringBuilder(subTag + ": ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002401 sb.append(ev.getDownTime()).append(',');
2402 sb.append(ev.getEventTime()).append(',');
2403 sb.append(ev.getAction()).append(',');
Romain Guy8506ab42009-06-11 17:35:47 -07002404 sb.append(ev.getX()).append(',');
2405 sb.append(ev.getY()).append(',');
2406 sb.append(ev.getPressure()).append(',');
2407 sb.append(ev.getSize()).append(',');
2408 sb.append(ev.getMetaState()).append(',');
2409 sb.append(ev.getXPrecision()).append(',');
2410 sb.append(ev.getYPrecision()).append(',');
2411 sb.append(ev.getDeviceId()).append(',');
2412 sb.append(ev.getEdgeFlags());
2413 Log.d(TAG, sb.toString());
2414 }
2415 /**
2416 * log motion events
2417 */
2418 private static void captureKeyLog(String subTag, KeyEvent ev) {
2419 //check dynamic switch
2420 if (ev == null ||
2421 SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_EVENT, 0) == 0) {
2422 return;
2423 }
2424 StringBuilder sb = new StringBuilder(subTag + ": ");
2425 sb.append(ev.getDownTime()).append(',');
2426 sb.append(ev.getEventTime()).append(',');
2427 sb.append(ev.getAction()).append(',');
2428 sb.append(ev.getKeyCode()).append(',');
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002429 sb.append(ev.getRepeatCount()).append(',');
2430 sb.append(ev.getMetaState()).append(',');
2431 sb.append(ev.getDeviceId()).append(',');
2432 sb.append(ev.getScanCode());
Romain Guy8506ab42009-06-11 17:35:47 -07002433 Log.d(TAG, sb.toString());
2434 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002435
2436 int enqueuePendingEvent(Object event, boolean sendDone) {
2437 int seq = mPendingEventSeq+1;
2438 if (seq < 0) seq = 0;
2439 mPendingEventSeq = seq;
2440 mPendingEvents.put(seq, event);
2441 return sendDone ? seq : -seq;
2442 }
2443
2444 Object retrievePendingEvent(int seq) {
2445 if (seq < 0) seq = -seq;
2446 Object event = mPendingEvents.get(seq);
2447 if (event != null) {
2448 mPendingEvents.remove(seq);
2449 }
2450 return event;
2451 }
Romain Guy8506ab42009-06-11 17:35:47 -07002452
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002453 private void deliverKeyEvent(KeyEvent event, boolean sendDone) {
Jeff Brown3915bb82010-11-05 15:02:16 -07002454 // If there is no view, then the event will not be handled.
2455 if (mView == null || !mAdded) {
2456 finishKeyEvent(event, sendDone, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002457 return;
2458 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002459
2460 if (LOCAL_LOGV) Log.v(TAG, "Dispatching key " + event + " to " + mView);
2461
2462 // Perform predispatching before the IME.
2463 if (mView.dispatchKeyEventPreIme(event)) {
2464 finishKeyEvent(event, sendDone, true);
2465 return;
2466 }
2467
2468 // Dispatch to the IME before propagating down the view hierarchy.
2469 // The IME will eventually call back into handleFinishedEvent.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002470 if (mLastWasImTarget) {
2471 InputMethodManager imm = InputMethodManager.peekInstance();
Jeff Brown3915bb82010-11-05 15:02:16 -07002472 if (imm != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002473 int seq = enqueuePendingEvent(event, sendDone);
2474 if (DEBUG_IMF) Log.v(TAG, "Sending key event to IME: seq="
2475 + seq + " event=" + event);
Jeff Brown3915bb82010-11-05 15:02:16 -07002476 imm.dispatchKeyEvent(mView.getContext(), seq, event, mInputMethodCallback);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002477 return;
2478 }
2479 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002480
2481 // Not dispatching to IME, continue with post IME actions.
2482 deliverKeyEventPostIme(event, sendDone);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002483 }
2484
Jeff Brown3915bb82010-11-05 15:02:16 -07002485 private void handleFinishedEvent(int seq, boolean handled) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002486 final KeyEvent event = (KeyEvent)retrievePendingEvent(seq);
2487 if (DEBUG_IMF) Log.v(TAG, "IME finished event: seq=" + seq
2488 + " handled=" + handled + " event=" + event);
2489 if (event != null) {
2490 final boolean sendDone = seq >= 0;
Jeff Brown3915bb82010-11-05 15:02:16 -07002491 if (handled) {
2492 finishKeyEvent(event, sendDone, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002493 } else {
Jeff Brown3915bb82010-11-05 15:02:16 -07002494 deliverKeyEventPostIme(event, sendDone);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002495 }
2496 }
2497 }
Romain Guy8506ab42009-06-11 17:35:47 -07002498
Jeff Brown3915bb82010-11-05 15:02:16 -07002499 private void deliverKeyEventPostIme(KeyEvent event, boolean sendDone) {
2500 // If the view went away, then the event will not be handled.
2501 if (mView == null || !mAdded) {
2502 finishKeyEvent(event, sendDone, false);
2503 return;
2504 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002505
Jeff Brown3915bb82010-11-05 15:02:16 -07002506 // If the key's purpose is to exit touch mode then we consume it and consider it handled.
2507 if (checkForLeavingTouchModeAndConsume(event)) {
2508 finishKeyEvent(event, sendDone, true);
2509 return;
2510 }
Romain Guy8506ab42009-06-11 17:35:47 -07002511
Jeff Brown3915bb82010-11-05 15:02:16 -07002512 if (Config.LOGV) {
2513 captureKeyLog("captureDispatchKeyEvent", event);
2514 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002515
Jeff Brown3915bb82010-11-05 15:02:16 -07002516 // Deliver the key to the view hierarchy.
2517 if (mView.dispatchKeyEvent(event)) {
2518 finishKeyEvent(event, sendDone, true);
2519 return;
2520 }
Joe Onorato86f67862010-11-05 18:57:34 -07002521
Jeff Brown3915bb82010-11-05 15:02:16 -07002522 // Apply the fallback event policy.
2523 if (mFallbackEventHandler.dispatchKeyEvent(event)) {
2524 finishKeyEvent(event, sendDone, true);
2525 return;
2526 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002527
Jeff Brown3915bb82010-11-05 15:02:16 -07002528 // Handle automatic focus changes.
2529 if (event.getAction() == KeyEvent.ACTION_DOWN) {
2530 int direction = 0;
2531 switch (event.getKeyCode()) {
2532 case KeyEvent.KEYCODE_DPAD_LEFT:
2533 direction = View.FOCUS_LEFT;
2534 break;
2535 case KeyEvent.KEYCODE_DPAD_RIGHT:
2536 direction = View.FOCUS_RIGHT;
2537 break;
2538 case KeyEvent.KEYCODE_DPAD_UP:
2539 direction = View.FOCUS_UP;
2540 break;
2541 case KeyEvent.KEYCODE_DPAD_DOWN:
2542 direction = View.FOCUS_DOWN;
2543 break;
2544 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002545
Jeff Brown3915bb82010-11-05 15:02:16 -07002546 if (direction != 0) {
2547 View focused = mView != null ? mView.findFocus() : null;
2548 if (focused != null) {
2549 View v = focused.focusSearch(direction);
2550 if (v != null && v != focused) {
2551 // do the math the get the interesting rect
2552 // of previous focused into the coord system of
2553 // newly focused view
2554 focused.getFocusedRect(mTempRect);
2555 if (mView instanceof ViewGroup) {
2556 ((ViewGroup) mView).offsetDescendantRectToMyCoords(
2557 focused, mTempRect);
2558 ((ViewGroup) mView).offsetRectIntoDescendantCoords(
2559 v, mTempRect);
2560 }
2561 if (v.requestFocus(direction, mTempRect)) {
2562 playSoundEffect(
2563 SoundEffectConstants.getContantForFocusDirection(direction));
2564 finishKeyEvent(event, sendDone, true);
2565 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002566 }
2567 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002568
2569 // Give the focused view a last chance to handle the dpad key.
2570 if (mView.dispatchUnhandledMove(focused, direction)) {
2571 finishKeyEvent(event, sendDone, true);
2572 return;
2573 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002574 }
2575 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002576 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002577
Jeff Brown3915bb82010-11-05 15:02:16 -07002578 // Key was unhandled.
2579 finishKeyEvent(event, sendDone, false);
2580 }
2581
2582 private void finishKeyEvent(KeyEvent event, boolean sendDone, boolean handled) {
2583 if (sendDone) {
2584 finishInputEvent(handled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002585 }
2586 }
2587
Christopher Tatea53146c2010-09-07 11:57:52 -07002588 /* drag/drop */
2589 private void handleDragEvent(DragEvent event) {
2590 // From the root, only drag start/end/location are dispatched. entered/exited
2591 // are determined and dispatched by the viewgroup hierarchy, who then report
2592 // that back here for ultimate reporting back to the framework.
2593 if (mView != null && mAdded) {
2594 final int what = event.mAction;
2595
2596 if (what == DragEvent.ACTION_DRAG_EXITED) {
2597 // A direct EXITED event means that the window manager knows we've just crossed
2598 // a window boundary, so the current drag target within this one must have
2599 // just been exited. Send it the usual notifications and then we're done
2600 // for now.
Chris Tate9d1ab882010-11-02 15:55:39 -07002601 mView.dispatchDragEvent(event);
Christopher Tatea53146c2010-09-07 11:57:52 -07002602 } else {
2603 // Cache the drag description when the operation starts, then fill it in
2604 // on subsequent calls as a convenience
2605 if (what == DragEvent.ACTION_DRAG_STARTED) {
Chris Tate9d1ab882010-11-02 15:55:39 -07002606 mCurrentDragView = null; // Start the current-recipient tracking
Christopher Tatea53146c2010-09-07 11:57:52 -07002607 mDragDescription = event.mClipDescription;
2608 } else {
2609 event.mClipDescription = mDragDescription;
2610 }
2611
2612 // For events with a [screen] location, translate into window coordinates
2613 if ((what == DragEvent.ACTION_DRAG_LOCATION) || (what == DragEvent.ACTION_DROP)) {
2614 mDragPoint.set(event.mX, event.mY);
2615 if (mTranslator != null) {
2616 mTranslator.translatePointInScreenToAppWindow(mDragPoint);
2617 }
2618
2619 if (mCurScrollY != 0) {
2620 mDragPoint.offset(0, mCurScrollY);
2621 }
2622
2623 event.mX = mDragPoint.x;
2624 event.mY = mDragPoint.y;
2625 }
2626
2627 // Remember who the current drag target is pre-dispatch
2628 final View prevDragView = mCurrentDragView;
2629
2630 // Now dispatch the drag/drop event
Chris Tated4533f12010-10-19 15:15:08 -07002631 boolean result = mView.dispatchDragEvent(event);
Christopher Tatea53146c2010-09-07 11:57:52 -07002632
2633 // If we changed apparent drag target, tell the OS about it
2634 if (prevDragView != mCurrentDragView) {
2635 try {
2636 if (prevDragView != null) {
2637 sWindowSession.dragRecipientExited(mWindow);
2638 }
2639 if (mCurrentDragView != null) {
2640 sWindowSession.dragRecipientEntered(mWindow);
2641 }
2642 } catch (RemoteException e) {
2643 Slog.e(TAG, "Unable to note drag target change");
2644 }
Christopher Tatea53146c2010-09-07 11:57:52 -07002645 }
Chris Tated4533f12010-10-19 15:15:08 -07002646
2647 // Report the drop result if necessary
2648 if (what == DragEvent.ACTION_DROP) {
2649 try {
2650 Log.i(TAG, "Reporting drop result: " + result);
2651 sWindowSession.reportDropResult(mWindow, result);
2652 } catch (RemoteException e) {
2653 Log.e(TAG, "Unable to report drop result");
2654 }
2655 }
Christopher Tatea53146c2010-09-07 11:57:52 -07002656 }
2657 }
2658 event.recycle();
2659 }
2660
Christopher Tate2c095f32010-10-04 14:13:40 -07002661 public void getLastTouchPoint(Point outLocation) {
2662 outLocation.x = (int) mLastTouchPoint.x;
2663 outLocation.y = (int) mLastTouchPoint.y;
2664 }
2665
Chris Tate9d1ab882010-11-02 15:55:39 -07002666 public void setDragFocus(View newDragTarget) {
Christopher Tatea53146c2010-09-07 11:57:52 -07002667 if (mCurrentDragView != newDragTarget) {
Chris Tate048691c2010-10-12 17:39:18 -07002668 mCurrentDragView = newDragTarget;
Christopher Tatea53146c2010-09-07 11:57:52 -07002669 }
Christopher Tatea53146c2010-09-07 11:57:52 -07002670 }
2671
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002672 private AudioManager getAudioManager() {
2673 if (mView == null) {
2674 throw new IllegalStateException("getAudioManager called when there is no mView");
2675 }
2676 if (mAudioManager == null) {
2677 mAudioManager = (AudioManager) mView.getContext().getSystemService(Context.AUDIO_SERVICE);
2678 }
2679 return mAudioManager;
2680 }
2681
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002682 private int relayoutWindow(WindowManager.LayoutParams params, int viewVisibility,
2683 boolean insetsPending) throws RemoteException {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002684
2685 float appScale = mAttachInfo.mApplicationScale;
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002686 boolean restore = false;
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002687 if (params != null && mTranslator != null) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07002688 restore = true;
2689 params.backup();
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002690 mTranslator.translateWindowLayout(params);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002691 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002692 if (params != null) {
2693 if (DBG) Log.d(TAG, "WindowLayout in layoutWindow:" + params);
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002694 }
Dianne Hackborn694f79b2010-03-17 19:44:59 -07002695 mPendingConfiguration.seq = 0;
Dianne Hackbornf123e492010-09-24 11:16:23 -07002696 //Log.d(TAG, ">>>>>> CALLING relayout");
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002697 int relayoutResult = sWindowSession.relayout(
2698 mWindow, params,
Mitsuru Oshima61324e52009-07-21 15:40:36 -07002699 (int) (mView.mMeasuredWidth * appScale + 0.5f),
2700 (int) (mView.mMeasuredHeight * appScale + 0.5f),
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002701 viewVisibility, insetsPending, mWinFrame,
Dianne Hackborn694f79b2010-03-17 19:44:59 -07002702 mPendingContentInsets, mPendingVisibleInsets,
2703 mPendingConfiguration, mSurface);
Dianne Hackbornf123e492010-09-24 11:16:23 -07002704 //Log.d(TAG, "<<<<<< BACK FROM relayout");
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002705 if (restore) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07002706 params.restore();
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002707 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002708
2709 if (mTranslator != null) {
2710 mTranslator.translateRectInScreenToAppWinFrame(mWinFrame);
2711 mTranslator.translateRectInScreenToAppWindow(mPendingContentInsets);
2712 mTranslator.translateRectInScreenToAppWindow(mPendingVisibleInsets);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002713 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002714 return relayoutResult;
2715 }
Romain Guy8506ab42009-06-11 17:35:47 -07002716
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002717 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002718 * {@inheritDoc}
2719 */
2720 public void playSoundEffect(int effectId) {
2721 checkThread();
2722
Jean-Michel Trivi13b18fd2010-05-05 09:18:15 -07002723 try {
2724 final AudioManager audioManager = getAudioManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002725
Jean-Michel Trivi13b18fd2010-05-05 09:18:15 -07002726 switch (effectId) {
2727 case SoundEffectConstants.CLICK:
2728 audioManager.playSoundEffect(AudioManager.FX_KEY_CLICK);
2729 return;
2730 case SoundEffectConstants.NAVIGATION_DOWN:
2731 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_DOWN);
2732 return;
2733 case SoundEffectConstants.NAVIGATION_LEFT:
2734 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_LEFT);
2735 return;
2736 case SoundEffectConstants.NAVIGATION_RIGHT:
2737 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_RIGHT);
2738 return;
2739 case SoundEffectConstants.NAVIGATION_UP:
2740 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_UP);
2741 return;
2742 default:
2743 throw new IllegalArgumentException("unknown effect id " + effectId +
2744 " not defined in " + SoundEffectConstants.class.getCanonicalName());
2745 }
2746 } catch (IllegalStateException e) {
2747 // Exception thrown by getAudioManager() when mView is null
2748 Log.e(TAG, "FATAL EXCEPTION when attempting to play sound effect: " + e);
2749 e.printStackTrace();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002750 }
2751 }
2752
2753 /**
2754 * {@inheritDoc}
2755 */
2756 public boolean performHapticFeedback(int effectId, boolean always) {
2757 try {
2758 return sWindowSession.performHapticFeedback(mWindow, effectId, always);
2759 } catch (RemoteException e) {
2760 return false;
2761 }
2762 }
2763
2764 /**
2765 * {@inheritDoc}
2766 */
2767 public View focusSearch(View focused, int direction) {
2768 checkThread();
2769 if (!(mView instanceof ViewGroup)) {
2770 return null;
2771 }
2772 return FocusFinder.getInstance().findNextFocus((ViewGroup) mView, focused, direction);
2773 }
2774
2775 public void debug() {
2776 mView.debug();
2777 }
2778
2779 public void die(boolean immediate) {
Dianne Hackborn94d69142009-09-28 22:14:42 -07002780 if (immediate) {
2781 doDie();
2782 } else {
2783 sendEmptyMessage(DIE);
2784 }
2785 }
2786
2787 void doDie() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002788 checkThread();
Jeff Brownb75fa302010-07-15 23:47:29 -07002789 if (LOCAL_LOGV) Log.v(TAG, "DIE in " + this + " of " + mSurface);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002790 synchronized (this) {
2791 if (mAdded && !mFirst) {
Romain Guy29d89972010-09-22 16:10:57 -07002792 destroyHardwareRenderer();
2793
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002794 int viewVisibility = mView.getVisibility();
2795 boolean viewVisibilityChanged = mViewVisibility != viewVisibility;
2796 if (mWindowAttributesChanged || viewVisibilityChanged) {
2797 // If layout params have been changed, first give them
2798 // to the window manager to make sure it has the correct
2799 // animation info.
2800 try {
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002801 if ((relayoutWindow(mWindowAttributes, viewVisibility, false)
2802 & WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002803 sWindowSession.finishDrawing(mWindow);
2804 }
2805 } catch (RemoteException e) {
2806 }
2807 }
2808
Dianne Hackborn0586a1b2009-09-06 21:08:27 -07002809 mSurface.release();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002810 }
2811 if (mAdded) {
2812 mAdded = false;
Dianne Hackborn94d69142009-09-28 22:14:42 -07002813 dispatchDetachedFromWindow();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002814 }
2815 }
2816 }
2817
Romain Guy29d89972010-09-22 16:10:57 -07002818 private void destroyHardwareRenderer() {
Romain Guyb051e892010-09-28 19:09:36 -07002819 if (mAttachInfo.mHardwareRenderer != null) {
2820 mAttachInfo.mHardwareRenderer.destroy(true);
2821 mAttachInfo.mHardwareRenderer = null;
Romain Guy29d89972010-09-22 16:10:57 -07002822 mAttachInfo.mHardwareAccelerated = false;
2823 }
2824 }
2825
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002826 public void dispatchFinishedEvent(int seq, boolean handled) {
2827 Message msg = obtainMessage(FINISHED_EVENT);
2828 msg.arg1 = seq;
2829 msg.arg2 = handled ? 1 : 0;
2830 sendMessage(msg);
2831 }
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002832
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002833 public void dispatchResized(int w, int h, Rect coveredInsets,
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002834 Rect visibleInsets, boolean reportDraw, Configuration newConfig) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002835 if (DEBUG_LAYOUT) Log.v(TAG, "Resizing " + this + ": w=" + w
2836 + " h=" + h + " coveredInsets=" + coveredInsets.toShortString()
2837 + " visibleInsets=" + visibleInsets.toShortString()
2838 + " reportDraw=" + reportDraw);
2839 Message msg = obtainMessage(reportDraw ? RESIZED_REPORT :RESIZED);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002840 if (mTranslator != null) {
2841 mTranslator.translateRectInScreenToAppWindow(coveredInsets);
2842 mTranslator.translateRectInScreenToAppWindow(visibleInsets);
2843 w *= mTranslator.applicationInvertedScale;
2844 h *= mTranslator.applicationInvertedScale;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002845 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002846 msg.arg1 = w;
2847 msg.arg2 = h;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002848 ResizedInfo ri = new ResizedInfo();
2849 ri.coveredInsets = new Rect(coveredInsets);
2850 ri.visibleInsets = new Rect(visibleInsets);
2851 ri.newConfig = newConfig;
2852 msg.obj = ri;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002853 sendMessage(msg);
2854 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002855
Jeff Brown3915bb82010-11-05 15:02:16 -07002856 private InputQueue.FinishedCallback mFinishedCallback;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002857
2858 private final InputHandler mInputHandler = new InputHandler() {
Jeff Brown3915bb82010-11-05 15:02:16 -07002859 public void handleKey(KeyEvent event, InputQueue.FinishedCallback finishedCallback) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07002860 startInputEvent(finishedCallback);
Jeff Brown92ff1dd2010-08-11 16:16:06 -07002861 dispatchKey(event, true);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002862 }
2863
Jeff Brown3915bb82010-11-05 15:02:16 -07002864 public void handleMotion(MotionEvent event, InputQueue.FinishedCallback finishedCallback) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07002865 startInputEvent(finishedCallback);
2866 dispatchMotion(event, true);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002867 }
2868 };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002869
2870 public void dispatchKey(KeyEvent event) {
Jeff Brown92ff1dd2010-08-11 16:16:06 -07002871 dispatchKey(event, false);
2872 }
2873
2874 private void dispatchKey(KeyEvent event, boolean sendDone) {
2875 //noinspection ConstantConditions
2876 if (false && event.getAction() == KeyEvent.ACTION_DOWN) {
2877 if (event.getKeyCode() == KeyEvent.KEYCODE_CAMERA) {
Romain Guy812ccbe2010-06-01 14:07:24 -07002878 if (DBG) Log.d("keydisp", "===================================================");
2879 if (DBG) Log.d("keydisp", "Focused view Hierarchy is:");
2880
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002881 debug();
2882
Romain Guy812ccbe2010-06-01 14:07:24 -07002883 if (DBG) Log.d("keydisp", "===================================================");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002884 }
2885 }
2886
2887 Message msg = obtainMessage(DISPATCH_KEY);
2888 msg.obj = event;
Jeff Brown92ff1dd2010-08-11 16:16:06 -07002889 msg.arg1 = sendDone ? 1 : 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002890
2891 if (LOCAL_LOGV) Log.v(
Jeff Brownc5ed5912010-07-14 18:48:53 -07002892 TAG, "sending key " + event + " to " + mView);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002893
2894 sendMessageAtTime(msg, event.getEventTime());
2895 }
Jeff Brownc5ed5912010-07-14 18:48:53 -07002896
2897 public void dispatchMotion(MotionEvent event) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07002898 dispatchMotion(event, false);
2899 }
2900
2901 private void dispatchMotion(MotionEvent event, boolean sendDone) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07002902 int source = event.getSource();
2903 if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07002904 dispatchPointer(event, sendDone);
Jeff Brownc5ed5912010-07-14 18:48:53 -07002905 } else if ((source & InputDevice.SOURCE_CLASS_TRACKBALL) != 0) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07002906 dispatchTrackball(event, sendDone);
Jeff Brownc5ed5912010-07-14 18:48:53 -07002907 } else {
2908 // TODO
2909 Log.v(TAG, "Dropping unsupported motion event (unimplemented): " + event);
Jeff Brown93ed4e32010-09-23 13:51:48 -07002910 if (sendDone) {
Jeff Brown3915bb82010-11-05 15:02:16 -07002911 finishInputEvent(false);
Jeff Brown93ed4e32010-09-23 13:51:48 -07002912 }
Jeff Brownc5ed5912010-07-14 18:48:53 -07002913 }
2914 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002915
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002916 public void dispatchPointer(MotionEvent event) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07002917 dispatchPointer(event, false);
2918 }
2919
2920 private void dispatchPointer(MotionEvent event, boolean sendDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002921 Message msg = obtainMessage(DISPATCH_POINTER);
2922 msg.obj = event;
Jeff Brown93ed4e32010-09-23 13:51:48 -07002923 msg.arg1 = sendDone ? 1 : 0;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002924 sendMessageAtTime(msg, event.getEventTime());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002925 }
2926
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002927 public void dispatchTrackball(MotionEvent event) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07002928 dispatchTrackball(event, false);
2929 }
2930
2931 private void dispatchTrackball(MotionEvent event, boolean sendDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002932 Message msg = obtainMessage(DISPATCH_TRACKBALL);
2933 msg.obj = event;
Jeff Brown93ed4e32010-09-23 13:51:48 -07002934 msg.arg1 = sendDone ? 1 : 0;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002935 sendMessageAtTime(msg, event.getEventTime());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002936 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002937
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002938 public void dispatchAppVisibility(boolean visible) {
2939 Message msg = obtainMessage(DISPATCH_APP_VISIBILITY);
2940 msg.arg1 = visible ? 1 : 0;
2941 sendMessage(msg);
2942 }
2943
2944 public void dispatchGetNewSurface() {
2945 Message msg = obtainMessage(DISPATCH_GET_NEW_SURFACE);
2946 sendMessage(msg);
2947 }
2948
2949 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
2950 Message msg = Message.obtain();
2951 msg.what = WINDOW_FOCUS_CHANGED;
2952 msg.arg1 = hasFocus ? 1 : 0;
2953 msg.arg2 = inTouchMode ? 1 : 0;
2954 sendMessage(msg);
2955 }
2956
Dianne Hackbornffa42482009-09-23 22:20:11 -07002957 public void dispatchCloseSystemDialogs(String reason) {
2958 Message msg = Message.obtain();
2959 msg.what = CLOSE_SYSTEM_DIALOGS;
2960 msg.obj = reason;
2961 sendMessage(msg);
2962 }
Christopher Tatea53146c2010-09-07 11:57:52 -07002963
2964 public void dispatchDragEvent(DragEvent event) {
Chris Tate91e9bb32010-10-12 12:58:43 -07002965 final int what;
2966 if (event.getAction() == DragEvent.ACTION_DRAG_LOCATION) {
2967 what = DISPATCH_DRAG_LOCATION_EVENT;
2968 removeMessages(what);
2969 } else {
2970 what = DISPATCH_DRAG_EVENT;
2971 }
2972 Message msg = obtainMessage(what, event);
Christopher Tatea53146c2010-09-07 11:57:52 -07002973 sendMessage(msg);
2974 }
2975
svetoslavganov75986cf2009-05-14 22:28:01 -07002976 /**
2977 * The window is getting focus so if there is anything focused/selected
2978 * send an {@link AccessibilityEvent} to announce that.
2979 */
2980 private void sendAccessibilityEvents() {
2981 if (!AccessibilityManager.getInstance(mView.getContext()).isEnabled()) {
2982 return;
2983 }
2984 mView.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
2985 View focusedView = mView.findFocus();
2986 if (focusedView != null && focusedView != mView) {
2987 focusedView.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
2988 }
2989 }
2990
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002991 public boolean showContextMenuForChild(View originalView) {
2992 return false;
2993 }
2994
Adam Powell6e346362010-07-23 10:18:23 -07002995 public ActionMode startActionModeForChild(View originalView, ActionMode.Callback callback) {
2996 return null;
2997 }
2998
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002999 public void createContextMenu(ContextMenu menu) {
3000 }
3001
3002 public void childDrawableStateChanged(View child) {
3003 }
3004
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003005 void checkThread() {
3006 if (mThread != Thread.currentThread()) {
3007 throw new CalledFromWrongThreadException(
3008 "Only the original thread that created a view hierarchy can touch its views.");
3009 }
3010 }
3011
3012 public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
3013 // ViewRoot never intercepts touch event, so this can be a no-op
3014 }
3015
3016 public boolean requestChildRectangleOnScreen(View child, Rect rectangle,
3017 boolean immediate) {
3018 return scrollToRectOrFocus(rectangle, immediate);
3019 }
Romain Guy8506ab42009-06-11 17:35:47 -07003020
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07003021 class TakenSurfaceHolder extends BaseSurfaceHolder {
3022 @Override
3023 public boolean onAllowLockCanvas() {
3024 return mDrawingAllowed;
3025 }
3026
3027 @Override
3028 public void onRelayoutContainer() {
3029 // Not currently interesting -- from changing between fixed and layout size.
3030 }
3031
3032 public void setFormat(int format) {
3033 ((RootViewSurfaceTaker)mView).setSurfaceFormat(format);
3034 }
3035
3036 public void setType(int type) {
3037 ((RootViewSurfaceTaker)mView).setSurfaceType(type);
3038 }
3039
3040 @Override
3041 public void onUpdateSurface() {
3042 // We take care of format and type changes on our own.
3043 throw new IllegalStateException("Shouldn't be here");
3044 }
3045
3046 public boolean isCreating() {
3047 return mIsCreating;
3048 }
3049
3050 @Override
3051 public void setFixedSize(int width, int height) {
3052 throw new UnsupportedOperationException(
3053 "Currently only support sizing from layout");
3054 }
3055
3056 public void setKeepScreenOn(boolean screenOn) {
3057 ((RootViewSurfaceTaker)mView).setSurfaceKeepScreenOn(screenOn);
3058 }
3059 }
3060
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003061 static class InputMethodCallback extends IInputMethodCallback.Stub {
3062 private WeakReference<ViewRoot> mViewRoot;
3063
3064 public InputMethodCallback(ViewRoot viewRoot) {
3065 mViewRoot = new WeakReference<ViewRoot>(viewRoot);
3066 }
Romain Guy8506ab42009-06-11 17:35:47 -07003067
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003068 public void finishedEvent(int seq, boolean handled) {
3069 final ViewRoot viewRoot = mViewRoot.get();
3070 if (viewRoot != null) {
3071 viewRoot.dispatchFinishedEvent(seq, handled);
3072 }
3073 }
3074
3075 public void sessionCreated(IInputMethodSession session) throws RemoteException {
3076 // Stub -- not for use in the client.
3077 }
3078 }
Romain Guy8506ab42009-06-11 17:35:47 -07003079
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003080 static class W extends IWindow.Stub {
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07003081 private final WeakReference<ViewRoot> mViewRoot;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003082
Romain Guyfb8b7632010-08-23 21:05:08 -07003083 W(ViewRoot viewRoot) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003084 mViewRoot = new WeakReference<ViewRoot>(viewRoot);
3085 }
3086
Romain Guyfb8b7632010-08-23 21:05:08 -07003087 public void resized(int w, int h, Rect coveredInsets, Rect visibleInsets,
3088 boolean reportDraw, Configuration newConfig) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003089 final ViewRoot viewRoot = mViewRoot.get();
3090 if (viewRoot != null) {
Romain Guyfb8b7632010-08-23 21:05:08 -07003091 viewRoot.dispatchResized(w, h, coveredInsets, visibleInsets, reportDraw, newConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003092 }
3093 }
3094
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003095 public void dispatchAppVisibility(boolean visible) {
3096 final ViewRoot viewRoot = mViewRoot.get();
3097 if (viewRoot != null) {
3098 viewRoot.dispatchAppVisibility(visible);
3099 }
3100 }
3101
3102 public void dispatchGetNewSurface() {
3103 final ViewRoot viewRoot = mViewRoot.get();
3104 if (viewRoot != null) {
3105 viewRoot.dispatchGetNewSurface();
3106 }
3107 }
3108
3109 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
3110 final ViewRoot viewRoot = mViewRoot.get();
3111 if (viewRoot != null) {
3112 viewRoot.windowFocusChanged(hasFocus, inTouchMode);
3113 }
3114 }
3115
3116 private static int checkCallingPermission(String permission) {
3117 if (!Process.supportsProcesses()) {
3118 return PackageManager.PERMISSION_GRANTED;
3119 }
3120
3121 try {
3122 return ActivityManagerNative.getDefault().checkPermission(
3123 permission, Binder.getCallingPid(), Binder.getCallingUid());
3124 } catch (RemoteException e) {
3125 return PackageManager.PERMISSION_DENIED;
3126 }
3127 }
3128
3129 public void executeCommand(String command, String parameters, ParcelFileDescriptor out) {
3130 final ViewRoot viewRoot = mViewRoot.get();
3131 if (viewRoot != null) {
3132 final View view = viewRoot.mView;
3133 if (view != null) {
3134 if (checkCallingPermission(Manifest.permission.DUMP) !=
3135 PackageManager.PERMISSION_GRANTED) {
3136 throw new SecurityException("Insufficient permissions to invoke"
3137 + " executeCommand() from pid=" + Binder.getCallingPid()
3138 + ", uid=" + Binder.getCallingUid());
3139 }
3140
3141 OutputStream clientStream = null;
3142 try {
3143 clientStream = new ParcelFileDescriptor.AutoCloseOutputStream(out);
3144 ViewDebug.dispatchCommand(view, command, parameters, clientStream);
3145 } catch (IOException e) {
3146 e.printStackTrace();
3147 } finally {
3148 if (clientStream != null) {
3149 try {
3150 clientStream.close();
3151 } catch (IOException e) {
3152 e.printStackTrace();
3153 }
3154 }
3155 }
3156 }
3157 }
3158 }
Dianne Hackborn72c82ab2009-08-11 21:13:54 -07003159
Dianne Hackbornffa42482009-09-23 22:20:11 -07003160 public void closeSystemDialogs(String reason) {
3161 final ViewRoot viewRoot = mViewRoot.get();
3162 if (viewRoot != null) {
3163 viewRoot.dispatchCloseSystemDialogs(reason);
3164 }
3165 }
3166
Marco Nelissenbf6956b2009-11-09 15:21:13 -08003167 public void dispatchWallpaperOffsets(float x, float y, float xStep, float yStep,
3168 boolean sync) {
Dianne Hackborn19382ac2009-09-11 21:13:37 -07003169 if (sync) {
3170 try {
3171 sWindowSession.wallpaperOffsetsComplete(asBinder());
3172 } catch (RemoteException e) {
3173 }
3174 }
Dianne Hackborn72c82ab2009-08-11 21:13:54 -07003175 }
Dianne Hackborn75804932009-10-20 20:15:20 -07003176
3177 public void dispatchWallpaperCommand(String action, int x, int y,
3178 int z, Bundle extras, boolean sync) {
3179 if (sync) {
3180 try {
3181 sWindowSession.wallpaperCommandComplete(asBinder(), null);
3182 } catch (RemoteException e) {
3183 }
3184 }
3185 }
Christopher Tatea53146c2010-09-07 11:57:52 -07003186
3187 /* Drag/drop */
3188 public void dispatchDragEvent(DragEvent event) {
3189 final ViewRoot viewRoot = mViewRoot.get();
3190 if (viewRoot != null) {
3191 viewRoot.dispatchDragEvent(event);
3192 }
3193 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003194 }
3195
3196 /**
3197 * Maintains state information for a single trackball axis, generating
3198 * discrete (DPAD) movements based on raw trackball motion.
3199 */
3200 static final class TrackballAxis {
3201 /**
3202 * The maximum amount of acceleration we will apply.
3203 */
3204 static final float MAX_ACCELERATION = 20;
Romain Guy8506ab42009-06-11 17:35:47 -07003205
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003206 /**
3207 * The maximum amount of time (in milliseconds) between events in order
3208 * for us to consider the user to be doing fast trackball movements,
3209 * and thus apply an acceleration.
3210 */
3211 static final long FAST_MOVE_TIME = 150;
Romain Guy8506ab42009-06-11 17:35:47 -07003212
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003213 /**
3214 * Scaling factor to the time (in milliseconds) between events to how
3215 * much to multiple/divide the current acceleration. When movement
3216 * is < FAST_MOVE_TIME this multiplies the acceleration; when >
3217 * FAST_MOVE_TIME it divides it.
3218 */
3219 static final float ACCEL_MOVE_SCALING_FACTOR = (1.0f/40);
Romain Guy8506ab42009-06-11 17:35:47 -07003220
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003221 float position;
3222 float absPosition;
3223 float acceleration = 1;
3224 long lastMoveTime = 0;
3225 int step;
3226 int dir;
3227 int nonAccelMovement;
3228
3229 void reset(int _step) {
3230 position = 0;
3231 acceleration = 1;
3232 lastMoveTime = 0;
3233 step = _step;
3234 dir = 0;
3235 }
3236
3237 /**
3238 * Add trackball movement into the state. If the direction of movement
3239 * has been reversed, the state is reset before adding the
3240 * movement (so that you don't have to compensate for any previously
3241 * collected movement before see the result of the movement in the
3242 * new direction).
3243 *
3244 * @return Returns the absolute value of the amount of movement
3245 * collected so far.
3246 */
3247 float collect(float off, long time, String axis) {
3248 long normTime;
3249 if (off > 0) {
3250 normTime = (long)(off * FAST_MOVE_TIME);
3251 if (dir < 0) {
3252 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to positive!");
3253 position = 0;
3254 step = 0;
3255 acceleration = 1;
3256 lastMoveTime = 0;
3257 }
3258 dir = 1;
3259 } else if (off < 0) {
3260 normTime = (long)((-off) * FAST_MOVE_TIME);
3261 if (dir > 0) {
3262 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to negative!");
3263 position = 0;
3264 step = 0;
3265 acceleration = 1;
3266 lastMoveTime = 0;
3267 }
3268 dir = -1;
3269 } else {
3270 normTime = 0;
3271 }
Romain Guy8506ab42009-06-11 17:35:47 -07003272
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003273 // The number of milliseconds between each movement that is
3274 // considered "normal" and will not result in any acceleration
3275 // or deceleration, scaled by the offset we have here.
3276 if (normTime > 0) {
3277 long delta = time - lastMoveTime;
3278 lastMoveTime = time;
3279 float acc = acceleration;
3280 if (delta < normTime) {
3281 // The user is scrolling rapidly, so increase acceleration.
3282 float scale = (normTime-delta) * ACCEL_MOVE_SCALING_FACTOR;
3283 if (scale > 1) acc *= scale;
3284 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " accelerate: off="
3285 + off + " normTime=" + normTime + " delta=" + delta
3286 + " scale=" + scale + " acc=" + acc);
3287 acceleration = acc < MAX_ACCELERATION ? acc : MAX_ACCELERATION;
3288 } else {
3289 // The user is scrolling slowly, so decrease acceleration.
3290 float scale = (delta-normTime) * ACCEL_MOVE_SCALING_FACTOR;
3291 if (scale > 1) acc /= scale;
3292 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " deccelerate: off="
3293 + off + " normTime=" + normTime + " delta=" + delta
3294 + " scale=" + scale + " acc=" + acc);
3295 acceleration = acc > 1 ? acc : 1;
3296 }
3297 }
3298 position += off;
3299 return (absPosition = Math.abs(position));
3300 }
3301
3302 /**
3303 * Generate the number of discrete movement events appropriate for
3304 * the currently collected trackball movement.
3305 *
3306 * @param precision The minimum movement required to generate the
3307 * first discrete movement.
3308 *
3309 * @return Returns the number of discrete movements, either positive
3310 * or negative, or 0 if there is not enough trackball movement yet
3311 * for a discrete movement.
3312 */
3313 int generate(float precision) {
3314 int movement = 0;
3315 nonAccelMovement = 0;
3316 do {
3317 final int dir = position >= 0 ? 1 : -1;
3318 switch (step) {
3319 // If we are going to execute the first step, then we want
3320 // to do this as soon as possible instead of waiting for
3321 // a full movement, in order to make things look responsive.
3322 case 0:
3323 if (absPosition < precision) {
3324 return movement;
3325 }
3326 movement += dir;
3327 nonAccelMovement += dir;
3328 step = 1;
3329 break;
3330 // If we have generated the first movement, then we need
3331 // to wait for the second complete trackball motion before
3332 // generating the second discrete movement.
3333 case 1:
3334 if (absPosition < 2) {
3335 return movement;
3336 }
3337 movement += dir;
3338 nonAccelMovement += dir;
3339 position += dir > 0 ? -2 : 2;
3340 absPosition = Math.abs(position);
3341 step = 2;
3342 break;
3343 // After the first two, we generate discrete movements
3344 // consistently with the trackball, applying an acceleration
3345 // if the trackball is moving quickly. This is a simple
3346 // acceleration on top of what we already compute based
3347 // on how quickly the wheel is being turned, to apply
3348 // a longer increasing acceleration to continuous movement
3349 // in one direction.
3350 default:
3351 if (absPosition < 1) {
3352 return movement;
3353 }
3354 movement += dir;
3355 position += dir >= 0 ? -1 : 1;
3356 absPosition = Math.abs(position);
3357 float acc = acceleration;
3358 acc *= 1.1f;
3359 acceleration = acc < MAX_ACCELERATION ? acc : acceleration;
3360 break;
3361 }
3362 } while (true);
3363 }
3364 }
3365
3366 public static final class CalledFromWrongThreadException extends AndroidRuntimeException {
3367 public CalledFromWrongThreadException(String msg) {
3368 super(msg);
3369 }
3370 }
3371
3372 private SurfaceHolder mHolder = new SurfaceHolder() {
3373 // we only need a SurfaceHolder for opengl. it would be nice
3374 // to implement everything else though, especially the callback
3375 // support (opengl doesn't make use of it right now, but eventually
3376 // will).
3377 public Surface getSurface() {
3378 return mSurface;
3379 }
3380
3381 public boolean isCreating() {
3382 return false;
3383 }
3384
3385 public void addCallback(Callback callback) {
3386 }
3387
3388 public void removeCallback(Callback callback) {
3389 }
3390
3391 public void setFixedSize(int width, int height) {
3392 }
3393
3394 public void setSizeFromLayout() {
3395 }
3396
3397 public void setFormat(int format) {
3398 }
3399
3400 public void setType(int type) {
3401 }
3402
3403 public void setKeepScreenOn(boolean screenOn) {
3404 }
3405
3406 public Canvas lockCanvas() {
3407 return null;
3408 }
3409
3410 public Canvas lockCanvas(Rect dirty) {
3411 return null;
3412 }
3413
3414 public void unlockCanvasAndPost(Canvas canvas) {
3415 }
3416 public Rect getSurfaceFrame() {
3417 return null;
3418 }
3419 };
3420
3421 static RunQueue getRunQueue() {
3422 RunQueue rq = sRunQueues.get();
3423 if (rq != null) {
3424 return rq;
3425 }
3426 rq = new RunQueue();
3427 sRunQueues.set(rq);
3428 return rq;
3429 }
Romain Guy8506ab42009-06-11 17:35:47 -07003430
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003431 /**
3432 * @hide
3433 */
3434 static final class RunQueue {
3435 private final ArrayList<HandlerAction> mActions = new ArrayList<HandlerAction>();
3436
3437 void post(Runnable action) {
3438 postDelayed(action, 0);
3439 }
3440
3441 void postDelayed(Runnable action, long delayMillis) {
3442 HandlerAction handlerAction = new HandlerAction();
3443 handlerAction.action = action;
3444 handlerAction.delay = delayMillis;
3445
3446 synchronized (mActions) {
3447 mActions.add(handlerAction);
3448 }
3449 }
3450
3451 void removeCallbacks(Runnable action) {
3452 final HandlerAction handlerAction = new HandlerAction();
3453 handlerAction.action = action;
3454
3455 synchronized (mActions) {
3456 final ArrayList<HandlerAction> actions = mActions;
3457
3458 while (actions.remove(handlerAction)) {
3459 // Keep going
3460 }
3461 }
3462 }
3463
3464 void executeActions(Handler handler) {
3465 synchronized (mActions) {
3466 final ArrayList<HandlerAction> actions = mActions;
3467 final int count = actions.size();
3468
3469 for (int i = 0; i < count; i++) {
3470 final HandlerAction handlerAction = actions.get(i);
3471 handler.postDelayed(handlerAction.action, handlerAction.delay);
3472 }
3473
Romain Guy15df6702009-08-17 20:17:30 -07003474 actions.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003475 }
3476 }
3477
3478 private static class HandlerAction {
3479 Runnable action;
3480 long delay;
3481
3482 @Override
3483 public boolean equals(Object o) {
3484 if (this == o) return true;
3485 if (o == null || getClass() != o.getClass()) return false;
3486
3487 HandlerAction that = (HandlerAction) o;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003488 return !(action != null ? !action.equals(that.action) : that.action != null);
3489
3490 }
3491
3492 @Override
3493 public int hashCode() {
3494 int result = action != null ? action.hashCode() : 0;
3495 result = 31 * result + (int) (delay ^ (delay >>> 32));
3496 return result;
3497 }
3498 }
3499 }
3500
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003501 private static native void nativeShowFPS(Canvas canvas, int durationMillis);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003502}