blob: fa7fe8033f9b3eaf5262e7d7ea47189457950470 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.view;
18
Romain Guy6b7bd242010-10-06 19:49:23 -070019import android.Manifest;
20import android.app.ActivityManagerNative;
21import android.content.ClipDescription;
22import android.content.ComponentCallbacks;
23import android.content.Context;
24import android.content.pm.PackageManager;
25import android.content.res.CompatibilityInfo;
26import android.content.res.Configuration;
27import android.content.res.Resources;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080028import android.graphics.Canvas;
29import android.graphics.PixelFormat;
Christopher Tate2c095f32010-10-04 14:13:40 -070030import android.graphics.Point;
Christopher Tatea53146c2010-09-07 11:57:52 -070031import android.graphics.PointF;
Romain Guy6b7bd242010-10-06 19:49:23 -070032import android.graphics.PorterDuff;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080033import android.graphics.Rect;
34import android.graphics.Region;
Romain Guy6b7bd242010-10-06 19:49:23 -070035import android.media.AudioManager;
36import android.os.Binder;
37import android.os.Bundle;
38import android.os.Debug;
39import android.os.Handler;
40import android.os.LatencyTimer;
41import android.os.Looper;
42import android.os.Message;
43import android.os.ParcelFileDescriptor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080044import android.os.Process;
Romain Guy6b7bd242010-10-06 19:49:23 -070045import android.os.RemoteException;
46import android.os.ServiceManager;
47import android.os.SystemClock;
48import android.os.SystemProperties;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080049import android.util.AndroidRuntimeException;
50import android.util.Config;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -070051import android.util.DisplayMetrics;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080052import android.util.EventLog;
Romain Guy6b7bd242010-10-06 19:49:23 -070053import android.util.Log;
Chet Haase949dbf72010-08-11 18:41:06 -070054import android.util.Slog;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080055import android.util.SparseArray;
Jeff Brown3915bb82010-11-05 15:02:16 -070056import android.view.InputQueue.FinishedCallback;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080057import android.view.View.MeasureSpec;
svetoslavganov75986cf2009-05-14 22:28:01 -070058import android.view.accessibility.AccessibilityEvent;
59import android.view.accessibility.AccessibilityManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080060import android.view.inputmethod.InputConnection;
61import android.view.inputmethod.InputMethodManager;
62import android.widget.Scroller;
Joe Onorato86f67862010-11-05 18:57:34 -070063import com.android.internal.policy.PolicyManager;
Romain Guy6b7bd242010-10-06 19:49:23 -070064import com.android.internal.view.BaseSurfaceHolder;
65import com.android.internal.view.IInputMethodCallback;
66import com.android.internal.view.IInputMethodSession;
67import com.android.internal.view.RootViewSurfaceTaker;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080068
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080069import java.io.IOException;
70import java.io.OutputStream;
Romain Guy6b7bd242010-10-06 19:49:23 -070071import java.lang.ref.WeakReference;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080072import java.util.ArrayList;
73
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080074/**
75 * The top of a view hierarchy, implementing the needed protocol between View
76 * and the WindowManager. This is for the most part an internal implementation
77 * detail of {@link WindowManagerImpl}.
78 *
79 * {@hide}
80 */
Romain Guy812ccbe2010-06-01 14:07:24 -070081@SuppressWarnings({"EmptyCatchBlock", "PointlessBooleanExpression"})
82public final class ViewRoot extends Handler implements ViewParent, View.AttachInfo.Callbacks {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080083 private static final String TAG = "ViewRoot";
84 private static final boolean DBG = false;
Mike Reedfd716532009-10-12 14:42:56 -040085 private static final boolean SHOW_FPS = false;
Romain Guy812ccbe2010-06-01 14:07:24 -070086 private static final boolean LOCAL_LOGV = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080087 /** @noinspection PointlessBooleanExpression*/
88 private static final boolean DEBUG_DRAW = false || LOCAL_LOGV;
89 private static final boolean DEBUG_LAYOUT = false || LOCAL_LOGV;
Christopher Tatefa9e7c02010-05-06 12:07:10 -070090 private static final boolean DEBUG_INPUT = true || LOCAL_LOGV;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080091 private static final boolean DEBUG_INPUT_RESIZE = false || LOCAL_LOGV;
92 private static final boolean DEBUG_ORIENTATION = false || LOCAL_LOGV;
93 private static final boolean DEBUG_TRACKBALL = false || LOCAL_LOGV;
94 private static final boolean DEBUG_IMF = false || LOCAL_LOGV;
Dianne Hackborn694f79b2010-03-17 19:44:59 -070095 private static final boolean DEBUG_CONFIGURATION = false || LOCAL_LOGV;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080096 private static final boolean WATCH_POINTER = false;
97
Michael Chan53071d62009-05-13 17:29:48 -070098 private static final boolean MEASURE_LATENCY = false;
99 private static LatencyTimer lt;
100
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800101 /**
102 * Maximum time we allow the user to roll the trackball enough to generate
103 * a key event, before resetting the counters.
104 */
105 static final int MAX_TRACKBALL_DELAY = 250;
106
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800107 static IWindowSession sWindowSession;
108
109 static final Object mStaticInit = new Object();
110 static boolean mInitialized = false;
111
112 static final ThreadLocal<RunQueue> sRunQueues = new ThreadLocal<RunQueue>();
113
Dianne Hackborn2a9094d2010-02-03 19:20:09 -0800114 static final ArrayList<Runnable> sFirstDrawHandlers = new ArrayList<Runnable>();
115 static boolean sFirstDrawComplete = false;
116
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800117 static final ArrayList<ComponentCallbacks> sConfigCallbacks
118 = new ArrayList<ComponentCallbacks>();
119
Romain Guy8506ab42009-06-11 17:35:47 -0700120 private static int sDrawTime;
Romain Guy13922e02009-05-12 17:56:14 -0700121
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800122 long mLastTrackballTime = 0;
123 final TrackballAxis mTrackballAxisX = new TrackballAxis();
124 final TrackballAxis mTrackballAxisY = new TrackballAxis();
125
126 final int[] mTmpLocation = new int[2];
Romain Guy8506ab42009-06-11 17:35:47 -0700127
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800128 final InputMethodCallback mInputMethodCallback;
129 final SparseArray<Object> mPendingEvents = new SparseArray<Object>();
130 int mPendingEventSeq = 0;
Romain Guy8506ab42009-06-11 17:35:47 -0700131
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800132 final Thread mThread;
133
134 final WindowLeaked mLocation;
135
136 final WindowManager.LayoutParams mWindowAttributes = new WindowManager.LayoutParams();
137
138 final W mWindow;
139
140 View mView;
141 View mFocusedView;
142 View mRealFocusedView; // this is not set to null in touch mode
143 int mViewVisibility;
144 boolean mAppVisible = true;
145
Dianne Hackbornd76b67c2010-07-13 17:48:30 -0700146 SurfaceHolder.Callback2 mSurfaceHolderCallback;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700147 BaseSurfaceHolder mSurfaceHolder;
148 boolean mIsCreating;
149 boolean mDrawingAllowed;
150
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800151 final Region mTransparentRegion;
152 final Region mPreviousTransparentRegion;
153
154 int mWidth;
155 int mHeight;
156 Rect mDirty; // will be a graphics.Region soon
Romain Guybb93d552009-03-24 21:04:15 -0700157 boolean mIsAnimating;
Romain Guy8506ab42009-06-11 17:35:47 -0700158
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700159 CompatibilityInfo.Translator mTranslator;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800160
161 final View.AttachInfo mAttachInfo;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700162 InputChannel mInputChannel;
Dianne Hackborn1e4b9f32010-06-23 14:10:57 -0700163 InputQueue.Callback mInputQueueCallback;
164 InputQueue mInputQueue;
Joe Onorato86f67862010-11-05 18:57:34 -0700165 FallbackEventHandler mFallbackEventHandler;
Dianne Hackborna95e4cb2010-06-18 18:09:33 -0700166
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800167 final Rect mTempRect; // used in the transaction to not thrash the heap.
168 final Rect mVisRect; // used to retrieve visible rect of focused view.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800169
170 boolean mTraversalScheduled;
171 boolean mWillDrawSoon;
172 boolean mLayoutRequested;
173 boolean mFirst;
174 boolean mReportNextDraw;
175 boolean mFullRedrawNeeded;
176 boolean mNewSurfaceNeeded;
177 boolean mHasHadWindowFocus;
178 boolean mLastWasImTarget;
179
180 boolean mWindowAttributesChanged = false;
181
182 // These can be accessed by any thread, must be protected with a lock.
Mathias Agopian5583dc62009-07-09 16:28:11 -0700183 // Surface can never be reassigned or cleared (use Surface.clear()).
184 private final Surface mSurface = new Surface();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800185
186 boolean mAdded;
187 boolean mAddedTouchMode;
188
189 /*package*/ int mAddNesting;
190
191 // These are accessed by multiple threads.
192 final Rect mWinFrame; // frame given by window manager.
193
194 final Rect mPendingVisibleInsets = new Rect();
195 final Rect mPendingContentInsets = new Rect();
196 final ViewTreeObserver.InternalInsetsInfo mLastGivenInsets
197 = new ViewTreeObserver.InternalInsetsInfo();
198
Dianne Hackborn694f79b2010-03-17 19:44:59 -0700199 final Configuration mLastConfiguration = new Configuration();
200 final Configuration mPendingConfiguration = new Configuration();
201
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800202 class ResizedInfo {
203 Rect coveredInsets;
204 Rect visibleInsets;
205 Configuration newConfig;
206 }
207
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800208 boolean mScrollMayChange;
209 int mSoftInputMode;
210 View mLastScrolledFocus;
211 int mScrollY;
212 int mCurScrollY;
213 Scroller mScroller;
Romain Guy8506ab42009-06-11 17:35:47 -0700214
Romain Guy8506ab42009-06-11 17:35:47 -0700215 final ViewConfiguration mViewConfiguration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800216
Christopher Tatea53146c2010-09-07 11:57:52 -0700217 /* Drag/drop */
218 ClipDescription mDragDescription;
219 View mCurrentDragView;
220 final PointF mDragPoint = new PointF();
Christopher Tate2c095f32010-10-04 14:13:40 -0700221 final PointF mLastTouchPoint = new PointF();
Christopher Tatea53146c2010-09-07 11:57:52 -0700222
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800223 /**
224 * see {@link #playSoundEffect(int)}
225 */
226 AudioManager mAudioManager;
227
Dianne Hackborn11ea3342009-07-22 21:48:55 -0700228 private final int mDensity;
Adam Powellb08013c2010-09-16 16:28:11 -0700229
Dianne Hackborn4c62fc02009-08-08 20:40:27 -0700230 public static IWindowSession getWindowSession(Looper mainLooper) {
231 synchronized (mStaticInit) {
232 if (!mInitialized) {
233 try {
234 InputMethodManager imm = InputMethodManager.getInstance(mainLooper);
235 sWindowSession = IWindowManager.Stub.asInterface(
236 ServiceManager.getService("window"))
237 .openSession(imm.getClient(), imm.getInputContext());
238 mInitialized = true;
239 } catch (RemoteException e) {
240 }
241 }
242 return sWindowSession;
243 }
244 }
245
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800246 public ViewRoot(Context context) {
247 super();
248
Romain Guy812ccbe2010-06-01 14:07:24 -0700249 if (MEASURE_LATENCY) {
250 if (lt == null) {
251 lt = new LatencyTimer(100, 1000);
252 }
Michael Chan53071d62009-05-13 17:29:48 -0700253 }
254
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800255 // Initialize the statics when this class is first instantiated. This is
256 // done here instead of in the static block because Zygote does not
257 // allow the spawning of threads.
Dianne Hackborn4c62fc02009-08-08 20:40:27 -0700258 getWindowSession(context.getMainLooper());
259
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800260 mThread = Thread.currentThread();
261 mLocation = new WindowLeaked(null);
262 mLocation.fillInStackTrace();
263 mWidth = -1;
264 mHeight = -1;
265 mDirty = new Rect();
266 mTempRect = new Rect();
267 mVisRect = new Rect();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800268 mWinFrame = new Rect();
Romain Guyfb8b7632010-08-23 21:05:08 -0700269 mWindow = new W(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800270 mInputMethodCallback = new InputMethodCallback(this);
271 mViewVisibility = View.GONE;
272 mTransparentRegion = new Region();
273 mPreviousTransparentRegion = new Region();
274 mFirst = true; // true for the first time the view is added
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800275 mAdded = false;
276 mAttachInfo = new View.AttachInfo(sWindowSession, mWindow, this, this);
277 mViewConfiguration = ViewConfiguration.get(context);
Dianne Hackborn11ea3342009-07-22 21:48:55 -0700278 mDensity = context.getResources().getDisplayMetrics().densityDpi;
Joe Onorato86f67862010-11-05 18:57:34 -0700279 mFallbackEventHandler = PolicyManager.makeNewFallbackEventHandler(context);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800280 }
281
Dianne Hackborn2a9094d2010-02-03 19:20:09 -0800282 public static void addFirstDrawHandler(Runnable callback) {
283 synchronized (sFirstDrawHandlers) {
284 if (!sFirstDrawComplete) {
285 sFirstDrawHandlers.add(callback);
286 }
287 }
288 }
289
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800290 public static void addConfigCallback(ComponentCallbacks callback) {
291 synchronized (sConfigCallbacks) {
292 sConfigCallbacks.add(callback);
293 }
294 }
295
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800296 // FIXME for perf testing only
297 private boolean mProfile = false;
298
299 /**
300 * Call this to profile the next traversal call.
301 * FIXME for perf testing only. Remove eventually
302 */
303 public void profile() {
304 mProfile = true;
305 }
306
307 /**
308 * Indicates whether we are in touch mode. Calling this method triggers an IPC
309 * call and should be avoided whenever possible.
310 *
311 * @return True, if the device is in touch mode, false otherwise.
312 *
313 * @hide
314 */
315 static boolean isInTouchMode() {
316 if (mInitialized) {
317 try {
318 return sWindowSession.getInTouchMode();
319 } catch (RemoteException e) {
320 }
321 }
322 return false;
323 }
324
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800325 /**
326 * We have one child
327 */
Romain Guye4d01122010-06-16 18:44:05 -0700328 public void setView(View view, WindowManager.LayoutParams attrs, View panelParentView) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800329 synchronized (this) {
330 if (mView == null) {
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700331 mView = view;
Joe Onorato86f67862010-11-05 18:57:34 -0700332 mFallbackEventHandler.setView(view);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700333 mWindowAttributes.copyFrom(attrs);
Mitsuru Oshima1ecf5d22009-07-06 17:20:38 -0700334 attrs = mWindowAttributes;
Romain Guye4d01122010-06-16 18:44:05 -0700335
Romain Guy529b60a2010-08-03 18:05:47 -0700336 enableHardwareAcceleration(attrs);
Romain Guye4d01122010-06-16 18:44:05 -0700337
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700338 if (view instanceof RootViewSurfaceTaker) {
339 mSurfaceHolderCallback =
340 ((RootViewSurfaceTaker)view).willYouTakeTheSurface();
341 if (mSurfaceHolderCallback != null) {
342 mSurfaceHolder = new TakenSurfaceHolder();
Dianne Hackborn289b9b62010-07-09 11:44:11 -0700343 mSurfaceHolder.setFormat(PixelFormat.UNKNOWN);
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700344 }
345 }
Mitsuru Oshima38ed7d772009-07-21 14:39:34 -0700346 Resources resources = mView.getContext().getResources();
347 CompatibilityInfo compatibilityInfo = resources.getCompatibilityInfo();
Mitsuru Oshima589cebe2009-07-22 20:38:58 -0700348 mTranslator = compatibilityInfo.getTranslator();
Mitsuru Oshima38ed7d772009-07-21 14:39:34 -0700349
350 if (mTranslator != null || !compatibilityInfo.supportsScreen()) {
Mitsuru Oshima240f8a72009-07-22 20:39:14 -0700351 mSurface.setCompatibleDisplayMetrics(resources.getDisplayMetrics(),
352 mTranslator);
Mitsuru Oshima38ed7d772009-07-21 14:39:34 -0700353 }
354
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -0700355 boolean restore = false;
Romain Guy35b38ce2009-10-07 13:38:55 -0700356 if (mTranslator != null) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -0700357 restore = true;
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700358 attrs.backup();
359 mTranslator.translateWindowLayout(attrs);
Mitsuru Oshima3d914922009-05-13 22:29:15 -0700360 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700361 if (DEBUG_LAYOUT) Log.d(TAG, "WindowLayout in setView:" + attrs);
362
Mitsuru Oshima1ecf5d22009-07-06 17:20:38 -0700363 if (!compatibilityInfo.supportsScreen()) {
364 attrs.flags |= WindowManager.LayoutParams.FLAG_COMPATIBLE_WINDOW;
365 }
366
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800367 mSoftInputMode = attrs.softInputMode;
368 mWindowAttributesChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800369 mAttachInfo.mRootView = view;
Romain Guy35b38ce2009-10-07 13:38:55 -0700370 mAttachInfo.mScalingRequired = mTranslator != null;
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700371 mAttachInfo.mApplicationScale =
372 mTranslator == null ? 1.0f : mTranslator.applicationScale;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800373 if (panelParentView != null) {
374 mAttachInfo.mPanelParentWindowToken
375 = panelParentView.getApplicationWindowToken();
376 }
377 mAdded = true;
378 int res; /* = WindowManagerImpl.ADD_OKAY; */
Romain Guy8506ab42009-06-11 17:35:47 -0700379
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800380 // Schedule the first layout -before- adding to the window
381 // manager, to make sure we do the relayout before receiving
382 // any other events from the system.
383 requestLayout();
Jeff Brown46b9ac02010-04-22 18:58:52 -0700384 mInputChannel = new InputChannel();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800385 try {
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700386 res = sWindowSession.add(mWindow, mWindowAttributes,
Jeff Brown46b9ac02010-04-22 18:58:52 -0700387 getHostVisibility(), mAttachInfo.mContentInsets,
388 mInputChannel);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800389 } catch (RemoteException e) {
390 mAdded = false;
391 mView = null;
392 mAttachInfo.mRootView = null;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700393 mInputChannel = null;
Joe Onorato86f67862010-11-05 18:57:34 -0700394 mFallbackEventHandler.setView(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800395 unscheduleTraversals();
396 throw new RuntimeException("Adding window failed", e);
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700397 } finally {
398 if (restore) {
399 attrs.restore();
400 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800401 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700402
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700403 if (mTranslator != null) {
404 mTranslator.translateRectInScreenToAppWindow(mAttachInfo.mContentInsets);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700405 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800406 mPendingContentInsets.set(mAttachInfo.mContentInsets);
407 mPendingVisibleInsets.set(0, 0, 0, 0);
Jeff Brownc5ed5912010-07-14 18:48:53 -0700408 if (Config.LOGV) Log.v(TAG, "Added window " + mWindow);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800409 if (res < WindowManagerImpl.ADD_OKAY) {
410 mView = null;
411 mAttachInfo.mRootView = null;
412 mAdded = false;
Joe Onorato86f67862010-11-05 18:57:34 -0700413 mFallbackEventHandler.setView(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800414 unscheduleTraversals();
415 switch (res) {
416 case WindowManagerImpl.ADD_BAD_APP_TOKEN:
417 case WindowManagerImpl.ADD_BAD_SUBWINDOW_TOKEN:
418 throw new WindowManagerImpl.BadTokenException(
419 "Unable to add window -- token " + attrs.token
420 + " is not valid; is your activity running?");
421 case WindowManagerImpl.ADD_NOT_APP_TOKEN:
422 throw new WindowManagerImpl.BadTokenException(
423 "Unable to add window -- token " + attrs.token
424 + " is not for an application");
425 case WindowManagerImpl.ADD_APP_EXITING:
426 throw new WindowManagerImpl.BadTokenException(
427 "Unable to add window -- app for token " + attrs.token
428 + " is exiting");
429 case WindowManagerImpl.ADD_DUPLICATE_ADD:
430 throw new WindowManagerImpl.BadTokenException(
431 "Unable to add window -- window " + mWindow
432 + " has already been added");
433 case WindowManagerImpl.ADD_STARTING_NOT_NEEDED:
434 // Silently ignore -- we would have just removed it
435 // right away, anyway.
436 return;
437 case WindowManagerImpl.ADD_MULTIPLE_SINGLETON:
438 throw new WindowManagerImpl.BadTokenException(
439 "Unable to add window " + mWindow +
440 " -- another window of this type already exists");
441 case WindowManagerImpl.ADD_PERMISSION_DENIED:
442 throw new WindowManagerImpl.BadTokenException(
443 "Unable to add window " + mWindow +
444 " -- permission denied for this window type");
445 }
446 throw new RuntimeException(
447 "Unable to add window -- unknown error code " + res);
448 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700449
Jeff Brown00fa7bd2010-07-02 15:37:36 -0700450 if (view instanceof RootViewSurfaceTaker) {
451 mInputQueueCallback =
452 ((RootViewSurfaceTaker)view).willYouTakeTheInputQueue();
453 }
454 if (mInputQueueCallback != null) {
455 mInputQueue = new InputQueue(mInputChannel);
456 mInputQueueCallback.onInputQueueCreated(mInputQueue);
457 } else {
458 InputQueue.registerInputChannel(mInputChannel, mInputHandler,
459 Looper.myQueue());
Jeff Brown46b9ac02010-04-22 18:58:52 -0700460 }
461
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800462 view.assignParent(this);
463 mAddedTouchMode = (res&WindowManagerImpl.ADD_FLAG_IN_TOUCH_MODE) != 0;
464 mAppVisible = (res&WindowManagerImpl.ADD_FLAG_APP_VISIBLE) != 0;
465 }
466 }
467 }
468
Romain Guy529b60a2010-08-03 18:05:47 -0700469 private void enableHardwareAcceleration(WindowManager.LayoutParams attrs) {
Romain Guye4d01122010-06-16 18:44:05 -0700470 // Only enable hardware acceleration if we are not in the system process
471 // The window manager creates ViewRoots to display animated preview windows
472 // of launching apps and we don't want those to be hardware accelerated
Romain Guy52339202010-09-03 16:04:46 -0700473 if (!HardwareRenderer.sRendererDisabled) {
Romain Guye4d01122010-06-16 18:44:05 -0700474 // Try to enable hardware acceleration if requested
Romain Guy529b60a2010-08-03 18:05:47 -0700475 if (attrs != null &&
476 (attrs.flags & WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED) != 0) {
Romain Guye4d01122010-06-16 18:44:05 -0700477 final boolean translucent = attrs.format != PixelFormat.OPAQUE;
Romain Guyb051e892010-09-28 19:09:36 -0700478 if (mAttachInfo.mHardwareRenderer != null) {
479 mAttachInfo.mHardwareRenderer.destroy(true);
Romain Guy4caa4ed2010-08-25 14:46:24 -0700480 }
Romain Guyb051e892010-09-28 19:09:36 -0700481 mAttachInfo.mHardwareRenderer = HardwareRenderer.createGlRenderer(2, translucent);
Romain Guy53ca03d2010-10-08 18:55:27 -0700482 mAttachInfo.mHardwareAccelerated = mAttachInfo.mHardwareRenderer != null;
Romain Guye4d01122010-06-16 18:44:05 -0700483 }
484 }
485 }
486
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800487 public View getView() {
488 return mView;
489 }
490
491 final WindowLeaked getLocation() {
492 return mLocation;
493 }
494
495 void setLayoutParams(WindowManager.LayoutParams attrs, boolean newView) {
496 synchronized (this) {
The Android Open Source Project10592532009-03-18 17:39:46 -0700497 int oldSoftInputMode = mWindowAttributes.softInputMode;
Mitsuru Oshima5a2b91d2009-07-16 16:30:02 -0700498 // preserve compatible window flag if exists.
499 int compatibleWindowFlag =
500 mWindowAttributes.flags & WindowManager.LayoutParams.FLAG_COMPATIBLE_WINDOW;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800501 mWindowAttributes.copyFrom(attrs);
Mitsuru Oshima5a2b91d2009-07-16 16:30:02 -0700502 mWindowAttributes.flags |= compatibleWindowFlag;
503
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800504 if (newView) {
505 mSoftInputMode = attrs.softInputMode;
506 requestLayout();
507 }
The Android Open Source Project10592532009-03-18 17:39:46 -0700508 // Don't lose the mode we last auto-computed.
509 if ((attrs.softInputMode&WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST)
510 == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED) {
511 mWindowAttributes.softInputMode = (mWindowAttributes.softInputMode
512 & ~WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST)
513 | (oldSoftInputMode
514 & WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST);
515 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800516 mWindowAttributesChanged = true;
517 scheduleTraversals();
518 }
519 }
520
521 void handleAppVisibility(boolean visible) {
522 if (mAppVisible != visible) {
523 mAppVisible = visible;
524 scheduleTraversals();
525 }
526 }
527
528 void handleGetNewSurface() {
529 mNewSurfaceNeeded = true;
530 mFullRedrawNeeded = true;
531 scheduleTraversals();
532 }
533
534 /**
535 * {@inheritDoc}
536 */
537 public void requestLayout() {
538 checkThread();
539 mLayoutRequested = true;
540 scheduleTraversals();
541 }
542
543 /**
544 * {@inheritDoc}
545 */
546 public boolean isLayoutRequested() {
547 return mLayoutRequested;
548 }
549
550 public void invalidateChild(View child, Rect dirty) {
551 checkThread();
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700552 if (DEBUG_DRAW) Log.v(TAG, "Invalidate child: " + dirty);
Chet Haase70d4ba12010-10-06 09:46:45 -0700553 if (dirty == null) {
554 // Fast invalidation for GL-enabled applications; GL must redraw everything
555 invalidate();
556 return;
557 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700558 if (mCurScrollY != 0 || mTranslator != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800559 mTempRect.set(dirty);
Romain Guy1e095972009-07-07 11:22:45 -0700560 dirty = mTempRect;
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700561 if (mCurScrollY != 0) {
Romain Guy1e095972009-07-07 11:22:45 -0700562 dirty.offset(0, -mCurScrollY);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700563 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700564 if (mTranslator != null) {
Romain Guy1e095972009-07-07 11:22:45 -0700565 mTranslator.translateRectInAppWindowToScreen(dirty);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700566 }
Romain Guy1e095972009-07-07 11:22:45 -0700567 if (mAttachInfo.mScalingRequired) {
568 dirty.inset(-1, -1);
569 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800570 }
571 mDirty.union(dirty);
572 if (!mWillDrawSoon) {
573 scheduleTraversals();
574 }
575 }
Romain Guy0d9275e2010-10-26 14:22:30 -0700576
577 void invalidate() {
578 mDirty.set(0, 0, mWidth, mHeight);
579 scheduleTraversals();
580 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800581
582 public ViewParent getParent() {
583 return null;
584 }
585
586 public ViewParent invalidateChildInParent(final int[] location, final Rect dirty) {
587 invalidateChild(null, dirty);
588 return null;
589 }
590
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700591 public boolean getChildVisibleRect(View child, Rect r, android.graphics.Point offset) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800592 if (child != mView) {
593 throw new RuntimeException("child is not mine, honest!");
594 }
595 // Note: don't apply scroll offset, because we want to know its
596 // visibility in the virtual canvas being given to the view hierarchy.
597 return r.intersect(0, 0, mWidth, mHeight);
598 }
599
600 public void bringChildToFront(View child) {
601 }
602
603 public void scheduleTraversals() {
604 if (!mTraversalScheduled) {
605 mTraversalScheduled = true;
606 sendEmptyMessage(DO_TRAVERSAL);
607 }
608 }
609
610 public void unscheduleTraversals() {
611 if (mTraversalScheduled) {
612 mTraversalScheduled = false;
613 removeMessages(DO_TRAVERSAL);
614 }
615 }
616
617 int getHostVisibility() {
618 return mAppVisible ? mView.getVisibility() : View.GONE;
619 }
Romain Guy8506ab42009-06-11 17:35:47 -0700620
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800621 private void performTraversals() {
622 // cache mView since it is used so much below...
623 final View host = mView;
624
625 if (DBG) {
626 System.out.println("======================================");
627 System.out.println("performTraversals");
628 host.debug();
629 }
630
631 if (host == null || !mAdded)
632 return;
633
634 mTraversalScheduled = false;
635 mWillDrawSoon = true;
636 boolean windowResizesToFitContent = false;
637 boolean fullRedrawNeeded = mFullRedrawNeeded;
638 boolean newSurface = false;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700639 boolean surfaceChanged = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800640 WindowManager.LayoutParams lp = mWindowAttributes;
641
642 int desiredWindowWidth;
643 int desiredWindowHeight;
644 int childWidthMeasureSpec;
645 int childHeightMeasureSpec;
646
647 final View.AttachInfo attachInfo = mAttachInfo;
648
649 final int viewVisibility = getHostVisibility();
650 boolean viewVisibilityChanged = mViewVisibility != viewVisibility
651 || mNewSurfaceNeeded;
652
653 WindowManager.LayoutParams params = null;
654 if (mWindowAttributesChanged) {
655 mWindowAttributesChanged = false;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700656 surfaceChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800657 params = lp;
658 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700659 Rect frame = mWinFrame;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800660 if (mFirst) {
661 fullRedrawNeeded = true;
662 mLayoutRequested = true;
663
Romain Guy8506ab42009-06-11 17:35:47 -0700664 DisplayMetrics packageMetrics =
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700665 mView.getContext().getResources().getDisplayMetrics();
666 desiredWindowWidth = packageMetrics.widthPixels;
667 desiredWindowHeight = packageMetrics.heightPixels;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800668
669 // For the very first time, tell the view hierarchy that it
670 // is attached to the window. Note that at this point the surface
671 // object is not initialized to its backing store, but soon it
672 // will be (assuming the window is visible).
673 attachInfo.mSurface = mSurface;
Dianne Hackborn289b9b62010-07-09 11:44:11 -0700674 attachInfo.mTranslucentWindow = PixelFormat.formatHasAlpha(lp.format);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800675 attachInfo.mHasWindowFocus = false;
676 attachInfo.mWindowVisibility = viewVisibility;
677 attachInfo.mRecomputeGlobalAttributes = false;
678 attachInfo.mKeepScreenOn = false;
679 viewVisibilityChanged = false;
Dianne Hackborn694f79b2010-03-17 19:44:59 -0700680 mLastConfiguration.setTo(host.getResources().getConfiguration());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800681 host.dispatchAttachedToWindow(attachInfo, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800682 //Log.i(TAG, "Screen on initialized: " + attachInfo.mKeepScreenOn);
svetoslavganov75986cf2009-05-14 22:28:01 -0700683
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800684 } else {
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700685 desiredWindowWidth = frame.width();
686 desiredWindowHeight = frame.height();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800687 if (desiredWindowWidth != mWidth || desiredWindowHeight != mHeight) {
Jeff Brownc5ed5912010-07-14 18:48:53 -0700688 if (DEBUG_ORIENTATION) Log.v(TAG,
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700689 "View " + host + " resized to: " + frame);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800690 fullRedrawNeeded = true;
691 mLayoutRequested = true;
692 windowResizesToFitContent = true;
693 }
694 }
695
696 if (viewVisibilityChanged) {
697 attachInfo.mWindowVisibility = viewVisibility;
698 host.dispatchWindowVisibilityChanged(viewVisibility);
699 if (viewVisibility != View.VISIBLE || mNewSurfaceNeeded) {
Romain Guyb051e892010-09-28 19:09:36 -0700700 if (mAttachInfo.mHardwareRenderer != null) {
701 mAttachInfo.mHardwareRenderer.destroy(false);
Romain Guy4caa4ed2010-08-25 14:46:24 -0700702 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800703 }
704 if (viewVisibility == View.GONE) {
705 // After making a window gone, we will count it as being
706 // shown for the first time the next time it gets focus.
707 mHasHadWindowFocus = false;
708 }
709 }
710
711 boolean insetsChanged = false;
Romain Guy8506ab42009-06-11 17:35:47 -0700712
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800713 if (mLayoutRequested) {
Romain Guy15df6702009-08-17 20:17:30 -0700714 // Execute enqueued actions on every layout in case a view that was detached
715 // enqueued an action after being detached
716 getRunQueue().executeActions(attachInfo.mHandler);
717
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800718 if (mFirst) {
719 host.fitSystemWindows(mAttachInfo.mContentInsets);
720 // make sure touch mode code executes by setting cached value
721 // to opposite of the added touch mode.
722 mAttachInfo.mInTouchMode = !mAddedTouchMode;
Romain Guy2d4cff62010-04-09 15:39:00 -0700723 ensureTouchModeLocally(mAddedTouchMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800724 } else {
725 if (!mAttachInfo.mContentInsets.equals(mPendingContentInsets)) {
726 mAttachInfo.mContentInsets.set(mPendingContentInsets);
727 host.fitSystemWindows(mAttachInfo.mContentInsets);
728 insetsChanged = true;
729 if (DEBUG_LAYOUT) Log.v(TAG, "Content insets changing to: "
730 + mAttachInfo.mContentInsets);
731 }
732 if (!mAttachInfo.mVisibleInsets.equals(mPendingVisibleInsets)) {
733 mAttachInfo.mVisibleInsets.set(mPendingVisibleInsets);
734 if (DEBUG_LAYOUT) Log.v(TAG, "Visible insets changing to: "
735 + mAttachInfo.mVisibleInsets);
736 }
737 if (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT
738 || lp.height == ViewGroup.LayoutParams.WRAP_CONTENT) {
739 windowResizesToFitContent = true;
740
Romain Guy8506ab42009-06-11 17:35:47 -0700741 DisplayMetrics packageMetrics =
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700742 mView.getContext().getResources().getDisplayMetrics();
743 desiredWindowWidth = packageMetrics.widthPixels;
744 desiredWindowHeight = packageMetrics.heightPixels;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800745 }
746 }
747
748 childWidthMeasureSpec = getRootMeasureSpec(desiredWindowWidth, lp.width);
749 childHeightMeasureSpec = getRootMeasureSpec(desiredWindowHeight, lp.height);
750
751 // Ask host how big it wants to be
Jeff Brownc5ed5912010-07-14 18:48:53 -0700752 if (DEBUG_ORIENTATION || DEBUG_LAYOUT) Log.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800753 "Measuring " + host + " in display " + desiredWindowWidth
754 + "x" + desiredWindowHeight + "...");
755 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
756
757 if (DBG) {
758 System.out.println("======================================");
759 System.out.println("performTraversals -- after measure");
760 host.debug();
761 }
762 }
763
764 if (attachInfo.mRecomputeGlobalAttributes) {
765 //Log.i(TAG, "Computing screen on!");
766 attachInfo.mRecomputeGlobalAttributes = false;
767 boolean oldVal = attachInfo.mKeepScreenOn;
768 attachInfo.mKeepScreenOn = false;
769 host.dispatchCollectViewAttributes(0);
770 if (attachInfo.mKeepScreenOn != oldVal) {
771 params = lp;
772 //Log.i(TAG, "Keep screen on changed: " + attachInfo.mKeepScreenOn);
773 }
774 }
775
776 if (mFirst || attachInfo.mViewVisibilityChanged) {
777 attachInfo.mViewVisibilityChanged = false;
778 int resizeMode = mSoftInputMode &
779 WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST;
780 // If we are in auto resize mode, then we need to determine
781 // what mode to use now.
782 if (resizeMode == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED) {
783 final int N = attachInfo.mScrollContainers.size();
784 for (int i=0; i<N; i++) {
785 if (attachInfo.mScrollContainers.get(i).isShown()) {
786 resizeMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE;
787 }
788 }
789 if (resizeMode == 0) {
790 resizeMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN;
791 }
792 if ((lp.softInputMode &
793 WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) != resizeMode) {
794 lp.softInputMode = (lp.softInputMode &
795 ~WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) |
796 resizeMode;
797 params = lp;
798 }
799 }
800 }
Romain Guy8506ab42009-06-11 17:35:47 -0700801
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800802 if (params != null && (host.mPrivateFlags & View.REQUEST_TRANSPARENT_REGIONS) != 0) {
803 if (!PixelFormat.formatHasAlpha(params.format)) {
804 params.format = PixelFormat.TRANSLUCENT;
805 }
806 }
807
808 boolean windowShouldResize = mLayoutRequested && windowResizesToFitContent
Romain Guy2e4f4262010-04-06 11:07:52 -0700809 && ((mWidth != host.mMeasuredWidth || mHeight != host.mMeasuredHeight)
810 || (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT &&
811 frame.width() < desiredWindowWidth && frame.width() != mWidth)
812 || (lp.height == ViewGroup.LayoutParams.WRAP_CONTENT &&
813 frame.height() < desiredWindowHeight && frame.height() != mHeight));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800814
815 final boolean computesInternalInsets =
816 attachInfo.mTreeObserver.hasComputeInternalInsetsListeners();
Romain Guy812ccbe2010-06-01 14:07:24 -0700817
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800818 boolean insetsPending = false;
819 int relayoutResult = 0;
Romain Guy812ccbe2010-06-01 14:07:24 -0700820
821 if (mFirst || windowShouldResize || insetsChanged ||
822 viewVisibilityChanged || params != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800823
824 if (viewVisibility == View.VISIBLE) {
825 // If this window is giving internal insets to the window
826 // manager, and it is being added or changing its visibility,
827 // then we want to first give the window manager "fake"
828 // insets to cause it to effectively ignore the content of
829 // the window during layout. This avoids it briefly causing
830 // other windows to resize/move based on the raw frame of the
831 // window, waiting until we can finish laying out this window
832 // and get back to the window manager with the ultimately
833 // computed insets.
Romain Guy812ccbe2010-06-01 14:07:24 -0700834 insetsPending = computesInternalInsets && (mFirst || viewVisibilityChanged);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800835 }
836
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700837 if (mSurfaceHolder != null) {
838 mSurfaceHolder.mSurfaceLock.lock();
839 mDrawingAllowed = true;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700840 }
Romain Guy812ccbe2010-06-01 14:07:24 -0700841
Romain Guyc361da82010-10-25 15:29:10 -0700842 boolean hwInitialized = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800843 boolean contentInsetsChanged = false;
Romain Guy13922e02009-05-12 17:56:14 -0700844 boolean visibleInsetsChanged;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700845 boolean hadSurface = mSurface.isValid();
Romain Guy812ccbe2010-06-01 14:07:24 -0700846
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800847 try {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800848 int fl = 0;
849 if (params != null) {
850 fl = params.flags;
851 if (attachInfo.mKeepScreenOn) {
852 params.flags |= WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
853 }
854 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700855 if (DEBUG_LAYOUT) {
856 Log.i(TAG, "host=w:" + host.mMeasuredWidth + ", h:" +
857 host.mMeasuredHeight + ", params=" + params);
858 }
859 relayoutResult = relayoutWindow(params, viewVisibility, insetsPending);
860
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800861 if (params != null) {
862 params.flags = fl;
863 }
864
865 if (DEBUG_LAYOUT) Log.v(TAG, "relayout: frame=" + frame.toShortString()
866 + " content=" + mPendingContentInsets.toShortString()
867 + " visible=" + mPendingVisibleInsets.toShortString()
868 + " surface=" + mSurface);
Romain Guy8506ab42009-06-11 17:35:47 -0700869
Dianne Hackborn694f79b2010-03-17 19:44:59 -0700870 if (mPendingConfiguration.seq != 0) {
871 if (DEBUG_CONFIGURATION) Log.v(TAG, "Visible with new config: "
872 + mPendingConfiguration);
873 updateConfiguration(mPendingConfiguration, !mFirst);
874 mPendingConfiguration.seq = 0;
875 }
876
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800877 contentInsetsChanged = !mPendingContentInsets.equals(
878 mAttachInfo.mContentInsets);
879 visibleInsetsChanged = !mPendingVisibleInsets.equals(
880 mAttachInfo.mVisibleInsets);
881 if (contentInsetsChanged) {
882 mAttachInfo.mContentInsets.set(mPendingContentInsets);
883 host.fitSystemWindows(mAttachInfo.mContentInsets);
884 if (DEBUG_LAYOUT) Log.v(TAG, "Content insets changing to: "
885 + mAttachInfo.mContentInsets);
886 }
887 if (visibleInsetsChanged) {
888 mAttachInfo.mVisibleInsets.set(mPendingVisibleInsets);
889 if (DEBUG_LAYOUT) Log.v(TAG, "Visible insets changing to: "
890 + mAttachInfo.mVisibleInsets);
891 }
892
893 if (!hadSurface) {
894 if (mSurface.isValid()) {
895 // If we are creating a new surface, then we need to
896 // completely redraw it. Also, when we get to the
897 // point of drawing it we will hold off and schedule
898 // a new traversal instead. This is so we can tell the
899 // window manager about all of the windows being displayed
900 // before actually drawing them, so it can display then
901 // all at once.
902 newSurface = true;
903 fullRedrawNeeded = true;
Jack Palevich61a6e682009-10-09 17:37:50 -0700904 mPreviousTransparentRegion.setEmpty();
Romain Guy8506ab42009-06-11 17:35:47 -0700905
Romain Guyb051e892010-09-28 19:09:36 -0700906 if (mAttachInfo.mHardwareRenderer != null) {
Romain Guyc361da82010-10-25 15:29:10 -0700907 hwInitialized = mAttachInfo.mHardwareRenderer.initialize(mHolder);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800908 }
909 }
910 } else if (!mSurface.isValid()) {
911 // If the surface has been removed, then reset the scroll
912 // positions.
913 mLastScrolledFocus = null;
914 mScrollY = mCurScrollY = 0;
915 if (mScroller != null) {
916 mScroller.abortAnimation();
917 }
918 }
919 } catch (RemoteException e) {
920 }
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700921
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800922 if (DEBUG_ORIENTATION) Log.v(
Jeff Brownc5ed5912010-07-14 18:48:53 -0700923 TAG, "Relayout returned: frame=" + frame + ", surface=" + mSurface);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800924
925 attachInfo.mWindowLeft = frame.left;
926 attachInfo.mWindowTop = frame.top;
927
928 // !!FIXME!! This next section handles the case where we did not get the
929 // window size we asked for. We should avoid this by getting a maximum size from
930 // the window session beforehand.
931 mWidth = frame.width();
932 mHeight = frame.height();
933
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700934 if (mSurfaceHolder != null) {
935 // The app owns the surface; tell it about what is going on.
936 if (mSurface.isValid()) {
937 // XXX .copyFrom() doesn't work!
938 //mSurfaceHolder.mSurface.copyFrom(mSurface);
939 mSurfaceHolder.mSurface = mSurface;
940 }
941 mSurfaceHolder.mSurfaceLock.unlock();
942 if (mSurface.isValid()) {
943 if (!hadSurface) {
944 mSurfaceHolder.ungetCallbacks();
945
946 mIsCreating = true;
947 mSurfaceHolderCallback.surfaceCreated(mSurfaceHolder);
948 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
949 if (callbacks != null) {
950 for (SurfaceHolder.Callback c : callbacks) {
951 c.surfaceCreated(mSurfaceHolder);
952 }
953 }
954 surfaceChanged = true;
Romain Guyc361da82010-10-25 15:29:10 -0700955
956 if (mAttachInfo.mHardwareRenderer != null) {
957 // This will bail out early if already initialized
958 mAttachInfo.mHardwareRenderer.initialize(mHolder);
959 }
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700960 }
961 if (surfaceChanged) {
962 mSurfaceHolderCallback.surfaceChanged(mSurfaceHolder,
963 lp.format, mWidth, mHeight);
964 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
965 if (callbacks != null) {
966 for (SurfaceHolder.Callback c : callbacks) {
967 c.surfaceChanged(mSurfaceHolder, lp.format,
968 mWidth, mHeight);
969 }
970 }
971 }
972 mIsCreating = false;
973 } else if (hadSurface) {
974 mSurfaceHolder.ungetCallbacks();
975 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
976 mSurfaceHolderCallback.surfaceDestroyed(mSurfaceHolder);
977 if (callbacks != null) {
978 for (SurfaceHolder.Callback c : callbacks) {
979 c.surfaceDestroyed(mSurfaceHolder);
980 }
981 }
982 mSurfaceHolder.mSurfaceLock.lock();
983 // Make surface invalid.
984 //mSurfaceHolder.mSurface.copyFrom(mSurface);
985 mSurfaceHolder.mSurface = new Surface();
986 mSurfaceHolder.mSurfaceLock.unlock();
987 }
988 }
Romain Guy53389bd2010-09-07 17:16:32 -0700989
Romain Guyc361da82010-10-25 15:29:10 -0700990 if (hwInitialized || (windowShouldResize && mAttachInfo.mHardwareRenderer != null)) {
Romain Guyb051e892010-09-28 19:09:36 -0700991 mAttachInfo.mHardwareRenderer.setup(mWidth, mHeight);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800992 }
993
994 boolean focusChangedDueToTouchMode = ensureTouchModeLocally(
Romain Guy2d4cff62010-04-09 15:39:00 -0700995 (relayoutResult&WindowManagerImpl.RELAYOUT_IN_TOUCH_MODE) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800996 if (focusChangedDueToTouchMode || mWidth != host.mMeasuredWidth
997 || mHeight != host.mMeasuredHeight || contentInsetsChanged) {
998 childWidthMeasureSpec = getRootMeasureSpec(mWidth, lp.width);
999 childHeightMeasureSpec = getRootMeasureSpec(mHeight, lp.height);
1000
1001 if (DEBUG_LAYOUT) Log.v(TAG, "Ooops, something changed! mWidth="
1002 + mWidth + " measuredWidth=" + host.mMeasuredWidth
1003 + " mHeight=" + mHeight
1004 + " measuredHeight" + host.mMeasuredHeight
1005 + " coveredInsetsChanged=" + contentInsetsChanged);
Romain Guy8506ab42009-06-11 17:35:47 -07001006
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001007 // Ask host how big it wants to be
1008 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
1009
1010 // Implementation of weights from WindowManager.LayoutParams
1011 // We just grow the dimensions as needed and re-measure if
1012 // needs be
1013 int width = host.mMeasuredWidth;
1014 int height = host.mMeasuredHeight;
1015 boolean measureAgain = false;
1016
1017 if (lp.horizontalWeight > 0.0f) {
1018 width += (int) ((mWidth - width) * lp.horizontalWeight);
1019 childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(width,
1020 MeasureSpec.EXACTLY);
1021 measureAgain = true;
1022 }
1023 if (lp.verticalWeight > 0.0f) {
1024 height += (int) ((mHeight - height) * lp.verticalWeight);
1025 childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(height,
1026 MeasureSpec.EXACTLY);
1027 measureAgain = true;
1028 }
1029
1030 if (measureAgain) {
1031 if (DEBUG_LAYOUT) Log.v(TAG,
1032 "And hey let's measure once more: width=" + width
1033 + " height=" + height);
1034 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
1035 }
1036
1037 mLayoutRequested = true;
1038 }
1039 }
1040
1041 final boolean didLayout = mLayoutRequested;
1042 boolean triggerGlobalLayoutListener = didLayout
1043 || attachInfo.mRecomputeGlobalAttributes;
1044 if (didLayout) {
1045 mLayoutRequested = false;
1046 mScrollMayChange = true;
1047 if (DEBUG_ORIENTATION || DEBUG_LAYOUT) Log.v(
Jeff Brownc5ed5912010-07-14 18:48:53 -07001048 TAG, "Laying out " + host + " to (" +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001049 host.mMeasuredWidth + ", " + host.mMeasuredHeight + ")");
Romain Guy13922e02009-05-12 17:56:14 -07001050 long startTime = 0L;
Romain Guy5429e1d2010-09-07 12:38:00 -07001051 if (ViewDebug.DEBUG_PROFILE_LAYOUT) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001052 startTime = SystemClock.elapsedRealtime();
1053 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001054 host.layout(0, 0, host.mMeasuredWidth, host.mMeasuredHeight);
1055
Romain Guy13922e02009-05-12 17:56:14 -07001056 if (Config.DEBUG && ViewDebug.consistencyCheckEnabled) {
1057 if (!host.dispatchConsistencyCheck(ViewDebug.CONSISTENCY_LAYOUT)) {
1058 throw new IllegalStateException("The view hierarchy is an inconsistent state,"
1059 + "please refer to the logs with the tag "
1060 + ViewDebug.CONSISTENCY_LOG_TAG + " for more infomation.");
1061 }
1062 }
1063
Romain Guy5429e1d2010-09-07 12:38:00 -07001064 if (ViewDebug.DEBUG_PROFILE_LAYOUT) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001065 EventLog.writeEvent(60001, SystemClock.elapsedRealtime() - startTime);
1066 }
1067
1068 // By this point all views have been sized and positionned
1069 // We can compute the transparent area
1070
1071 if ((host.mPrivateFlags & View.REQUEST_TRANSPARENT_REGIONS) != 0) {
1072 // start out transparent
1073 // TODO: AVOID THAT CALL BY CACHING THE RESULT?
1074 host.getLocationInWindow(mTmpLocation);
1075 mTransparentRegion.set(mTmpLocation[0], mTmpLocation[1],
1076 mTmpLocation[0] + host.mRight - host.mLeft,
1077 mTmpLocation[1] + host.mBottom - host.mTop);
1078
1079 host.gatherTransparentRegion(mTransparentRegion);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001080 if (mTranslator != null) {
1081 mTranslator.translateRegionInWindowToScreen(mTransparentRegion);
1082 }
1083
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001084 if (!mTransparentRegion.equals(mPreviousTransparentRegion)) {
1085 mPreviousTransparentRegion.set(mTransparentRegion);
1086 // reconfigure window manager
1087 try {
1088 sWindowSession.setTransparentRegion(mWindow, mTransparentRegion);
1089 } catch (RemoteException e) {
1090 }
1091 }
1092 }
1093
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001094 if (DBG) {
1095 System.out.println("======================================");
1096 System.out.println("performTraversals -- after setFrame");
1097 host.debug();
1098 }
1099 }
1100
1101 if (triggerGlobalLayoutListener) {
1102 attachInfo.mRecomputeGlobalAttributes = false;
1103 attachInfo.mTreeObserver.dispatchOnGlobalLayout();
1104 }
1105
1106 if (computesInternalInsets) {
1107 ViewTreeObserver.InternalInsetsInfo insets = attachInfo.mGivenInternalInsets;
1108 final Rect givenContent = attachInfo.mGivenInternalInsets.contentInsets;
1109 final Rect givenVisible = attachInfo.mGivenInternalInsets.visibleInsets;
1110 givenContent.left = givenContent.top = givenContent.right
1111 = givenContent.bottom = givenVisible.left = givenVisible.top
1112 = givenVisible.right = givenVisible.bottom = 0;
1113 attachInfo.mTreeObserver.dispatchOnComputeInternalInsets(insets);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001114 Rect contentInsets = insets.contentInsets;
1115 Rect visibleInsets = insets.visibleInsets;
1116 if (mTranslator != null) {
1117 contentInsets = mTranslator.getTranslatedContentInsets(contentInsets);
1118 visibleInsets = mTranslator.getTranslatedVisbileInsets(visibleInsets);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001119 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001120 if (insetsPending || !mLastGivenInsets.equals(insets)) {
1121 mLastGivenInsets.set(insets);
1122 try {
1123 sWindowSession.setInsets(mWindow, insets.mTouchableInsets,
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001124 contentInsets, visibleInsets);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001125 } catch (RemoteException e) {
1126 }
1127 }
1128 }
Romain Guy8506ab42009-06-11 17:35:47 -07001129
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001130 if (mFirst) {
1131 // handle first focus request
1132 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: mView.hasFocus()="
1133 + mView.hasFocus());
1134 if (mView != null) {
1135 if (!mView.hasFocus()) {
1136 mView.requestFocus(View.FOCUS_FORWARD);
1137 mFocusedView = mRealFocusedView = mView.findFocus();
1138 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: requested focused view="
1139 + mFocusedView);
1140 } else {
1141 mRealFocusedView = mView.findFocus();
1142 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: existing focused view="
1143 + mRealFocusedView);
1144 }
1145 }
1146 }
1147
1148 mFirst = false;
1149 mWillDrawSoon = false;
1150 mNewSurfaceNeeded = false;
1151 mViewVisibility = viewVisibility;
1152
1153 if (mAttachInfo.mHasWindowFocus) {
1154 final boolean imTarget = WindowManager.LayoutParams
1155 .mayUseInputMethod(mWindowAttributes.flags);
1156 if (imTarget != mLastWasImTarget) {
1157 mLastWasImTarget = imTarget;
1158 InputMethodManager imm = InputMethodManager.peekInstance();
1159 if (imm != null && imTarget) {
1160 imm.startGettingWindowFocus(mView);
1161 imm.onWindowFocus(mView, mView.findFocus(),
1162 mWindowAttributes.softInputMode,
1163 !mHasHadWindowFocus, mWindowAttributes.flags);
1164 }
1165 }
1166 }
Romain Guy8506ab42009-06-11 17:35:47 -07001167
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001168 boolean cancelDraw = attachInfo.mTreeObserver.dispatchOnPreDraw();
1169
1170 if (!cancelDraw && !newSurface) {
1171 mFullRedrawNeeded = false;
1172 draw(fullRedrawNeeded);
1173
1174 if ((relayoutResult&WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0
1175 || mReportNextDraw) {
1176 if (LOCAL_LOGV) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001177 Log.v(TAG, "FINISHED DRAWING: " + mWindowAttributes.getTitle());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001178 }
1179 mReportNextDraw = false;
Dianne Hackbornd76b67c2010-07-13 17:48:30 -07001180 if (mSurfaceHolder != null && mSurface.isValid()) {
1181 mSurfaceHolderCallback.surfaceRedrawNeeded(mSurfaceHolder);
1182 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
1183 if (callbacks != null) {
1184 for (SurfaceHolder.Callback c : callbacks) {
1185 if (c instanceof SurfaceHolder.Callback2) {
1186 ((SurfaceHolder.Callback2)c).surfaceRedrawNeeded(
1187 mSurfaceHolder);
1188 }
1189 }
1190 }
1191 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001192 try {
1193 sWindowSession.finishDrawing(mWindow);
1194 } catch (RemoteException e) {
1195 }
1196 }
1197 } else {
1198 // We were supposed to report when we are done drawing. Since we canceled the
1199 // draw, remember it here.
1200 if ((relayoutResult&WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0) {
1201 mReportNextDraw = true;
1202 }
1203 if (fullRedrawNeeded) {
1204 mFullRedrawNeeded = true;
1205 }
1206 // Try again
1207 scheduleTraversals();
1208 }
1209 }
1210
1211 public void requestTransparentRegion(View child) {
1212 // the test below should not fail unless someone is messing with us
1213 checkThread();
1214 if (mView == child) {
1215 mView.mPrivateFlags |= View.REQUEST_TRANSPARENT_REGIONS;
1216 // Need to make sure we re-evaluate the window attributes next
1217 // time around, to ensure the window has the correct format.
1218 mWindowAttributesChanged = true;
1219 }
1220 }
1221
1222 /**
1223 * Figures out the measure spec for the root view in a window based on it's
1224 * layout params.
1225 *
1226 * @param windowSize
1227 * The available width or height of the window
1228 *
1229 * @param rootDimension
1230 * The layout params for one dimension (width or height) of the
1231 * window.
1232 *
1233 * @return The measure spec to use to measure the root view.
1234 */
1235 private int getRootMeasureSpec(int windowSize, int rootDimension) {
1236 int measureSpec;
1237 switch (rootDimension) {
1238
Romain Guy980a9382010-01-08 15:06:28 -08001239 case ViewGroup.LayoutParams.MATCH_PARENT:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001240 // Window can't resize. Force root view to be windowSize.
1241 measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.EXACTLY);
1242 break;
1243 case ViewGroup.LayoutParams.WRAP_CONTENT:
1244 // Window can resize. Set max size for root view.
1245 measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.AT_MOST);
1246 break;
1247 default:
1248 // Window wants to be an exact size. Force root view to be that size.
1249 measureSpec = MeasureSpec.makeMeasureSpec(rootDimension, MeasureSpec.EXACTLY);
1250 break;
1251 }
1252 return measureSpec;
1253 }
1254
1255 private void draw(boolean fullRedrawNeeded) {
1256 Surface surface = mSurface;
1257 if (surface == null || !surface.isValid()) {
1258 return;
1259 }
1260
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001261 if (!sFirstDrawComplete) {
1262 synchronized (sFirstDrawHandlers) {
1263 sFirstDrawComplete = true;
Romain Guy812ccbe2010-06-01 14:07:24 -07001264 final int count = sFirstDrawHandlers.size();
1265 for (int i = 0; i< count; i++) {
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001266 post(sFirstDrawHandlers.get(i));
1267 }
1268 }
1269 }
1270
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001271 scrollToRectOrFocus(null, false);
1272
1273 if (mAttachInfo.mViewScrollChanged) {
1274 mAttachInfo.mViewScrollChanged = false;
1275 mAttachInfo.mTreeObserver.dispatchOnScrollChanged();
1276 }
Romain Guy8506ab42009-06-11 17:35:47 -07001277
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001278 int yoff;
Romain Guy5bcdff42009-05-14 21:27:18 -07001279 final boolean scrolling = mScroller != null && mScroller.computeScrollOffset();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001280 if (scrolling) {
1281 yoff = mScroller.getCurrY();
1282 } else {
1283 yoff = mScrollY;
1284 }
1285 if (mCurScrollY != yoff) {
1286 mCurScrollY = yoff;
1287 fullRedrawNeeded = true;
1288 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001289 float appScale = mAttachInfo.mApplicationScale;
1290 boolean scalingRequired = mAttachInfo.mScalingRequired;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001291
1292 Rect dirty = mDirty;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001293 if (mSurfaceHolder != null) {
1294 // The app owns the surface, we won't draw.
1295 dirty.setEmpty();
1296 return;
1297 }
Romain Guy58ef7fb2010-09-13 12:52:37 -07001298
1299 if (fullRedrawNeeded) {
1300 mAttachInfo.mIgnoreDirtyState = true;
1301 dirty.union(0, 0, (int) (mWidth * appScale + 0.5f), (int) (mHeight * appScale + 0.5f));
1302 }
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001303
Romain Guyb051e892010-09-28 19:09:36 -07001304 if (mAttachInfo.mHardwareRenderer != null && mAttachInfo.mHardwareRenderer.isEnabled()) {
Romain Guyfd507262010-10-10 15:42:49 -07001305 if (!dirty.isEmpty() || mIsAnimating) {
Romain Guy101e2ae2010-10-11 12:41:21 -07001306 mIsAnimating = false;
Romain Guyfd507262010-10-10 15:42:49 -07001307 dirty.setEmpty();
Romain Guy101e2ae2010-10-11 12:41:21 -07001308 mAttachInfo.mHardwareRenderer.draw(mView, mAttachInfo, yoff);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001309 }
Romain Guy812ccbe2010-06-01 14:07:24 -07001310
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001311 if (scrolling) {
1312 mFullRedrawNeeded = true;
1313 scheduleTraversals();
1314 }
Romain Guy812ccbe2010-06-01 14:07:24 -07001315
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001316 return;
1317 }
1318
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001319 if (DEBUG_ORIENTATION || DEBUG_DRAW) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001320 Log.v(TAG, "Draw " + mView + "/"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001321 + mWindowAttributes.getTitle()
1322 + ": dirty={" + dirty.left + "," + dirty.top
1323 + "," + dirty.right + "," + dirty.bottom + "} surface="
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001324 + surface + " surface.isValid()=" + surface.isValid() + ", appScale:" +
1325 appScale + ", width=" + mWidth + ", height=" + mHeight);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001326 }
1327
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001328 if (!dirty.isEmpty() || mIsAnimating) {
1329 Canvas canvas;
1330 try {
1331 int left = dirty.left;
1332 int top = dirty.top;
1333 int right = dirty.right;
1334 int bottom = dirty.bottom;
1335 canvas = surface.lockCanvas(dirty);
Romain Guy5bcdff42009-05-14 21:27:18 -07001336
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001337 if (left != dirty.left || top != dirty.top || right != dirty.right ||
1338 bottom != dirty.bottom) {
1339 mAttachInfo.mIgnoreDirtyState = true;
1340 }
1341
1342 // TODO: Do this in native
1343 canvas.setDensity(mDensity);
1344 } catch (Surface.OutOfResourcesException e) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001345 Log.e(TAG, "OutOfResourcesException locking surface", e);
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001346 // TODO: we should ask the window manager to do something!
1347 // for now we just do nothing
1348 return;
1349 } catch (IllegalArgumentException e) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001350 Log.e(TAG, "IllegalArgumentException locking surface", e);
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001351 // TODO: we should ask the window manager to do something!
1352 // for now we just do nothing
1353 return;
Romain Guy5bcdff42009-05-14 21:27:18 -07001354 }
1355
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001356 try {
1357 if (!dirty.isEmpty() || mIsAnimating) {
1358 long startTime = 0L;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001359
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001360 if (DEBUG_ORIENTATION || DEBUG_DRAW) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001361 Log.v(TAG, "Surface " + surface + " drawing to bitmap w="
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001362 + canvas.getWidth() + ", h=" + canvas.getHeight());
1363 //canvas.drawARGB(255, 255, 0, 0);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001364 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001365
Romain Guy5429e1d2010-09-07 12:38:00 -07001366 if (ViewDebug.DEBUG_PROFILE_DRAWING) {
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001367 startTime = SystemClock.elapsedRealtime();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001368 }
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001369
1370 // If this bitmap's format includes an alpha channel, we
1371 // need to clear it before drawing so that the child will
1372 // properly re-composite its drawing on a transparent
1373 // background. This automatically respects the clip/dirty region
1374 // or
1375 // If we are applying an offset, we need to clear the area
1376 // where the offset doesn't appear to avoid having garbage
1377 // left in the blank areas.
1378 if (!canvas.isOpaque() || yoff != 0) {
1379 canvas.drawColor(0, PorterDuff.Mode.CLEAR);
1380 }
1381
1382 dirty.setEmpty();
1383 mIsAnimating = false;
1384 mAttachInfo.mDrawingTime = SystemClock.uptimeMillis();
1385 mView.mPrivateFlags |= View.DRAWN;
1386
1387 if (DEBUG_DRAW) {
1388 Context cxt = mView.getContext();
1389 Log.i(TAG, "Drawing: package:" + cxt.getPackageName() +
1390 ", metrics=" + cxt.getResources().getDisplayMetrics() +
1391 ", compatibilityInfo=" + cxt.getResources().getCompatibilityInfo());
1392 }
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001393 try {
1394 canvas.translate(0, -yoff);
1395 if (mTranslator != null) {
1396 mTranslator.translateCanvas(canvas);
1397 }
1398 canvas.setScreenDensity(scalingRequired
1399 ? DisplayMetrics.DENSITY_DEVICE : 0);
1400 mView.draw(canvas);
1401 } finally {
1402 mAttachInfo.mIgnoreDirtyState = false;
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001403 }
1404
1405 if (Config.DEBUG && ViewDebug.consistencyCheckEnabled) {
1406 mView.dispatchConsistencyCheck(ViewDebug.CONSISTENCY_DRAWING);
1407 }
1408
Romain Guy5429e1d2010-09-07 12:38:00 -07001409 if (SHOW_FPS || ViewDebug.DEBUG_SHOW_FPS) {
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001410 int now = (int)SystemClock.elapsedRealtime();
1411 if (sDrawTime != 0) {
1412 nativeShowFPS(canvas, now - sDrawTime);
1413 }
1414 sDrawTime = now;
1415 }
1416
Romain Guy5429e1d2010-09-07 12:38:00 -07001417 if (ViewDebug.DEBUG_PROFILE_DRAWING) {
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001418 EventLog.writeEvent(60000, SystemClock.elapsedRealtime() - startTime);
1419 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001420 }
1421
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001422 } finally {
1423 surface.unlockCanvasAndPost(canvas);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001424 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001425 }
1426
1427 if (LOCAL_LOGV) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001428 Log.v(TAG, "Surface " + surface + " unlockCanvasAndPost");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001429 }
Romain Guy8506ab42009-06-11 17:35:47 -07001430
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001431 if (scrolling) {
1432 mFullRedrawNeeded = true;
1433 scheduleTraversals();
1434 }
1435 }
1436
1437 boolean scrollToRectOrFocus(Rect rectangle, boolean immediate) {
1438 final View.AttachInfo attachInfo = mAttachInfo;
1439 final Rect ci = attachInfo.mContentInsets;
1440 final Rect vi = attachInfo.mVisibleInsets;
1441 int scrollY = 0;
1442 boolean handled = false;
Romain Guy8506ab42009-06-11 17:35:47 -07001443
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001444 if (vi.left > ci.left || vi.top > ci.top
1445 || vi.right > ci.right || vi.bottom > ci.bottom) {
1446 // We'll assume that we aren't going to change the scroll
1447 // offset, since we want to avoid that unless it is actually
1448 // going to make the focus visible... otherwise we scroll
1449 // all over the place.
1450 scrollY = mScrollY;
1451 // We can be called for two different situations: during a draw,
1452 // to update the scroll position if the focus has changed (in which
1453 // case 'rectangle' is null), or in response to a
1454 // requestChildRectangleOnScreen() call (in which case 'rectangle'
1455 // is non-null and we just want to scroll to whatever that
1456 // rectangle is).
1457 View focus = mRealFocusedView;
Romain Guye8b16522009-07-14 13:06:42 -07001458
1459 // When in touch mode, focus points to the previously focused view,
1460 // which may have been removed from the view hierarchy. The following
Joe Onoratob71193b2009-11-24 18:34:42 -05001461 // line checks whether the view is still in our hierarchy.
1462 if (focus == null || focus.mAttachInfo != mAttachInfo) {
Romain Guye8b16522009-07-14 13:06:42 -07001463 mRealFocusedView = null;
1464 return false;
1465 }
1466
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001467 if (focus != mLastScrolledFocus) {
1468 // If the focus has changed, then ignore any requests to scroll
1469 // to a rectangle; first we want to make sure the entire focus
1470 // view is visible.
1471 rectangle = null;
1472 }
1473 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Eval scroll: focus=" + focus
1474 + " rectangle=" + rectangle + " ci=" + ci
1475 + " vi=" + vi);
1476 if (focus == mLastScrolledFocus && !mScrollMayChange
1477 && rectangle == null) {
1478 // Optimization: if the focus hasn't changed since last
1479 // time, and no layout has happened, then just leave things
1480 // as they are.
1481 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Keeping scroll y="
1482 + mScrollY + " vi=" + vi.toShortString());
1483 } else if (focus != null) {
1484 // We need to determine if the currently focused view is
1485 // within the visible part of the window and, if not, apply
1486 // a pan so it can be seen.
1487 mLastScrolledFocus = focus;
1488 mScrollMayChange = false;
1489 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Need to scroll?");
1490 // Try to find the rectangle from the focus view.
1491 if (focus.getGlobalVisibleRect(mVisRect, null)) {
1492 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Root w="
1493 + mView.getWidth() + " h=" + mView.getHeight()
1494 + " ci=" + ci.toShortString()
1495 + " vi=" + vi.toShortString());
1496 if (rectangle == null) {
1497 focus.getFocusedRect(mTempRect);
1498 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Focus " + focus
1499 + ": focusRect=" + mTempRect.toShortString());
Dianne Hackborn1c6a8942010-03-23 16:34:20 -07001500 if (mView instanceof ViewGroup) {
1501 ((ViewGroup) mView).offsetDescendantRectToMyCoords(
1502 focus, mTempRect);
1503 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001504 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1505 "Focus in window: focusRect="
1506 + mTempRect.toShortString()
1507 + " visRect=" + mVisRect.toShortString());
1508 } else {
1509 mTempRect.set(rectangle);
1510 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1511 "Request scroll to rect: "
1512 + mTempRect.toShortString()
1513 + " visRect=" + mVisRect.toShortString());
1514 }
1515 if (mTempRect.intersect(mVisRect)) {
1516 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1517 "Focus window visible rect: "
1518 + mTempRect.toShortString());
1519 if (mTempRect.height() >
1520 (mView.getHeight()-vi.top-vi.bottom)) {
1521 // If the focus simply is not going to fit, then
1522 // best is probably just to leave things as-is.
1523 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1524 "Too tall; leaving scrollY=" + scrollY);
1525 } else if ((mTempRect.top-scrollY) < vi.top) {
1526 scrollY -= vi.top - (mTempRect.top-scrollY);
1527 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1528 "Top covered; scrollY=" + scrollY);
1529 } else if ((mTempRect.bottom-scrollY)
1530 > (mView.getHeight()-vi.bottom)) {
1531 scrollY += (mTempRect.bottom-scrollY)
1532 - (mView.getHeight()-vi.bottom);
1533 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1534 "Bottom covered; scrollY=" + scrollY);
1535 }
1536 handled = true;
1537 }
1538 }
1539 }
1540 }
Romain Guy8506ab42009-06-11 17:35:47 -07001541
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001542 if (scrollY != mScrollY) {
1543 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Pan scroll changed: old="
1544 + mScrollY + " , new=" + scrollY);
1545 if (!immediate) {
1546 if (mScroller == null) {
1547 mScroller = new Scroller(mView.getContext());
1548 }
1549 mScroller.startScroll(0, mScrollY, 0, scrollY-mScrollY);
1550 } else if (mScroller != null) {
1551 mScroller.abortAnimation();
1552 }
1553 mScrollY = scrollY;
1554 }
Romain Guy8506ab42009-06-11 17:35:47 -07001555
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001556 return handled;
1557 }
Romain Guy8506ab42009-06-11 17:35:47 -07001558
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001559 public void requestChildFocus(View child, View focused) {
1560 checkThread();
1561 if (mFocusedView != focused) {
1562 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(mFocusedView, focused);
1563 scheduleTraversals();
1564 }
1565 mFocusedView = mRealFocusedView = focused;
1566 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Request child focus: focus now "
1567 + mFocusedView);
1568 }
1569
1570 public void clearChildFocus(View child) {
1571 checkThread();
1572
1573 View oldFocus = mFocusedView;
1574
1575 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Clearing child focus");
1576 mFocusedView = mRealFocusedView = null;
1577 if (mView != null && !mView.hasFocus()) {
1578 // If a view gets the focus, the listener will be invoked from requestChildFocus()
1579 if (!mView.requestFocus(View.FOCUS_FORWARD)) {
1580 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
1581 }
1582 } else if (oldFocus != null) {
1583 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
1584 }
1585 }
1586
1587
1588 public void focusableViewAvailable(View v) {
1589 checkThread();
1590
1591 if (mView != null && !mView.hasFocus()) {
1592 v.requestFocus();
1593 } else {
1594 // the one case where will transfer focus away from the current one
1595 // is if the current view is a view group that prefers to give focus
1596 // to its children first AND the view is a descendant of it.
1597 mFocusedView = mView.findFocus();
1598 boolean descendantsHaveDibsOnFocus =
1599 (mFocusedView instanceof ViewGroup) &&
1600 (((ViewGroup) mFocusedView).getDescendantFocusability() ==
1601 ViewGroup.FOCUS_AFTER_DESCENDANTS);
1602 if (descendantsHaveDibsOnFocus && isViewDescendantOf(v, mFocusedView)) {
1603 // If a view gets the focus, the listener will be invoked from requestChildFocus()
1604 v.requestFocus();
1605 }
1606 }
1607 }
1608
1609 public void recomputeViewAttributes(View child) {
1610 checkThread();
1611 if (mView == child) {
1612 mAttachInfo.mRecomputeGlobalAttributes = true;
1613 if (!mWillDrawSoon) {
1614 scheduleTraversals();
1615 }
1616 }
1617 }
1618
1619 void dispatchDetachedFromWindow() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001620 if (mView != null) {
1621 mView.dispatchDetachedFromWindow();
1622 }
1623
1624 mView = null;
1625 mAttachInfo.mRootView = null;
Mathias Agopian5583dc62009-07-09 16:28:11 -07001626 mAttachInfo.mSurface = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001627
Romain Guy29d89972010-09-22 16:10:57 -07001628 destroyHardwareRenderer();
Romain Guy4caa4ed2010-08-25 14:46:24 -07001629
Dianne Hackborn0586a1b2009-09-06 21:08:27 -07001630 mSurface.release();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001631
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001632 if (mInputChannel != null) {
1633 if (mInputQueueCallback != null) {
1634 mInputQueueCallback.onInputQueueDestroyed(mInputQueue);
1635 mInputQueueCallback = null;
1636 } else {
1637 InputQueue.unregisterInputChannel(mInputChannel);
Jeff Brown46b9ac02010-04-22 18:58:52 -07001638 }
1639 }
1640
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001641 try {
1642 sWindowSession.remove(mWindow);
1643 } catch (RemoteException e) {
1644 }
Jeff Brown349703e2010-06-22 01:27:15 -07001645
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001646 // Dispose the input channel after removing the window so the Window Manager
1647 // doesn't interpret the input channel being closed as an abnormal termination.
1648 if (mInputChannel != null) {
1649 mInputChannel.dispose();
1650 mInputChannel = null;
Jeff Brown349703e2010-06-22 01:27:15 -07001651 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001652 }
Romain Guy8506ab42009-06-11 17:35:47 -07001653
Dianne Hackborn694f79b2010-03-17 19:44:59 -07001654 void updateConfiguration(Configuration config, boolean force) {
1655 if (DEBUG_CONFIGURATION) Log.v(TAG,
1656 "Applying new config to window "
1657 + mWindowAttributes.getTitle()
1658 + ": " + config);
1659 synchronized (sConfigCallbacks) {
1660 for (int i=sConfigCallbacks.size()-1; i>=0; i--) {
1661 sConfigCallbacks.get(i).onConfigurationChanged(config);
1662 }
1663 }
1664 if (mView != null) {
1665 // At this point the resources have been updated to
1666 // have the most recent config, whatever that is. Use
1667 // the on in them which may be newer.
1668 if (mView != null) {
1669 config = mView.getResources().getConfiguration();
1670 }
1671 if (force || mLastConfiguration.diff(config) != 0) {
1672 mLastConfiguration.setTo(config);
1673 mView.dispatchConfigurationChanged(config);
1674 }
1675 }
1676 }
1677
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001678 /**
1679 * Return true if child is an ancestor of parent, (or equal to the parent).
1680 */
1681 private static boolean isViewDescendantOf(View child, View parent) {
1682 if (child == parent) {
1683 return true;
1684 }
1685
1686 final ViewParent theParent = child.getParent();
1687 return (theParent instanceof ViewGroup) && isViewDescendantOf((View) theParent, parent);
1688 }
1689
Romain Guycdb86672010-03-18 18:54:50 -07001690 private static void forceLayout(View view) {
1691 view.forceLayout();
1692 if (view instanceof ViewGroup) {
1693 ViewGroup group = (ViewGroup) view;
1694 final int count = group.getChildCount();
1695 for (int i = 0; i < count; i++) {
1696 forceLayout(group.getChildAt(i));
1697 }
1698 }
1699 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001700
1701 public final static int DO_TRAVERSAL = 1000;
1702 public final static int DIE = 1001;
1703 public final static int RESIZED = 1002;
1704 public final static int RESIZED_REPORT = 1003;
1705 public final static int WINDOW_FOCUS_CHANGED = 1004;
1706 public final static int DISPATCH_KEY = 1005;
1707 public final static int DISPATCH_POINTER = 1006;
1708 public final static int DISPATCH_TRACKBALL = 1007;
1709 public final static int DISPATCH_APP_VISIBILITY = 1008;
1710 public final static int DISPATCH_GET_NEW_SURFACE = 1009;
1711 public final static int FINISHED_EVENT = 1010;
1712 public final static int DISPATCH_KEY_FROM_IME = 1011;
1713 public final static int FINISH_INPUT_CONNECTION = 1012;
1714 public final static int CHECK_FOCUS = 1013;
Dianne Hackbornffa42482009-09-23 22:20:11 -07001715 public final static int CLOSE_SYSTEM_DIALOGS = 1014;
Christopher Tatea53146c2010-09-07 11:57:52 -07001716 public final static int DISPATCH_DRAG_EVENT = 1015;
Chris Tate91e9bb32010-10-12 12:58:43 -07001717 public final static int DISPATCH_DRAG_LOCATION_EVENT = 1016;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001718
1719 @Override
1720 public void handleMessage(Message msg) {
1721 switch (msg.what) {
1722 case View.AttachInfo.INVALIDATE_MSG:
1723 ((View) msg.obj).invalidate();
1724 break;
1725 case View.AttachInfo.INVALIDATE_RECT_MSG:
1726 final View.AttachInfo.InvalidateInfo info = (View.AttachInfo.InvalidateInfo) msg.obj;
1727 info.target.invalidate(info.left, info.top, info.right, info.bottom);
1728 info.release();
1729 break;
1730 case DO_TRAVERSAL:
1731 if (mProfile) {
1732 Debug.startMethodTracing("ViewRoot");
1733 }
1734
1735 performTraversals();
1736
1737 if (mProfile) {
1738 Debug.stopMethodTracing();
1739 mProfile = false;
1740 }
1741 break;
1742 case FINISHED_EVENT:
1743 handleFinishedEvent(msg.arg1, msg.arg2 != 0);
1744 break;
1745 case DISPATCH_KEY:
Jeff Brown92ff1dd2010-08-11 16:16:06 -07001746 deliverKeyEvent((KeyEvent)msg.obj, msg.arg1 != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001747 break;
Jeff Brown3915bb82010-11-05 15:02:16 -07001748 case DISPATCH_POINTER:
1749 deliverPointerEvent((MotionEvent) msg.obj, msg.arg1 != 0);
1750 break;
1751 case DISPATCH_TRACKBALL:
1752 deliverTrackballEvent((MotionEvent) msg.obj, msg.arg1 != 0);
1753 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001754 case DISPATCH_APP_VISIBILITY:
1755 handleAppVisibility(msg.arg1 != 0);
1756 break;
1757 case DISPATCH_GET_NEW_SURFACE:
1758 handleGetNewSurface();
1759 break;
1760 case RESIZED:
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001761 ResizedInfo ri = (ResizedInfo)msg.obj;
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001762
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001763 if (mWinFrame.width() == msg.arg1 && mWinFrame.height() == msg.arg2
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001764 && mPendingContentInsets.equals(ri.coveredInsets)
Dianne Hackbornd49258f2010-03-26 00:44:29 -07001765 && mPendingVisibleInsets.equals(ri.visibleInsets)
1766 && ((ResizedInfo)msg.obj).newConfig == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001767 break;
1768 }
1769 // fall through...
1770 case RESIZED_REPORT:
1771 if (mAdded) {
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001772 Configuration config = ((ResizedInfo)msg.obj).newConfig;
1773 if (config != null) {
Dianne Hackborn694f79b2010-03-17 19:44:59 -07001774 updateConfiguration(config, false);
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001775 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001776 mWinFrame.left = 0;
1777 mWinFrame.right = msg.arg1;
1778 mWinFrame.top = 0;
1779 mWinFrame.bottom = msg.arg2;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001780 mPendingContentInsets.set(((ResizedInfo)msg.obj).coveredInsets);
1781 mPendingVisibleInsets.set(((ResizedInfo)msg.obj).visibleInsets);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001782 if (msg.what == RESIZED_REPORT) {
1783 mReportNextDraw = true;
1784 }
Romain Guycdb86672010-03-18 18:54:50 -07001785
1786 if (mView != null) {
1787 forceLayout(mView);
1788 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001789 requestLayout();
1790 }
1791 break;
1792 case WINDOW_FOCUS_CHANGED: {
1793 if (mAdded) {
1794 boolean hasWindowFocus = msg.arg1 != 0;
1795 mAttachInfo.mHasWindowFocus = hasWindowFocus;
1796 if (hasWindowFocus) {
1797 boolean inTouchMode = msg.arg2 != 0;
Romain Guy2d4cff62010-04-09 15:39:00 -07001798 ensureTouchModeLocally(inTouchMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001799
Romain Guyc361da82010-10-25 15:29:10 -07001800 if (mAttachInfo.mHardwareRenderer != null &&
1801 mSurface != null && mSurface.isValid()) {
Romain Guyb051e892010-09-28 19:09:36 -07001802 mAttachInfo.mHardwareRenderer.initializeIfNeeded(mWidth, mHeight,
1803 mAttachInfo, mHolder);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001804 }
1805 }
Romain Guy8506ab42009-06-11 17:35:47 -07001806
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001807 mLastWasImTarget = WindowManager.LayoutParams
1808 .mayUseInputMethod(mWindowAttributes.flags);
Romain Guy8506ab42009-06-11 17:35:47 -07001809
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001810 InputMethodManager imm = InputMethodManager.peekInstance();
1811 if (mView != null) {
1812 if (hasWindowFocus && imm != null && mLastWasImTarget) {
1813 imm.startGettingWindowFocus(mView);
1814 }
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07001815 mAttachInfo.mKeyDispatchState.reset();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001816 mView.dispatchWindowFocusChanged(hasWindowFocus);
1817 }
svetoslavganov75986cf2009-05-14 22:28:01 -07001818
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001819 // Note: must be done after the focus change callbacks,
1820 // so all of the view state is set up correctly.
1821 if (hasWindowFocus) {
1822 if (imm != null && mLastWasImTarget) {
1823 imm.onWindowFocus(mView, mView.findFocus(),
1824 mWindowAttributes.softInputMode,
1825 !mHasHadWindowFocus, mWindowAttributes.flags);
1826 }
1827 // Clear the forward bit. We can just do this directly, since
1828 // the window manager doesn't care about it.
1829 mWindowAttributes.softInputMode &=
1830 ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
1831 ((WindowManager.LayoutParams)mView.getLayoutParams())
1832 .softInputMode &=
1833 ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
1834 mHasHadWindowFocus = true;
1835 }
svetoslavganov75986cf2009-05-14 22:28:01 -07001836
1837 if (hasWindowFocus && mView != null) {
1838 sendAccessibilityEvents();
1839 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001840 }
1841 } break;
1842 case DIE:
Dianne Hackborn94d69142009-09-28 22:14:42 -07001843 doDie();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001844 break;
The Android Open Source Project10592532009-03-18 17:39:46 -07001845 case DISPATCH_KEY_FROM_IME: {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001846 if (LOCAL_LOGV) Log.v(
Jeff Brownc5ed5912010-07-14 18:48:53 -07001847 TAG, "Dispatching key "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001848 + msg.obj + " from IME to " + mView);
The Android Open Source Project10592532009-03-18 17:39:46 -07001849 KeyEvent event = (KeyEvent)msg.obj;
1850 if ((event.getFlags()&KeyEvent.FLAG_FROM_SYSTEM) != 0) {
1851 // The IME is trying to say this event is from the
1852 // system! Bad bad bad!
Romain Guy812ccbe2010-06-01 14:07:24 -07001853 event = KeyEvent.changeFlags(event, event.getFlags() & ~KeyEvent.FLAG_FROM_SYSTEM);
The Android Open Source Project10592532009-03-18 17:39:46 -07001854 }
Jeff Brown3915bb82010-11-05 15:02:16 -07001855 deliverKeyEventPostIme((KeyEvent)msg.obj, false);
The Android Open Source Project10592532009-03-18 17:39:46 -07001856 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001857 case FINISH_INPUT_CONNECTION: {
1858 InputMethodManager imm = InputMethodManager.peekInstance();
1859 if (imm != null) {
1860 imm.reportFinishInputConnection((InputConnection)msg.obj);
1861 }
1862 } break;
1863 case CHECK_FOCUS: {
1864 InputMethodManager imm = InputMethodManager.peekInstance();
1865 if (imm != null) {
1866 imm.checkFocus();
1867 }
1868 } break;
Dianne Hackbornffa42482009-09-23 22:20:11 -07001869 case CLOSE_SYSTEM_DIALOGS: {
1870 if (mView != null) {
1871 mView.onCloseSystemDialogs((String)msg.obj);
1872 }
1873 } break;
Chris Tate91e9bb32010-10-12 12:58:43 -07001874 case DISPATCH_DRAG_EVENT:
1875 case DISPATCH_DRAG_LOCATION_EVENT: {
Christopher Tatea53146c2010-09-07 11:57:52 -07001876 handleDragEvent((DragEvent)msg.obj);
1877 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001878 }
1879 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07001880
Jeff Brown3915bb82010-11-05 15:02:16 -07001881 private void startInputEvent(InputQueue.FinishedCallback finishedCallback) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07001882 if (mFinishedCallback != null) {
1883 Slog.w(TAG, "Received a new input event from the input queue but there is "
1884 + "already an unfinished input event in progress.");
1885 }
1886
1887 mFinishedCallback = finishedCallback;
1888 }
1889
Jeff Brown3915bb82010-11-05 15:02:16 -07001890 private void finishInputEvent(boolean handled) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07001891 if (LOCAL_LOGV) Log.v(TAG, "Telling window manager input event is finished");
Jeff Brown92ff1dd2010-08-11 16:16:06 -07001892
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001893 if (mFinishedCallback != null) {
Jeff Brown3915bb82010-11-05 15:02:16 -07001894 mFinishedCallback.finished(handled);
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001895 mFinishedCallback = null;
Jeff Brown92ff1dd2010-08-11 16:16:06 -07001896 } else {
Jeff Brown93ed4e32010-09-23 13:51:48 -07001897 Slog.w(TAG, "Attempted to tell the input queue that the current input event "
1898 + "is finished but there is no input event actually in progress.");
Jeff Brown46b9ac02010-04-22 18:58:52 -07001899 }
1900 }
1901
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001902 /**
1903 * Something in the current window tells us we need to change the touch mode. For
1904 * example, we are not in touch mode, and the user touches the screen.
1905 *
1906 * If the touch mode has changed, tell the window manager, and handle it locally.
1907 *
1908 * @param inTouchMode Whether we want to be in touch mode.
1909 * @return True if the touch mode changed and focus changed was changed as a result
1910 */
1911 boolean ensureTouchMode(boolean inTouchMode) {
1912 if (DBG) Log.d("touchmode", "ensureTouchMode(" + inTouchMode + "), current "
1913 + "touch mode is " + mAttachInfo.mInTouchMode);
1914 if (mAttachInfo.mInTouchMode == inTouchMode) return false;
1915
1916 // tell the window manager
1917 try {
1918 sWindowSession.setInTouchMode(inTouchMode);
1919 } catch (RemoteException e) {
1920 throw new RuntimeException(e);
1921 }
1922
1923 // handle the change
Romain Guy2d4cff62010-04-09 15:39:00 -07001924 return ensureTouchModeLocally(inTouchMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001925 }
1926
1927 /**
1928 * Ensure that the touch mode for this window is set, and if it is changing,
1929 * take the appropriate action.
1930 * @param inTouchMode Whether we want to be in touch mode.
1931 * @return True if the touch mode changed and focus changed was changed as a result
1932 */
Romain Guy2d4cff62010-04-09 15:39:00 -07001933 private boolean ensureTouchModeLocally(boolean inTouchMode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001934 if (DBG) Log.d("touchmode", "ensureTouchModeLocally(" + inTouchMode + "), current "
1935 + "touch mode is " + mAttachInfo.mInTouchMode);
1936
1937 if (mAttachInfo.mInTouchMode == inTouchMode) return false;
1938
1939 mAttachInfo.mInTouchMode = inTouchMode;
1940 mAttachInfo.mTreeObserver.dispatchOnTouchModeChanged(inTouchMode);
1941
Romain Guy2d4cff62010-04-09 15:39:00 -07001942 return (inTouchMode) ? enterTouchMode() : leaveTouchMode();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001943 }
1944
1945 private boolean enterTouchMode() {
1946 if (mView != null) {
1947 if (mView.hasFocus()) {
1948 // note: not relying on mFocusedView here because this could
1949 // be when the window is first being added, and mFocused isn't
1950 // set yet.
1951 final View focused = mView.findFocus();
1952 if (focused != null && !focused.isFocusableInTouchMode()) {
1953
1954 final ViewGroup ancestorToTakeFocus =
1955 findAncestorToTakeFocusInTouchMode(focused);
1956 if (ancestorToTakeFocus != null) {
1957 // there is an ancestor that wants focus after its descendants that
1958 // is focusable in touch mode.. give it focus
1959 return ancestorToTakeFocus.requestFocus();
1960 } else {
1961 // nothing appropriate to have focus in touch mode, clear it out
1962 mView.unFocus();
1963 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(focused, null);
1964 mFocusedView = null;
1965 return true;
1966 }
1967 }
1968 }
1969 }
1970 return false;
1971 }
1972
1973
1974 /**
1975 * Find an ancestor of focused that wants focus after its descendants and is
1976 * focusable in touch mode.
1977 * @param focused The currently focused view.
1978 * @return An appropriate view, or null if no such view exists.
1979 */
1980 private ViewGroup findAncestorToTakeFocusInTouchMode(View focused) {
1981 ViewParent parent = focused.getParent();
1982 while (parent instanceof ViewGroup) {
1983 final ViewGroup vgParent = (ViewGroup) parent;
1984 if (vgParent.getDescendantFocusability() == ViewGroup.FOCUS_AFTER_DESCENDANTS
1985 && vgParent.isFocusableInTouchMode()) {
1986 return vgParent;
1987 }
1988 if (vgParent.isRootNamespace()) {
1989 return null;
1990 } else {
1991 parent = vgParent.getParent();
1992 }
1993 }
1994 return null;
1995 }
1996
1997 private boolean leaveTouchMode() {
1998 if (mView != null) {
1999 if (mView.hasFocus()) {
2000 // i learned the hard way to not trust mFocusedView :)
2001 mFocusedView = mView.findFocus();
2002 if (!(mFocusedView instanceof ViewGroup)) {
2003 // some view has focus, let it keep it
2004 return false;
2005 } else if (((ViewGroup)mFocusedView).getDescendantFocusability() !=
2006 ViewGroup.FOCUS_AFTER_DESCENDANTS) {
2007 // some view group has focus, and doesn't prefer its children
2008 // over itself for focus, so let them keep it.
2009 return false;
2010 }
2011 }
2012
2013 // find the best view to give focus to in this brave new non-touch-mode
2014 // world
2015 final View focused = focusSearch(null, View.FOCUS_DOWN);
2016 if (focused != null) {
2017 return focused.requestFocus(View.FOCUS_DOWN);
2018 }
2019 }
2020 return false;
2021 }
2022
Jeff Brown3915bb82010-11-05 15:02:16 -07002023 private void deliverPointerEvent(MotionEvent event, boolean sendDone) {
2024 // If there is no view, then the event will not be handled.
2025 if (mView == null || !mAdded) {
2026 finishPointerEvent(event, sendDone, false);
2027 return;
2028 }
2029
2030 // Translate the pointer event for compatibility, if needed.
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002031 if (mTranslator != null) {
2032 mTranslator.translateEventInScreenToAppWindow(event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002033 }
2034
Jeff Brown3915bb82010-11-05 15:02:16 -07002035 // Enter touch mode on the down.
2036 boolean isDown = event.getAction() == MotionEvent.ACTION_DOWN;
2037 if (isDown) {
2038 ensureTouchMode(true);
2039 }
2040 if(Config.LOGV) {
2041 captureMotionLog("captureDispatchPointer", event);
2042 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002043
Jeff Brown3915bb82010-11-05 15:02:16 -07002044 // Offset the scroll position.
2045 if (mCurScrollY != 0) {
2046 event.offsetLocation(0, mCurScrollY);
2047 }
2048 if (MEASURE_LATENCY) {
2049 lt.sample("A Dispatching TouchEvents", System.nanoTime() - event.getEventTimeNano());
2050 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002051
Jeff Brown3915bb82010-11-05 15:02:16 -07002052 // Remember the touch position for possible drag-initiation.
2053 mLastTouchPoint.x = event.getRawX();
2054 mLastTouchPoint.y = event.getRawY();
2055
2056 // Dispatch touch to view hierarchy.
2057 boolean handled = mView.dispatchTouchEvent(event);
2058 if (MEASURE_LATENCY) {
2059 lt.sample("B Dispatched TouchEvents ", System.nanoTime() - event.getEventTimeNano());
2060 }
2061 if (handled) {
2062 finishPointerEvent(event, sendDone, true);
2063 return;
2064 }
2065
2066 // Apply edge slop and try again, if appropriate.
2067 final int edgeFlags = event.getEdgeFlags();
2068 if (edgeFlags != 0 && mView instanceof ViewGroup) {
2069 final int edgeSlop = mViewConfiguration.getScaledEdgeSlop();
2070 int direction = View.FOCUS_UP;
2071 int x = (int)event.getX();
2072 int y = (int)event.getY();
2073 final int[] deltas = new int[2];
2074
2075 if ((edgeFlags & MotionEvent.EDGE_TOP) != 0) {
2076 direction = View.FOCUS_DOWN;
2077 if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
2078 deltas[0] = edgeSlop;
2079 x += edgeSlop;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002080 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
Jeff Brown3915bb82010-11-05 15:02:16 -07002081 deltas[0] = -edgeSlop;
2082 x -= edgeSlop;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002083 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002084 } else if ((edgeFlags & MotionEvent.EDGE_BOTTOM) != 0) {
2085 direction = View.FOCUS_UP;
2086 if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
2087 deltas[0] = edgeSlop;
2088 x += edgeSlop;
2089 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
2090 deltas[0] = -edgeSlop;
2091 x -= edgeSlop;
2092 }
2093 } else if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
2094 direction = View.FOCUS_RIGHT;
2095 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
2096 direction = View.FOCUS_LEFT;
2097 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002098
Jeff Brown3915bb82010-11-05 15:02:16 -07002099 View nearest = FocusFinder.getInstance().findNearestTouchable(
2100 ((ViewGroup) mView), x, y, direction, deltas);
2101 if (nearest != null) {
2102 event.offsetLocation(deltas[0], deltas[1]);
2103 event.setEdgeFlags(0);
2104 if (mView.dispatchTouchEvent(event)) {
2105 finishPointerEvent(event, sendDone, true);
2106 return;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002107 }
2108 }
2109 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002110
2111 // Pointer event was unhandled.
2112 finishPointerEvent(event, sendDone, false);
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002113 }
2114
Jeff Brown3915bb82010-11-05 15:02:16 -07002115 private void finishPointerEvent(MotionEvent event, boolean sendDone, boolean handled) {
2116 event.recycle();
2117 if (sendDone) {
2118 finishInputEvent(handled);
2119 }
2120 if (LOCAL_LOGV || WATCH_POINTER) Log.i(TAG, "Done dispatching!");
2121 }
2122
2123 private void deliverTrackballEvent(MotionEvent event, boolean sendDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002124 if (DEBUG_TRACKBALL) Log.v(TAG, "Motion event:" + event);
2125
Jeff Brown3915bb82010-11-05 15:02:16 -07002126 // If there is no view, then the event will not be handled.
2127 if (mView == null || !mAdded) {
2128 finishTrackballEvent(event, sendDone, false);
2129 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002130 }
2131
Jeff Brown3915bb82010-11-05 15:02:16 -07002132 // Deliver the trackball event to the view.
2133 if (mView.dispatchTrackballEvent(event)) {
2134 // If we reach this, we delivered a trackball event to mView and
2135 // mView consumed it. Because we will not translate the trackball
2136 // event into a key event, touch mode will not exit, so we exit
2137 // touch mode here.
2138 ensureTouchMode(false);
2139
2140 finishTrackballEvent(event, sendDone, true);
2141 mLastTrackballTime = Integer.MIN_VALUE;
2142 return;
2143 }
2144
2145 // Translate the trackball event into DPAD keys and try to deliver those.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002146 final TrackballAxis x = mTrackballAxisX;
2147 final TrackballAxis y = mTrackballAxisY;
2148
2149 long curTime = SystemClock.uptimeMillis();
Jeff Brown3915bb82010-11-05 15:02:16 -07002150 if ((mLastTrackballTime + MAX_TRACKBALL_DELAY) < curTime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002151 // It has been too long since the last movement,
2152 // so restart at the beginning.
2153 x.reset(0);
2154 y.reset(0);
2155 mLastTrackballTime = curTime;
2156 }
2157
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002158 final int action = event.getAction();
2159 final int metastate = event.getMetaState();
2160 switch (action) {
2161 case MotionEvent.ACTION_DOWN:
2162 x.reset(2);
2163 y.reset(2);
2164 deliverKeyEvent(new KeyEvent(curTime, curTime,
2165 KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_CENTER,
2166 0, metastate), false);
2167 break;
2168 case MotionEvent.ACTION_UP:
2169 x.reset(2);
2170 y.reset(2);
2171 deliverKeyEvent(new KeyEvent(curTime, curTime,
2172 KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_CENTER,
2173 0, metastate), false);
2174 break;
2175 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002176
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002177 if (DEBUG_TRACKBALL) Log.v(TAG, "TB X=" + x.position + " step="
2178 + x.step + " dir=" + x.dir + " acc=" + x.acceleration
2179 + " move=" + event.getX()
2180 + " / Y=" + y.position + " step="
2181 + y.step + " dir=" + y.dir + " acc=" + y.acceleration
2182 + " move=" + event.getY());
2183 final float xOff = x.collect(event.getX(), event.getEventTime(), "X");
2184 final float yOff = y.collect(event.getY(), event.getEventTime(), "Y");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002185
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002186 // Generate DPAD events based on the trackball movement.
2187 // We pick the axis that has moved the most as the direction of
2188 // the DPAD. When we generate DPAD events for one axis, then the
2189 // other axis is reset -- we don't want to perform DPAD jumps due
2190 // to slight movements in the trackball when making major movements
2191 // along the other axis.
2192 int keycode = 0;
2193 int movement = 0;
2194 float accel = 1;
2195 if (xOff > yOff) {
2196 movement = x.generate((2/event.getXPrecision()));
2197 if (movement != 0) {
2198 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_RIGHT
2199 : KeyEvent.KEYCODE_DPAD_LEFT;
2200 accel = x.acceleration;
2201 y.reset(2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002202 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002203 } else if (yOff > 0) {
2204 movement = y.generate((2/event.getYPrecision()));
2205 if (movement != 0) {
2206 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_DOWN
2207 : KeyEvent.KEYCODE_DPAD_UP;
2208 accel = y.acceleration;
2209 x.reset(2);
2210 }
2211 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002212
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002213 if (keycode != 0) {
2214 if (movement < 0) movement = -movement;
2215 int accelMovement = (int)(movement * accel);
2216 if (DEBUG_TRACKBALL) Log.v(TAG, "Move: movement=" + movement
2217 + " accelMovement=" + accelMovement
2218 + " accel=" + accel);
2219 if (accelMovement > movement) {
2220 if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: "
2221 + keycode);
2222 movement--;
2223 deliverKeyEvent(new KeyEvent(curTime, curTime,
2224 KeyEvent.ACTION_MULTIPLE, keycode,
2225 accelMovement-movement, metastate), false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002226 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002227 while (movement > 0) {
2228 if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: "
2229 + keycode);
2230 movement--;
2231 curTime = SystemClock.uptimeMillis();
2232 deliverKeyEvent(new KeyEvent(curTime, curTime,
2233 KeyEvent.ACTION_DOWN, keycode, 0, event.getMetaState()), false);
2234 deliverKeyEvent(new KeyEvent(curTime, curTime,
2235 KeyEvent.ACTION_UP, keycode, 0, metastate), false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002236 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002237 mLastTrackballTime = curTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002238 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002239
2240 // Unfortunately we can't tell whether the application consumed the keys, so
2241 // we always consider the trackball event handled.
2242 finishTrackballEvent(event, sendDone, true);
2243 }
2244
2245 private void finishTrackballEvent(MotionEvent event, boolean sendDone, boolean handled) {
2246 event.recycle();
2247 if (sendDone) {
2248 finishInputEvent(handled);
2249 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002250 }
2251
2252 /**
2253 * @param keyCode The key code
2254 * @return True if the key is directional.
2255 */
2256 static boolean isDirectional(int keyCode) {
2257 switch (keyCode) {
2258 case KeyEvent.KEYCODE_DPAD_LEFT:
2259 case KeyEvent.KEYCODE_DPAD_RIGHT:
2260 case KeyEvent.KEYCODE_DPAD_UP:
2261 case KeyEvent.KEYCODE_DPAD_DOWN:
2262 return true;
2263 }
2264 return false;
2265 }
2266
2267 /**
2268 * Returns true if this key is a keyboard key.
2269 * @param keyEvent The key event.
2270 * @return whether this key is a keyboard key.
2271 */
2272 private static boolean isKeyboardKey(KeyEvent keyEvent) {
2273 final int convertedKey = keyEvent.getUnicodeChar();
2274 return convertedKey > 0;
2275 }
2276
2277
2278
2279 /**
2280 * See if the key event means we should leave touch mode (and leave touch
2281 * mode if so).
2282 * @param event The key event.
2283 * @return Whether this key event should be consumed (meaning the act of
2284 * leaving touch mode alone is considered the event).
2285 */
2286 private boolean checkForLeavingTouchModeAndConsume(KeyEvent event) {
Adam Powell51a6bee2010-03-15 14:07:28 -07002287 final int action = event.getAction();
2288 if (action != KeyEvent.ACTION_DOWN && action != KeyEvent.ACTION_MULTIPLE) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002289 return false;
2290 }
2291 if ((event.getFlags()&KeyEvent.FLAG_KEEP_TOUCH_MODE) != 0) {
2292 return false;
2293 }
2294
2295 // only relevant if we are in touch mode
2296 if (!mAttachInfo.mInTouchMode) {
2297 return false;
2298 }
2299
2300 // if something like an edit text has focus and the user is typing,
2301 // leave touch mode
2302 //
2303 // note: the condition of not being a keyboard key is kind of a hacky
2304 // approximation of whether we think the focused view will want the
2305 // key; if we knew for sure whether the focused view would consume
2306 // the event, that would be better.
2307 if (isKeyboardKey(event) && mView != null && mView.hasFocus()) {
2308 mFocusedView = mView.findFocus();
2309 if ((mFocusedView instanceof ViewGroup)
2310 && ((ViewGroup) mFocusedView).getDescendantFocusability() ==
2311 ViewGroup.FOCUS_AFTER_DESCENDANTS) {
2312 // something has focus, but is holding it weakly as a container
2313 return false;
2314 }
2315 if (ensureTouchMode(false)) {
2316 throw new IllegalStateException("should not have changed focus "
2317 + "when leaving touch mode while a view has focus.");
2318 }
2319 return false;
2320 }
2321
2322 if (isDirectional(event.getKeyCode())) {
2323 // no view has focus, so we leave touch mode (and find something
2324 // to give focus to). the event is consumed if we were able to
2325 // find something to give focus to.
2326 return ensureTouchMode(false);
2327 }
2328 return false;
2329 }
2330
2331 /**
Romain Guy8506ab42009-06-11 17:35:47 -07002332 * log motion events
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002333 */
2334 private static void captureMotionLog(String subTag, MotionEvent ev) {
Romain Guy8506ab42009-06-11 17:35:47 -07002335 //check dynamic switch
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002336 if (ev == null ||
2337 SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_EVENT, 0) == 0) {
2338 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002339 }
Romain Guy8506ab42009-06-11 17:35:47 -07002340
2341 StringBuilder sb = new StringBuilder(subTag + ": ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002342 sb.append(ev.getDownTime()).append(',');
2343 sb.append(ev.getEventTime()).append(',');
2344 sb.append(ev.getAction()).append(',');
Romain Guy8506ab42009-06-11 17:35:47 -07002345 sb.append(ev.getX()).append(',');
2346 sb.append(ev.getY()).append(',');
2347 sb.append(ev.getPressure()).append(',');
2348 sb.append(ev.getSize()).append(',');
2349 sb.append(ev.getMetaState()).append(',');
2350 sb.append(ev.getXPrecision()).append(',');
2351 sb.append(ev.getYPrecision()).append(',');
2352 sb.append(ev.getDeviceId()).append(',');
2353 sb.append(ev.getEdgeFlags());
2354 Log.d(TAG, sb.toString());
2355 }
2356 /**
2357 * log motion events
2358 */
2359 private static void captureKeyLog(String subTag, KeyEvent ev) {
2360 //check dynamic switch
2361 if (ev == null ||
2362 SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_EVENT, 0) == 0) {
2363 return;
2364 }
2365 StringBuilder sb = new StringBuilder(subTag + ": ");
2366 sb.append(ev.getDownTime()).append(',');
2367 sb.append(ev.getEventTime()).append(',');
2368 sb.append(ev.getAction()).append(',');
2369 sb.append(ev.getKeyCode()).append(',');
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002370 sb.append(ev.getRepeatCount()).append(',');
2371 sb.append(ev.getMetaState()).append(',');
2372 sb.append(ev.getDeviceId()).append(',');
2373 sb.append(ev.getScanCode());
Romain Guy8506ab42009-06-11 17:35:47 -07002374 Log.d(TAG, sb.toString());
2375 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002376
2377 int enqueuePendingEvent(Object event, boolean sendDone) {
2378 int seq = mPendingEventSeq+1;
2379 if (seq < 0) seq = 0;
2380 mPendingEventSeq = seq;
2381 mPendingEvents.put(seq, event);
2382 return sendDone ? seq : -seq;
2383 }
2384
2385 Object retrievePendingEvent(int seq) {
2386 if (seq < 0) seq = -seq;
2387 Object event = mPendingEvents.get(seq);
2388 if (event != null) {
2389 mPendingEvents.remove(seq);
2390 }
2391 return event;
2392 }
Romain Guy8506ab42009-06-11 17:35:47 -07002393
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002394 private void deliverKeyEvent(KeyEvent event, boolean sendDone) {
Jeff Brown3915bb82010-11-05 15:02:16 -07002395 // If there is no view, then the event will not be handled.
2396 if (mView == null || !mAdded) {
2397 finishKeyEvent(event, sendDone, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002398 return;
2399 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002400
2401 if (LOCAL_LOGV) Log.v(TAG, "Dispatching key " + event + " to " + mView);
2402
2403 // Perform predispatching before the IME.
2404 if (mView.dispatchKeyEventPreIme(event)) {
2405 finishKeyEvent(event, sendDone, true);
2406 return;
2407 }
2408
2409 // Dispatch to the IME before propagating down the view hierarchy.
2410 // The IME will eventually call back into handleFinishedEvent.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002411 if (mLastWasImTarget) {
2412 InputMethodManager imm = InputMethodManager.peekInstance();
Jeff Brown3915bb82010-11-05 15:02:16 -07002413 if (imm != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002414 int seq = enqueuePendingEvent(event, sendDone);
2415 if (DEBUG_IMF) Log.v(TAG, "Sending key event to IME: seq="
2416 + seq + " event=" + event);
Jeff Brown3915bb82010-11-05 15:02:16 -07002417 imm.dispatchKeyEvent(mView.getContext(), seq, event, mInputMethodCallback);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002418 return;
2419 }
2420 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002421
2422 // Not dispatching to IME, continue with post IME actions.
2423 deliverKeyEventPostIme(event, sendDone);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002424 }
2425
Jeff Brown3915bb82010-11-05 15:02:16 -07002426 private void handleFinishedEvent(int seq, boolean handled) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002427 final KeyEvent event = (KeyEvent)retrievePendingEvent(seq);
2428 if (DEBUG_IMF) Log.v(TAG, "IME finished event: seq=" + seq
2429 + " handled=" + handled + " event=" + event);
2430 if (event != null) {
2431 final boolean sendDone = seq >= 0;
Jeff Brown3915bb82010-11-05 15:02:16 -07002432 if (handled) {
2433 finishKeyEvent(event, sendDone, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002434 } else {
Jeff Brown3915bb82010-11-05 15:02:16 -07002435 deliverKeyEventPostIme(event, sendDone);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002436 }
2437 }
2438 }
Romain Guy8506ab42009-06-11 17:35:47 -07002439
Jeff Brown3915bb82010-11-05 15:02:16 -07002440 private void deliverKeyEventPostIme(KeyEvent event, boolean sendDone) {
2441 // If the view went away, then the event will not be handled.
2442 if (mView == null || !mAdded) {
2443 finishKeyEvent(event, sendDone, false);
2444 return;
2445 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002446
Jeff Brown3915bb82010-11-05 15:02:16 -07002447 // If the key's purpose is to exit touch mode then we consume it and consider it handled.
2448 if (checkForLeavingTouchModeAndConsume(event)) {
2449 finishKeyEvent(event, sendDone, true);
2450 return;
2451 }
Romain Guy8506ab42009-06-11 17:35:47 -07002452
Jeff Brown3915bb82010-11-05 15:02:16 -07002453 if (Config.LOGV) {
2454 captureKeyLog("captureDispatchKeyEvent", event);
2455 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002456
Jeff Brown3915bb82010-11-05 15:02:16 -07002457 // Deliver the key to the view hierarchy.
2458 if (mView.dispatchKeyEvent(event)) {
2459 finishKeyEvent(event, sendDone, true);
2460 return;
2461 }
Joe Onorato86f67862010-11-05 18:57:34 -07002462
Jeff Brown3915bb82010-11-05 15:02:16 -07002463 // Apply the fallback event policy.
2464 if (mFallbackEventHandler.dispatchKeyEvent(event)) {
2465 finishKeyEvent(event, sendDone, true);
2466 return;
2467 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002468
Jeff Brown3915bb82010-11-05 15:02:16 -07002469 // Handle automatic focus changes.
2470 if (event.getAction() == KeyEvent.ACTION_DOWN) {
2471 int direction = 0;
2472 switch (event.getKeyCode()) {
2473 case KeyEvent.KEYCODE_DPAD_LEFT:
2474 direction = View.FOCUS_LEFT;
2475 break;
2476 case KeyEvent.KEYCODE_DPAD_RIGHT:
2477 direction = View.FOCUS_RIGHT;
2478 break;
2479 case KeyEvent.KEYCODE_DPAD_UP:
2480 direction = View.FOCUS_UP;
2481 break;
2482 case KeyEvent.KEYCODE_DPAD_DOWN:
2483 direction = View.FOCUS_DOWN;
2484 break;
2485 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002486
Jeff Brown3915bb82010-11-05 15:02:16 -07002487 if (direction != 0) {
2488 View focused = mView != null ? mView.findFocus() : null;
2489 if (focused != null) {
2490 View v = focused.focusSearch(direction);
2491 if (v != null && v != focused) {
2492 // do the math the get the interesting rect
2493 // of previous focused into the coord system of
2494 // newly focused view
2495 focused.getFocusedRect(mTempRect);
2496 if (mView instanceof ViewGroup) {
2497 ((ViewGroup) mView).offsetDescendantRectToMyCoords(
2498 focused, mTempRect);
2499 ((ViewGroup) mView).offsetRectIntoDescendantCoords(
2500 v, mTempRect);
2501 }
2502 if (v.requestFocus(direction, mTempRect)) {
2503 playSoundEffect(
2504 SoundEffectConstants.getContantForFocusDirection(direction));
2505 finishKeyEvent(event, sendDone, true);
2506 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002507 }
2508 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002509
2510 // Give the focused view a last chance to handle the dpad key.
2511 if (mView.dispatchUnhandledMove(focused, direction)) {
2512 finishKeyEvent(event, sendDone, true);
2513 return;
2514 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002515 }
2516 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002517 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002518
Jeff Brown3915bb82010-11-05 15:02:16 -07002519 // Key was unhandled.
2520 finishKeyEvent(event, sendDone, false);
2521 }
2522
2523 private void finishKeyEvent(KeyEvent event, boolean sendDone, boolean handled) {
2524 if (sendDone) {
2525 finishInputEvent(handled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002526 }
2527 }
2528
Christopher Tatea53146c2010-09-07 11:57:52 -07002529 /* drag/drop */
2530 private void handleDragEvent(DragEvent event) {
2531 // From the root, only drag start/end/location are dispatched. entered/exited
2532 // are determined and dispatched by the viewgroup hierarchy, who then report
2533 // that back here for ultimate reporting back to the framework.
2534 if (mView != null && mAdded) {
2535 final int what = event.mAction;
2536
2537 if (what == DragEvent.ACTION_DRAG_EXITED) {
2538 // A direct EXITED event means that the window manager knows we've just crossed
2539 // a window boundary, so the current drag target within this one must have
2540 // just been exited. Send it the usual notifications and then we're done
2541 // for now.
Chris Tate9d1ab882010-11-02 15:55:39 -07002542 mView.dispatchDragEvent(event);
Christopher Tatea53146c2010-09-07 11:57:52 -07002543 } else {
2544 // Cache the drag description when the operation starts, then fill it in
2545 // on subsequent calls as a convenience
2546 if (what == DragEvent.ACTION_DRAG_STARTED) {
Chris Tate9d1ab882010-11-02 15:55:39 -07002547 mCurrentDragView = null; // Start the current-recipient tracking
Christopher Tatea53146c2010-09-07 11:57:52 -07002548 mDragDescription = event.mClipDescription;
2549 } else {
2550 event.mClipDescription = mDragDescription;
2551 }
2552
2553 // For events with a [screen] location, translate into window coordinates
2554 if ((what == DragEvent.ACTION_DRAG_LOCATION) || (what == DragEvent.ACTION_DROP)) {
2555 mDragPoint.set(event.mX, event.mY);
2556 if (mTranslator != null) {
2557 mTranslator.translatePointInScreenToAppWindow(mDragPoint);
2558 }
2559
2560 if (mCurScrollY != 0) {
2561 mDragPoint.offset(0, mCurScrollY);
2562 }
2563
2564 event.mX = mDragPoint.x;
2565 event.mY = mDragPoint.y;
2566 }
2567
2568 // Remember who the current drag target is pre-dispatch
2569 final View prevDragView = mCurrentDragView;
2570
2571 // Now dispatch the drag/drop event
Chris Tated4533f12010-10-19 15:15:08 -07002572 boolean result = mView.dispatchDragEvent(event);
Christopher Tatea53146c2010-09-07 11:57:52 -07002573
2574 // If we changed apparent drag target, tell the OS about it
2575 if (prevDragView != mCurrentDragView) {
2576 try {
2577 if (prevDragView != null) {
2578 sWindowSession.dragRecipientExited(mWindow);
2579 }
2580 if (mCurrentDragView != null) {
2581 sWindowSession.dragRecipientEntered(mWindow);
2582 }
2583 } catch (RemoteException e) {
2584 Slog.e(TAG, "Unable to note drag target change");
2585 }
Christopher Tatea53146c2010-09-07 11:57:52 -07002586 }
Chris Tated4533f12010-10-19 15:15:08 -07002587
2588 // Report the drop result if necessary
2589 if (what == DragEvent.ACTION_DROP) {
2590 try {
2591 Log.i(TAG, "Reporting drop result: " + result);
2592 sWindowSession.reportDropResult(mWindow, result);
2593 } catch (RemoteException e) {
2594 Log.e(TAG, "Unable to report drop result");
2595 }
2596 }
Christopher Tatea53146c2010-09-07 11:57:52 -07002597 }
2598 }
2599 event.recycle();
2600 }
2601
Christopher Tate2c095f32010-10-04 14:13:40 -07002602 public void getLastTouchPoint(Point outLocation) {
2603 outLocation.x = (int) mLastTouchPoint.x;
2604 outLocation.y = (int) mLastTouchPoint.y;
2605 }
2606
Chris Tate9d1ab882010-11-02 15:55:39 -07002607 public void setDragFocus(View newDragTarget) {
Christopher Tatea53146c2010-09-07 11:57:52 -07002608 if (mCurrentDragView != newDragTarget) {
Chris Tate048691c2010-10-12 17:39:18 -07002609 mCurrentDragView = newDragTarget;
Christopher Tatea53146c2010-09-07 11:57:52 -07002610 }
Christopher Tatea53146c2010-09-07 11:57:52 -07002611 }
2612
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002613 private AudioManager getAudioManager() {
2614 if (mView == null) {
2615 throw new IllegalStateException("getAudioManager called when there is no mView");
2616 }
2617 if (mAudioManager == null) {
2618 mAudioManager = (AudioManager) mView.getContext().getSystemService(Context.AUDIO_SERVICE);
2619 }
2620 return mAudioManager;
2621 }
2622
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002623 private int relayoutWindow(WindowManager.LayoutParams params, int viewVisibility,
2624 boolean insetsPending) throws RemoteException {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002625
2626 float appScale = mAttachInfo.mApplicationScale;
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002627 boolean restore = false;
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002628 if (params != null && mTranslator != null) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07002629 restore = true;
2630 params.backup();
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002631 mTranslator.translateWindowLayout(params);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002632 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002633 if (params != null) {
2634 if (DBG) Log.d(TAG, "WindowLayout in layoutWindow:" + params);
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002635 }
Dianne Hackborn694f79b2010-03-17 19:44:59 -07002636 mPendingConfiguration.seq = 0;
Dianne Hackbornf123e492010-09-24 11:16:23 -07002637 //Log.d(TAG, ">>>>>> CALLING relayout");
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002638 int relayoutResult = sWindowSession.relayout(
2639 mWindow, params,
Mitsuru Oshima61324e52009-07-21 15:40:36 -07002640 (int) (mView.mMeasuredWidth * appScale + 0.5f),
2641 (int) (mView.mMeasuredHeight * appScale + 0.5f),
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002642 viewVisibility, insetsPending, mWinFrame,
Dianne Hackborn694f79b2010-03-17 19:44:59 -07002643 mPendingContentInsets, mPendingVisibleInsets,
2644 mPendingConfiguration, mSurface);
Dianne Hackbornf123e492010-09-24 11:16:23 -07002645 //Log.d(TAG, "<<<<<< BACK FROM relayout");
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002646 if (restore) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07002647 params.restore();
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002648 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002649
2650 if (mTranslator != null) {
2651 mTranslator.translateRectInScreenToAppWinFrame(mWinFrame);
2652 mTranslator.translateRectInScreenToAppWindow(mPendingContentInsets);
2653 mTranslator.translateRectInScreenToAppWindow(mPendingVisibleInsets);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002654 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002655 return relayoutResult;
2656 }
Romain Guy8506ab42009-06-11 17:35:47 -07002657
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002658 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002659 * {@inheritDoc}
2660 */
2661 public void playSoundEffect(int effectId) {
2662 checkThread();
2663
Jean-Michel Trivi13b18fd2010-05-05 09:18:15 -07002664 try {
2665 final AudioManager audioManager = getAudioManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002666
Jean-Michel Trivi13b18fd2010-05-05 09:18:15 -07002667 switch (effectId) {
2668 case SoundEffectConstants.CLICK:
2669 audioManager.playSoundEffect(AudioManager.FX_KEY_CLICK);
2670 return;
2671 case SoundEffectConstants.NAVIGATION_DOWN:
2672 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_DOWN);
2673 return;
2674 case SoundEffectConstants.NAVIGATION_LEFT:
2675 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_LEFT);
2676 return;
2677 case SoundEffectConstants.NAVIGATION_RIGHT:
2678 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_RIGHT);
2679 return;
2680 case SoundEffectConstants.NAVIGATION_UP:
2681 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_UP);
2682 return;
2683 default:
2684 throw new IllegalArgumentException("unknown effect id " + effectId +
2685 " not defined in " + SoundEffectConstants.class.getCanonicalName());
2686 }
2687 } catch (IllegalStateException e) {
2688 // Exception thrown by getAudioManager() when mView is null
2689 Log.e(TAG, "FATAL EXCEPTION when attempting to play sound effect: " + e);
2690 e.printStackTrace();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002691 }
2692 }
2693
2694 /**
2695 * {@inheritDoc}
2696 */
2697 public boolean performHapticFeedback(int effectId, boolean always) {
2698 try {
2699 return sWindowSession.performHapticFeedback(mWindow, effectId, always);
2700 } catch (RemoteException e) {
2701 return false;
2702 }
2703 }
2704
2705 /**
2706 * {@inheritDoc}
2707 */
2708 public View focusSearch(View focused, int direction) {
2709 checkThread();
2710 if (!(mView instanceof ViewGroup)) {
2711 return null;
2712 }
2713 return FocusFinder.getInstance().findNextFocus((ViewGroup) mView, focused, direction);
2714 }
2715
2716 public void debug() {
2717 mView.debug();
2718 }
2719
2720 public void die(boolean immediate) {
Dianne Hackborn94d69142009-09-28 22:14:42 -07002721 if (immediate) {
2722 doDie();
2723 } else {
2724 sendEmptyMessage(DIE);
2725 }
2726 }
2727
2728 void doDie() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002729 checkThread();
Jeff Brownb75fa302010-07-15 23:47:29 -07002730 if (LOCAL_LOGV) Log.v(TAG, "DIE in " + this + " of " + mSurface);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002731 synchronized (this) {
2732 if (mAdded && !mFirst) {
Romain Guy29d89972010-09-22 16:10:57 -07002733 destroyHardwareRenderer();
2734
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002735 int viewVisibility = mView.getVisibility();
2736 boolean viewVisibilityChanged = mViewVisibility != viewVisibility;
2737 if (mWindowAttributesChanged || viewVisibilityChanged) {
2738 // If layout params have been changed, first give them
2739 // to the window manager to make sure it has the correct
2740 // animation info.
2741 try {
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002742 if ((relayoutWindow(mWindowAttributes, viewVisibility, false)
2743 & WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002744 sWindowSession.finishDrawing(mWindow);
2745 }
2746 } catch (RemoteException e) {
2747 }
2748 }
2749
Dianne Hackborn0586a1b2009-09-06 21:08:27 -07002750 mSurface.release();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002751 }
2752 if (mAdded) {
2753 mAdded = false;
Dianne Hackborn94d69142009-09-28 22:14:42 -07002754 dispatchDetachedFromWindow();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002755 }
2756 }
2757 }
2758
Romain Guy29d89972010-09-22 16:10:57 -07002759 private void destroyHardwareRenderer() {
Romain Guyb051e892010-09-28 19:09:36 -07002760 if (mAttachInfo.mHardwareRenderer != null) {
2761 mAttachInfo.mHardwareRenderer.destroy(true);
2762 mAttachInfo.mHardwareRenderer = null;
Romain Guy29d89972010-09-22 16:10:57 -07002763 mAttachInfo.mHardwareAccelerated = false;
2764 }
2765 }
2766
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002767 public void dispatchFinishedEvent(int seq, boolean handled) {
2768 Message msg = obtainMessage(FINISHED_EVENT);
2769 msg.arg1 = seq;
2770 msg.arg2 = handled ? 1 : 0;
2771 sendMessage(msg);
2772 }
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002773
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002774 public void dispatchResized(int w, int h, Rect coveredInsets,
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002775 Rect visibleInsets, boolean reportDraw, Configuration newConfig) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002776 if (DEBUG_LAYOUT) Log.v(TAG, "Resizing " + this + ": w=" + w
2777 + " h=" + h + " coveredInsets=" + coveredInsets.toShortString()
2778 + " visibleInsets=" + visibleInsets.toShortString()
2779 + " reportDraw=" + reportDraw);
2780 Message msg = obtainMessage(reportDraw ? RESIZED_REPORT :RESIZED);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002781 if (mTranslator != null) {
2782 mTranslator.translateRectInScreenToAppWindow(coveredInsets);
2783 mTranslator.translateRectInScreenToAppWindow(visibleInsets);
2784 w *= mTranslator.applicationInvertedScale;
2785 h *= mTranslator.applicationInvertedScale;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002786 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002787 msg.arg1 = w;
2788 msg.arg2 = h;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002789 ResizedInfo ri = new ResizedInfo();
2790 ri.coveredInsets = new Rect(coveredInsets);
2791 ri.visibleInsets = new Rect(visibleInsets);
2792 ri.newConfig = newConfig;
2793 msg.obj = ri;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002794 sendMessage(msg);
2795 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002796
Jeff Brown3915bb82010-11-05 15:02:16 -07002797 private InputQueue.FinishedCallback mFinishedCallback;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002798
2799 private final InputHandler mInputHandler = new InputHandler() {
Jeff Brown3915bb82010-11-05 15:02:16 -07002800 public void handleKey(KeyEvent event, InputQueue.FinishedCallback finishedCallback) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07002801 startInputEvent(finishedCallback);
Jeff Brown92ff1dd2010-08-11 16:16:06 -07002802 dispatchKey(event, true);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002803 }
2804
Jeff Brown3915bb82010-11-05 15:02:16 -07002805 public void handleMotion(MotionEvent event, InputQueue.FinishedCallback finishedCallback) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07002806 startInputEvent(finishedCallback);
2807 dispatchMotion(event, true);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002808 }
2809 };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002810
2811 public void dispatchKey(KeyEvent event) {
Jeff Brown92ff1dd2010-08-11 16:16:06 -07002812 dispatchKey(event, false);
2813 }
2814
2815 private void dispatchKey(KeyEvent event, boolean sendDone) {
2816 //noinspection ConstantConditions
2817 if (false && event.getAction() == KeyEvent.ACTION_DOWN) {
2818 if (event.getKeyCode() == KeyEvent.KEYCODE_CAMERA) {
Romain Guy812ccbe2010-06-01 14:07:24 -07002819 if (DBG) Log.d("keydisp", "===================================================");
2820 if (DBG) Log.d("keydisp", "Focused view Hierarchy is:");
2821
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002822 debug();
2823
Romain Guy812ccbe2010-06-01 14:07:24 -07002824 if (DBG) Log.d("keydisp", "===================================================");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002825 }
2826 }
2827
2828 Message msg = obtainMessage(DISPATCH_KEY);
2829 msg.obj = event;
Jeff Brown92ff1dd2010-08-11 16:16:06 -07002830 msg.arg1 = sendDone ? 1 : 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002831
2832 if (LOCAL_LOGV) Log.v(
Jeff Brownc5ed5912010-07-14 18:48:53 -07002833 TAG, "sending key " + event + " to " + mView);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002834
2835 sendMessageAtTime(msg, event.getEventTime());
2836 }
Jeff Brownc5ed5912010-07-14 18:48:53 -07002837
2838 public void dispatchMotion(MotionEvent event) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07002839 dispatchMotion(event, false);
2840 }
2841
2842 private void dispatchMotion(MotionEvent event, boolean sendDone) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07002843 int source = event.getSource();
2844 if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07002845 dispatchPointer(event, sendDone);
Jeff Brownc5ed5912010-07-14 18:48:53 -07002846 } else if ((source & InputDevice.SOURCE_CLASS_TRACKBALL) != 0) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07002847 dispatchTrackball(event, sendDone);
Jeff Brownc5ed5912010-07-14 18:48:53 -07002848 } else {
2849 // TODO
2850 Log.v(TAG, "Dropping unsupported motion event (unimplemented): " + event);
Jeff Brown93ed4e32010-09-23 13:51:48 -07002851 if (sendDone) {
Jeff Brown3915bb82010-11-05 15:02:16 -07002852 finishInputEvent(false);
Jeff Brown93ed4e32010-09-23 13:51:48 -07002853 }
Jeff Brownc5ed5912010-07-14 18:48:53 -07002854 }
2855 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002856
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002857 public void dispatchPointer(MotionEvent event) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07002858 dispatchPointer(event, false);
2859 }
2860
2861 private void dispatchPointer(MotionEvent event, boolean sendDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002862 Message msg = obtainMessage(DISPATCH_POINTER);
2863 msg.obj = event;
Jeff Brown93ed4e32010-09-23 13:51:48 -07002864 msg.arg1 = sendDone ? 1 : 0;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002865 sendMessageAtTime(msg, event.getEventTime());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002866 }
2867
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002868 public void dispatchTrackball(MotionEvent event) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07002869 dispatchTrackball(event, false);
2870 }
2871
2872 private void dispatchTrackball(MotionEvent event, boolean sendDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002873 Message msg = obtainMessage(DISPATCH_TRACKBALL);
2874 msg.obj = event;
Jeff Brown93ed4e32010-09-23 13:51:48 -07002875 msg.arg1 = sendDone ? 1 : 0;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002876 sendMessageAtTime(msg, event.getEventTime());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002877 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002878
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002879 public void dispatchAppVisibility(boolean visible) {
2880 Message msg = obtainMessage(DISPATCH_APP_VISIBILITY);
2881 msg.arg1 = visible ? 1 : 0;
2882 sendMessage(msg);
2883 }
2884
2885 public void dispatchGetNewSurface() {
2886 Message msg = obtainMessage(DISPATCH_GET_NEW_SURFACE);
2887 sendMessage(msg);
2888 }
2889
2890 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
2891 Message msg = Message.obtain();
2892 msg.what = WINDOW_FOCUS_CHANGED;
2893 msg.arg1 = hasFocus ? 1 : 0;
2894 msg.arg2 = inTouchMode ? 1 : 0;
2895 sendMessage(msg);
2896 }
2897
Dianne Hackbornffa42482009-09-23 22:20:11 -07002898 public void dispatchCloseSystemDialogs(String reason) {
2899 Message msg = Message.obtain();
2900 msg.what = CLOSE_SYSTEM_DIALOGS;
2901 msg.obj = reason;
2902 sendMessage(msg);
2903 }
Christopher Tatea53146c2010-09-07 11:57:52 -07002904
2905 public void dispatchDragEvent(DragEvent event) {
Chris Tate91e9bb32010-10-12 12:58:43 -07002906 final int what;
2907 if (event.getAction() == DragEvent.ACTION_DRAG_LOCATION) {
2908 what = DISPATCH_DRAG_LOCATION_EVENT;
2909 removeMessages(what);
2910 } else {
2911 what = DISPATCH_DRAG_EVENT;
2912 }
2913 Message msg = obtainMessage(what, event);
Christopher Tatea53146c2010-09-07 11:57:52 -07002914 sendMessage(msg);
2915 }
2916
svetoslavganov75986cf2009-05-14 22:28:01 -07002917 /**
2918 * The window is getting focus so if there is anything focused/selected
2919 * send an {@link AccessibilityEvent} to announce that.
2920 */
2921 private void sendAccessibilityEvents() {
2922 if (!AccessibilityManager.getInstance(mView.getContext()).isEnabled()) {
2923 return;
2924 }
2925 mView.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
2926 View focusedView = mView.findFocus();
2927 if (focusedView != null && focusedView != mView) {
2928 focusedView.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
2929 }
2930 }
2931
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002932 public boolean showContextMenuForChild(View originalView) {
2933 return false;
2934 }
2935
Adam Powell6e346362010-07-23 10:18:23 -07002936 public ActionMode startActionModeForChild(View originalView, ActionMode.Callback callback) {
2937 return null;
2938 }
2939
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002940 public void createContextMenu(ContextMenu menu) {
2941 }
2942
2943 public void childDrawableStateChanged(View child) {
2944 }
2945
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002946 void checkThread() {
2947 if (mThread != Thread.currentThread()) {
2948 throw new CalledFromWrongThreadException(
2949 "Only the original thread that created a view hierarchy can touch its views.");
2950 }
2951 }
2952
2953 public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
2954 // ViewRoot never intercepts touch event, so this can be a no-op
2955 }
2956
2957 public boolean requestChildRectangleOnScreen(View child, Rect rectangle,
2958 boolean immediate) {
2959 return scrollToRectOrFocus(rectangle, immediate);
2960 }
Romain Guy8506ab42009-06-11 17:35:47 -07002961
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07002962 class TakenSurfaceHolder extends BaseSurfaceHolder {
2963 @Override
2964 public boolean onAllowLockCanvas() {
2965 return mDrawingAllowed;
2966 }
2967
2968 @Override
2969 public void onRelayoutContainer() {
2970 // Not currently interesting -- from changing between fixed and layout size.
2971 }
2972
2973 public void setFormat(int format) {
2974 ((RootViewSurfaceTaker)mView).setSurfaceFormat(format);
2975 }
2976
2977 public void setType(int type) {
2978 ((RootViewSurfaceTaker)mView).setSurfaceType(type);
2979 }
2980
2981 @Override
2982 public void onUpdateSurface() {
2983 // We take care of format and type changes on our own.
2984 throw new IllegalStateException("Shouldn't be here");
2985 }
2986
2987 public boolean isCreating() {
2988 return mIsCreating;
2989 }
2990
2991 @Override
2992 public void setFixedSize(int width, int height) {
2993 throw new UnsupportedOperationException(
2994 "Currently only support sizing from layout");
2995 }
2996
2997 public void setKeepScreenOn(boolean screenOn) {
2998 ((RootViewSurfaceTaker)mView).setSurfaceKeepScreenOn(screenOn);
2999 }
3000 }
3001
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003002 static class InputMethodCallback extends IInputMethodCallback.Stub {
3003 private WeakReference<ViewRoot> mViewRoot;
3004
3005 public InputMethodCallback(ViewRoot viewRoot) {
3006 mViewRoot = new WeakReference<ViewRoot>(viewRoot);
3007 }
Romain Guy8506ab42009-06-11 17:35:47 -07003008
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003009 public void finishedEvent(int seq, boolean handled) {
3010 final ViewRoot viewRoot = mViewRoot.get();
3011 if (viewRoot != null) {
3012 viewRoot.dispatchFinishedEvent(seq, handled);
3013 }
3014 }
3015
3016 public void sessionCreated(IInputMethodSession session) throws RemoteException {
3017 // Stub -- not for use in the client.
3018 }
3019 }
Romain Guy8506ab42009-06-11 17:35:47 -07003020
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003021 static class W extends IWindow.Stub {
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07003022 private final WeakReference<ViewRoot> mViewRoot;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003023
Romain Guyfb8b7632010-08-23 21:05:08 -07003024 W(ViewRoot viewRoot) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003025 mViewRoot = new WeakReference<ViewRoot>(viewRoot);
3026 }
3027
Romain Guyfb8b7632010-08-23 21:05:08 -07003028 public void resized(int w, int h, Rect coveredInsets, Rect visibleInsets,
3029 boolean reportDraw, Configuration newConfig) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003030 final ViewRoot viewRoot = mViewRoot.get();
3031 if (viewRoot != null) {
Romain Guyfb8b7632010-08-23 21:05:08 -07003032 viewRoot.dispatchResized(w, h, coveredInsets, visibleInsets, reportDraw, newConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003033 }
3034 }
3035
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003036 public void dispatchAppVisibility(boolean visible) {
3037 final ViewRoot viewRoot = mViewRoot.get();
3038 if (viewRoot != null) {
3039 viewRoot.dispatchAppVisibility(visible);
3040 }
3041 }
3042
3043 public void dispatchGetNewSurface() {
3044 final ViewRoot viewRoot = mViewRoot.get();
3045 if (viewRoot != null) {
3046 viewRoot.dispatchGetNewSurface();
3047 }
3048 }
3049
3050 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
3051 final ViewRoot viewRoot = mViewRoot.get();
3052 if (viewRoot != null) {
3053 viewRoot.windowFocusChanged(hasFocus, inTouchMode);
3054 }
3055 }
3056
3057 private static int checkCallingPermission(String permission) {
3058 if (!Process.supportsProcesses()) {
3059 return PackageManager.PERMISSION_GRANTED;
3060 }
3061
3062 try {
3063 return ActivityManagerNative.getDefault().checkPermission(
3064 permission, Binder.getCallingPid(), Binder.getCallingUid());
3065 } catch (RemoteException e) {
3066 return PackageManager.PERMISSION_DENIED;
3067 }
3068 }
3069
3070 public void executeCommand(String command, String parameters, ParcelFileDescriptor out) {
3071 final ViewRoot viewRoot = mViewRoot.get();
3072 if (viewRoot != null) {
3073 final View view = viewRoot.mView;
3074 if (view != null) {
3075 if (checkCallingPermission(Manifest.permission.DUMP) !=
3076 PackageManager.PERMISSION_GRANTED) {
3077 throw new SecurityException("Insufficient permissions to invoke"
3078 + " executeCommand() from pid=" + Binder.getCallingPid()
3079 + ", uid=" + Binder.getCallingUid());
3080 }
3081
3082 OutputStream clientStream = null;
3083 try {
3084 clientStream = new ParcelFileDescriptor.AutoCloseOutputStream(out);
3085 ViewDebug.dispatchCommand(view, command, parameters, clientStream);
3086 } catch (IOException e) {
3087 e.printStackTrace();
3088 } finally {
3089 if (clientStream != null) {
3090 try {
3091 clientStream.close();
3092 } catch (IOException e) {
3093 e.printStackTrace();
3094 }
3095 }
3096 }
3097 }
3098 }
3099 }
Dianne Hackborn72c82ab2009-08-11 21:13:54 -07003100
Dianne Hackbornffa42482009-09-23 22:20:11 -07003101 public void closeSystemDialogs(String reason) {
3102 final ViewRoot viewRoot = mViewRoot.get();
3103 if (viewRoot != null) {
3104 viewRoot.dispatchCloseSystemDialogs(reason);
3105 }
3106 }
3107
Marco Nelissenbf6956b2009-11-09 15:21:13 -08003108 public void dispatchWallpaperOffsets(float x, float y, float xStep, float yStep,
3109 boolean sync) {
Dianne Hackborn19382ac2009-09-11 21:13:37 -07003110 if (sync) {
3111 try {
3112 sWindowSession.wallpaperOffsetsComplete(asBinder());
3113 } catch (RemoteException e) {
3114 }
3115 }
Dianne Hackborn72c82ab2009-08-11 21:13:54 -07003116 }
Dianne Hackborn75804932009-10-20 20:15:20 -07003117
3118 public void dispatchWallpaperCommand(String action, int x, int y,
3119 int z, Bundle extras, boolean sync) {
3120 if (sync) {
3121 try {
3122 sWindowSession.wallpaperCommandComplete(asBinder(), null);
3123 } catch (RemoteException e) {
3124 }
3125 }
3126 }
Christopher Tatea53146c2010-09-07 11:57:52 -07003127
3128 /* Drag/drop */
3129 public void dispatchDragEvent(DragEvent event) {
3130 final ViewRoot viewRoot = mViewRoot.get();
3131 if (viewRoot != null) {
3132 viewRoot.dispatchDragEvent(event);
3133 }
3134 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003135 }
3136
3137 /**
3138 * Maintains state information for a single trackball axis, generating
3139 * discrete (DPAD) movements based on raw trackball motion.
3140 */
3141 static final class TrackballAxis {
3142 /**
3143 * The maximum amount of acceleration we will apply.
3144 */
3145 static final float MAX_ACCELERATION = 20;
Romain Guy8506ab42009-06-11 17:35:47 -07003146
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003147 /**
3148 * The maximum amount of time (in milliseconds) between events in order
3149 * for us to consider the user to be doing fast trackball movements,
3150 * and thus apply an acceleration.
3151 */
3152 static final long FAST_MOVE_TIME = 150;
Romain Guy8506ab42009-06-11 17:35:47 -07003153
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003154 /**
3155 * Scaling factor to the time (in milliseconds) between events to how
3156 * much to multiple/divide the current acceleration. When movement
3157 * is < FAST_MOVE_TIME this multiplies the acceleration; when >
3158 * FAST_MOVE_TIME it divides it.
3159 */
3160 static final float ACCEL_MOVE_SCALING_FACTOR = (1.0f/40);
Romain Guy8506ab42009-06-11 17:35:47 -07003161
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003162 float position;
3163 float absPosition;
3164 float acceleration = 1;
3165 long lastMoveTime = 0;
3166 int step;
3167 int dir;
3168 int nonAccelMovement;
3169
3170 void reset(int _step) {
3171 position = 0;
3172 acceleration = 1;
3173 lastMoveTime = 0;
3174 step = _step;
3175 dir = 0;
3176 }
3177
3178 /**
3179 * Add trackball movement into the state. If the direction of movement
3180 * has been reversed, the state is reset before adding the
3181 * movement (so that you don't have to compensate for any previously
3182 * collected movement before see the result of the movement in the
3183 * new direction).
3184 *
3185 * @return Returns the absolute value of the amount of movement
3186 * collected so far.
3187 */
3188 float collect(float off, long time, String axis) {
3189 long normTime;
3190 if (off > 0) {
3191 normTime = (long)(off * FAST_MOVE_TIME);
3192 if (dir < 0) {
3193 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to positive!");
3194 position = 0;
3195 step = 0;
3196 acceleration = 1;
3197 lastMoveTime = 0;
3198 }
3199 dir = 1;
3200 } else if (off < 0) {
3201 normTime = (long)((-off) * FAST_MOVE_TIME);
3202 if (dir > 0) {
3203 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to negative!");
3204 position = 0;
3205 step = 0;
3206 acceleration = 1;
3207 lastMoveTime = 0;
3208 }
3209 dir = -1;
3210 } else {
3211 normTime = 0;
3212 }
Romain Guy8506ab42009-06-11 17:35:47 -07003213
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003214 // The number of milliseconds between each movement that is
3215 // considered "normal" and will not result in any acceleration
3216 // or deceleration, scaled by the offset we have here.
3217 if (normTime > 0) {
3218 long delta = time - lastMoveTime;
3219 lastMoveTime = time;
3220 float acc = acceleration;
3221 if (delta < normTime) {
3222 // The user is scrolling rapidly, so increase acceleration.
3223 float scale = (normTime-delta) * ACCEL_MOVE_SCALING_FACTOR;
3224 if (scale > 1) acc *= scale;
3225 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " accelerate: off="
3226 + off + " normTime=" + normTime + " delta=" + delta
3227 + " scale=" + scale + " acc=" + acc);
3228 acceleration = acc < MAX_ACCELERATION ? acc : MAX_ACCELERATION;
3229 } else {
3230 // The user is scrolling slowly, so decrease acceleration.
3231 float scale = (delta-normTime) * ACCEL_MOVE_SCALING_FACTOR;
3232 if (scale > 1) acc /= scale;
3233 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " deccelerate: off="
3234 + off + " normTime=" + normTime + " delta=" + delta
3235 + " scale=" + scale + " acc=" + acc);
3236 acceleration = acc > 1 ? acc : 1;
3237 }
3238 }
3239 position += off;
3240 return (absPosition = Math.abs(position));
3241 }
3242
3243 /**
3244 * Generate the number of discrete movement events appropriate for
3245 * the currently collected trackball movement.
3246 *
3247 * @param precision The minimum movement required to generate the
3248 * first discrete movement.
3249 *
3250 * @return Returns the number of discrete movements, either positive
3251 * or negative, or 0 if there is not enough trackball movement yet
3252 * for a discrete movement.
3253 */
3254 int generate(float precision) {
3255 int movement = 0;
3256 nonAccelMovement = 0;
3257 do {
3258 final int dir = position >= 0 ? 1 : -1;
3259 switch (step) {
3260 // If we are going to execute the first step, then we want
3261 // to do this as soon as possible instead of waiting for
3262 // a full movement, in order to make things look responsive.
3263 case 0:
3264 if (absPosition < precision) {
3265 return movement;
3266 }
3267 movement += dir;
3268 nonAccelMovement += dir;
3269 step = 1;
3270 break;
3271 // If we have generated the first movement, then we need
3272 // to wait for the second complete trackball motion before
3273 // generating the second discrete movement.
3274 case 1:
3275 if (absPosition < 2) {
3276 return movement;
3277 }
3278 movement += dir;
3279 nonAccelMovement += dir;
3280 position += dir > 0 ? -2 : 2;
3281 absPosition = Math.abs(position);
3282 step = 2;
3283 break;
3284 // After the first two, we generate discrete movements
3285 // consistently with the trackball, applying an acceleration
3286 // if the trackball is moving quickly. This is a simple
3287 // acceleration on top of what we already compute based
3288 // on how quickly the wheel is being turned, to apply
3289 // a longer increasing acceleration to continuous movement
3290 // in one direction.
3291 default:
3292 if (absPosition < 1) {
3293 return movement;
3294 }
3295 movement += dir;
3296 position += dir >= 0 ? -1 : 1;
3297 absPosition = Math.abs(position);
3298 float acc = acceleration;
3299 acc *= 1.1f;
3300 acceleration = acc < MAX_ACCELERATION ? acc : acceleration;
3301 break;
3302 }
3303 } while (true);
3304 }
3305 }
3306
3307 public static final class CalledFromWrongThreadException extends AndroidRuntimeException {
3308 public CalledFromWrongThreadException(String msg) {
3309 super(msg);
3310 }
3311 }
3312
3313 private SurfaceHolder mHolder = new SurfaceHolder() {
3314 // we only need a SurfaceHolder for opengl. it would be nice
3315 // to implement everything else though, especially the callback
3316 // support (opengl doesn't make use of it right now, but eventually
3317 // will).
3318 public Surface getSurface() {
3319 return mSurface;
3320 }
3321
3322 public boolean isCreating() {
3323 return false;
3324 }
3325
3326 public void addCallback(Callback callback) {
3327 }
3328
3329 public void removeCallback(Callback callback) {
3330 }
3331
3332 public void setFixedSize(int width, int height) {
3333 }
3334
3335 public void setSizeFromLayout() {
3336 }
3337
3338 public void setFormat(int format) {
3339 }
3340
3341 public void setType(int type) {
3342 }
3343
3344 public void setKeepScreenOn(boolean screenOn) {
3345 }
3346
3347 public Canvas lockCanvas() {
3348 return null;
3349 }
3350
3351 public Canvas lockCanvas(Rect dirty) {
3352 return null;
3353 }
3354
3355 public void unlockCanvasAndPost(Canvas canvas) {
3356 }
3357 public Rect getSurfaceFrame() {
3358 return null;
3359 }
3360 };
3361
3362 static RunQueue getRunQueue() {
3363 RunQueue rq = sRunQueues.get();
3364 if (rq != null) {
3365 return rq;
3366 }
3367 rq = new RunQueue();
3368 sRunQueues.set(rq);
3369 return rq;
3370 }
Romain Guy8506ab42009-06-11 17:35:47 -07003371
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003372 /**
3373 * @hide
3374 */
3375 static final class RunQueue {
3376 private final ArrayList<HandlerAction> mActions = new ArrayList<HandlerAction>();
3377
3378 void post(Runnable action) {
3379 postDelayed(action, 0);
3380 }
3381
3382 void postDelayed(Runnable action, long delayMillis) {
3383 HandlerAction handlerAction = new HandlerAction();
3384 handlerAction.action = action;
3385 handlerAction.delay = delayMillis;
3386
3387 synchronized (mActions) {
3388 mActions.add(handlerAction);
3389 }
3390 }
3391
3392 void removeCallbacks(Runnable action) {
3393 final HandlerAction handlerAction = new HandlerAction();
3394 handlerAction.action = action;
3395
3396 synchronized (mActions) {
3397 final ArrayList<HandlerAction> actions = mActions;
3398
3399 while (actions.remove(handlerAction)) {
3400 // Keep going
3401 }
3402 }
3403 }
3404
3405 void executeActions(Handler handler) {
3406 synchronized (mActions) {
3407 final ArrayList<HandlerAction> actions = mActions;
3408 final int count = actions.size();
3409
3410 for (int i = 0; i < count; i++) {
3411 final HandlerAction handlerAction = actions.get(i);
3412 handler.postDelayed(handlerAction.action, handlerAction.delay);
3413 }
3414
Romain Guy15df6702009-08-17 20:17:30 -07003415 actions.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003416 }
3417 }
3418
3419 private static class HandlerAction {
3420 Runnable action;
3421 long delay;
3422
3423 @Override
3424 public boolean equals(Object o) {
3425 if (this == o) return true;
3426 if (o == null || getClass() != o.getClass()) return false;
3427
3428 HandlerAction that = (HandlerAction) o;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003429 return !(action != null ? !action.equals(that.action) : that.action != null);
3430
3431 }
3432
3433 @Override
3434 public int hashCode() {
3435 int result = action != null ? action.hashCode() : 0;
3436 result = 31 * result + (int) (delay ^ (delay >>> 32));
3437 return result;
3438 }
3439 }
3440 }
3441
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003442 private static native void nativeShowFPS(Canvas canvas, int durationMillis);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003443}