blob: 5b18715de8ca07a582893667ca663f522bd1cb4c [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;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080056import android.view.View.MeasureSpec;
svetoslavganov75986cf2009-05-14 22:28:01 -070057import android.view.accessibility.AccessibilityEvent;
58import android.view.accessibility.AccessibilityManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080059import android.view.inputmethod.InputConnection;
60import android.view.inputmethod.InputMethodManager;
61import android.widget.Scroller;
Joe Onorato86f67862010-11-05 18:57:34 -070062import com.android.internal.policy.PolicyManager;
Romain Guy6b7bd242010-10-06 19:49:23 -070063import com.android.internal.view.BaseSurfaceHolder;
64import com.android.internal.view.IInputMethodCallback;
65import com.android.internal.view.IInputMethodSession;
66import com.android.internal.view.RootViewSurfaceTaker;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080067
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080068import java.io.IOException;
69import java.io.OutputStream;
Romain Guy6b7bd242010-10-06 19:49:23 -070070import java.lang.ref.WeakReference;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080071import java.util.ArrayList;
72
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080073/**
74 * The top of a view hierarchy, implementing the needed protocol between View
75 * and the WindowManager. This is for the most part an internal implementation
76 * detail of {@link WindowManagerImpl}.
77 *
78 * {@hide}
79 */
Romain Guy812ccbe2010-06-01 14:07:24 -070080@SuppressWarnings({"EmptyCatchBlock", "PointlessBooleanExpression"})
81public final class ViewRoot extends Handler implements ViewParent, View.AttachInfo.Callbacks {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080082 private static final String TAG = "ViewRoot";
83 private static final boolean DBG = false;
Mike Reedfd716532009-10-12 14:42:56 -040084 private static final boolean SHOW_FPS = false;
Romain Guy812ccbe2010-06-01 14:07:24 -070085 private static final boolean LOCAL_LOGV = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080086 /** @noinspection PointlessBooleanExpression*/
87 private static final boolean DEBUG_DRAW = false || LOCAL_LOGV;
88 private static final boolean DEBUG_LAYOUT = false || LOCAL_LOGV;
Christopher Tatefa9e7c02010-05-06 12:07:10 -070089 private static final boolean DEBUG_INPUT = true || LOCAL_LOGV;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080090 private static final boolean DEBUG_INPUT_RESIZE = false || LOCAL_LOGV;
91 private static final boolean DEBUG_ORIENTATION = false || LOCAL_LOGV;
92 private static final boolean DEBUG_TRACKBALL = false || LOCAL_LOGV;
93 private static final boolean DEBUG_IMF = false || LOCAL_LOGV;
Dianne Hackborn694f79b2010-03-17 19:44:59 -070094 private static final boolean DEBUG_CONFIGURATION = false || LOCAL_LOGV;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080095 private static final boolean WATCH_POINTER = false;
96
Michael Chan53071d62009-05-13 17:29:48 -070097 private static final boolean MEASURE_LATENCY = false;
98 private static LatencyTimer lt;
99
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800100 /**
101 * Maximum time we allow the user to roll the trackball enough to generate
102 * a key event, before resetting the counters.
103 */
104 static final int MAX_TRACKBALL_DELAY = 250;
105
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800106 static IWindowSession sWindowSession;
107
108 static final Object mStaticInit = new Object();
109 static boolean mInitialized = false;
110
111 static final ThreadLocal<RunQueue> sRunQueues = new ThreadLocal<RunQueue>();
112
Dianne Hackborn2a9094d2010-02-03 19:20:09 -0800113 static final ArrayList<Runnable> sFirstDrawHandlers = new ArrayList<Runnable>();
114 static boolean sFirstDrawComplete = false;
115
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800116 static final ArrayList<ComponentCallbacks> sConfigCallbacks
117 = new ArrayList<ComponentCallbacks>();
118
Romain Guy8506ab42009-06-11 17:35:47 -0700119 private static int sDrawTime;
Romain Guy13922e02009-05-12 17:56:14 -0700120
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800121 long mLastTrackballTime = 0;
122 final TrackballAxis mTrackballAxisX = new TrackballAxis();
123 final TrackballAxis mTrackballAxisY = new TrackballAxis();
124
125 final int[] mTmpLocation = new int[2];
Romain Guy8506ab42009-06-11 17:35:47 -0700126
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800127 final InputMethodCallback mInputMethodCallback;
128 final SparseArray<Object> mPendingEvents = new SparseArray<Object>();
129 int mPendingEventSeq = 0;
Romain Guy8506ab42009-06-11 17:35:47 -0700130
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800131 final Thread mThread;
132
133 final WindowLeaked mLocation;
134
135 final WindowManager.LayoutParams mWindowAttributes = new WindowManager.LayoutParams();
136
137 final W mWindow;
138
139 View mView;
140 View mFocusedView;
141 View mRealFocusedView; // this is not set to null in touch mode
142 int mViewVisibility;
143 boolean mAppVisible = true;
144
Dianne Hackbornd76b67c2010-07-13 17:48:30 -0700145 SurfaceHolder.Callback2 mSurfaceHolderCallback;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700146 BaseSurfaceHolder mSurfaceHolder;
147 boolean mIsCreating;
148 boolean mDrawingAllowed;
149
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800150 final Region mTransparentRegion;
151 final Region mPreviousTransparentRegion;
152
153 int mWidth;
154 int mHeight;
155 Rect mDirty; // will be a graphics.Region soon
Romain Guybb93d552009-03-24 21:04:15 -0700156 boolean mIsAnimating;
Romain Guy8506ab42009-06-11 17:35:47 -0700157
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700158 CompatibilityInfo.Translator mTranslator;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800159
160 final View.AttachInfo mAttachInfo;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700161 InputChannel mInputChannel;
Dianne Hackborn1e4b9f32010-06-23 14:10:57 -0700162 InputQueue.Callback mInputQueueCallback;
163 InputQueue mInputQueue;
Joe Onorato86f67862010-11-05 18:57:34 -0700164 FallbackEventHandler mFallbackEventHandler;
Dianne Hackborna95e4cb2010-06-18 18:09:33 -0700165
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800166 final Rect mTempRect; // used in the transaction to not thrash the heap.
167 final Rect mVisRect; // used to retrieve visible rect of focused view.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800168
169 boolean mTraversalScheduled;
170 boolean mWillDrawSoon;
171 boolean mLayoutRequested;
172 boolean mFirst;
173 boolean mReportNextDraw;
174 boolean mFullRedrawNeeded;
175 boolean mNewSurfaceNeeded;
176 boolean mHasHadWindowFocus;
177 boolean mLastWasImTarget;
178
179 boolean mWindowAttributesChanged = false;
180
181 // These can be accessed by any thread, must be protected with a lock.
Mathias Agopian5583dc62009-07-09 16:28:11 -0700182 // Surface can never be reassigned or cleared (use Surface.clear()).
183 private final Surface mSurface = new Surface();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800184
185 boolean mAdded;
186 boolean mAddedTouchMode;
187
188 /*package*/ int mAddNesting;
189
190 // These are accessed by multiple threads.
191 final Rect mWinFrame; // frame given by window manager.
192
193 final Rect mPendingVisibleInsets = new Rect();
194 final Rect mPendingContentInsets = new Rect();
195 final ViewTreeObserver.InternalInsetsInfo mLastGivenInsets
196 = new ViewTreeObserver.InternalInsetsInfo();
197
Dianne Hackborn694f79b2010-03-17 19:44:59 -0700198 final Configuration mLastConfiguration = new Configuration();
199 final Configuration mPendingConfiguration = new Configuration();
200
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800201 class ResizedInfo {
202 Rect coveredInsets;
203 Rect visibleInsets;
204 Configuration newConfig;
205 }
206
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800207 boolean mScrollMayChange;
208 int mSoftInputMode;
209 View mLastScrolledFocus;
210 int mScrollY;
211 int mCurScrollY;
212 Scroller mScroller;
Romain Guy8506ab42009-06-11 17:35:47 -0700213
Romain Guy8506ab42009-06-11 17:35:47 -0700214 final ViewConfiguration mViewConfiguration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800215
Christopher Tatea53146c2010-09-07 11:57:52 -0700216 /* Drag/drop */
217 ClipDescription mDragDescription;
218 View mCurrentDragView;
219 final PointF mDragPoint = new PointF();
Christopher Tate2c095f32010-10-04 14:13:40 -0700220 final PointF mLastTouchPoint = new PointF();
Christopher Tatea53146c2010-09-07 11:57:52 -0700221
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800222 /**
223 * see {@link #playSoundEffect(int)}
224 */
225 AudioManager mAudioManager;
226
Dianne Hackborn11ea3342009-07-22 21:48:55 -0700227 private final int mDensity;
Adam Powellb08013c2010-09-16 16:28:11 -0700228
Dianne Hackborn4c62fc02009-08-08 20:40:27 -0700229 public static IWindowSession getWindowSession(Looper mainLooper) {
230 synchronized (mStaticInit) {
231 if (!mInitialized) {
232 try {
233 InputMethodManager imm = InputMethodManager.getInstance(mainLooper);
234 sWindowSession = IWindowManager.Stub.asInterface(
235 ServiceManager.getService("window"))
236 .openSession(imm.getClient(), imm.getInputContext());
237 mInitialized = true;
238 } catch (RemoteException e) {
239 }
240 }
241 return sWindowSession;
242 }
243 }
244
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800245 public ViewRoot(Context context) {
246 super();
247
Romain Guy812ccbe2010-06-01 14:07:24 -0700248 if (MEASURE_LATENCY) {
249 if (lt == null) {
250 lt = new LatencyTimer(100, 1000);
251 }
Michael Chan53071d62009-05-13 17:29:48 -0700252 }
253
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800254 // Initialize the statics when this class is first instantiated. This is
255 // done here instead of in the static block because Zygote does not
256 // allow the spawning of threads.
Dianne Hackborn4c62fc02009-08-08 20:40:27 -0700257 getWindowSession(context.getMainLooper());
258
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800259 mThread = Thread.currentThread();
260 mLocation = new WindowLeaked(null);
261 mLocation.fillInStackTrace();
262 mWidth = -1;
263 mHeight = -1;
264 mDirty = new Rect();
265 mTempRect = new Rect();
266 mVisRect = new Rect();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800267 mWinFrame = new Rect();
Romain Guyfb8b7632010-08-23 21:05:08 -0700268 mWindow = new W(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800269 mInputMethodCallback = new InputMethodCallback(this);
270 mViewVisibility = View.GONE;
271 mTransparentRegion = new Region();
272 mPreviousTransparentRegion = new Region();
273 mFirst = true; // true for the first time the view is added
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800274 mAdded = false;
275 mAttachInfo = new View.AttachInfo(sWindowSession, mWindow, this, this);
276 mViewConfiguration = ViewConfiguration.get(context);
Dianne Hackborn11ea3342009-07-22 21:48:55 -0700277 mDensity = context.getResources().getDisplayMetrics().densityDpi;
Joe Onorato86f67862010-11-05 18:57:34 -0700278 mFallbackEventHandler = PolicyManager.makeNewFallbackEventHandler(context);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800279 }
280
Dianne Hackborn2a9094d2010-02-03 19:20:09 -0800281 public static void addFirstDrawHandler(Runnable callback) {
282 synchronized (sFirstDrawHandlers) {
283 if (!sFirstDrawComplete) {
284 sFirstDrawHandlers.add(callback);
285 }
286 }
287 }
288
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800289 public static void addConfigCallback(ComponentCallbacks callback) {
290 synchronized (sConfigCallbacks) {
291 sConfigCallbacks.add(callback);
292 }
293 }
294
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800295 // FIXME for perf testing only
296 private boolean mProfile = false;
297
298 /**
299 * Call this to profile the next traversal call.
300 * FIXME for perf testing only. Remove eventually
301 */
302 public void profile() {
303 mProfile = true;
304 }
305
306 /**
307 * Indicates whether we are in touch mode. Calling this method triggers an IPC
308 * call and should be avoided whenever possible.
309 *
310 * @return True, if the device is in touch mode, false otherwise.
311 *
312 * @hide
313 */
314 static boolean isInTouchMode() {
315 if (mInitialized) {
316 try {
317 return sWindowSession.getInTouchMode();
318 } catch (RemoteException e) {
319 }
320 }
321 return false;
322 }
323
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800324 /**
325 * We have one child
326 */
Romain Guye4d01122010-06-16 18:44:05 -0700327 public void setView(View view, WindowManager.LayoutParams attrs, View panelParentView) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800328 synchronized (this) {
329 if (mView == null) {
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700330 mView = view;
Joe Onorato86f67862010-11-05 18:57:34 -0700331 mFallbackEventHandler.setView(view);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700332 mWindowAttributes.copyFrom(attrs);
Mitsuru Oshima1ecf5d22009-07-06 17:20:38 -0700333 attrs = mWindowAttributes;
Romain Guye4d01122010-06-16 18:44:05 -0700334
Romain Guy529b60a2010-08-03 18:05:47 -0700335 enableHardwareAcceleration(attrs);
Romain Guye4d01122010-06-16 18:44:05 -0700336
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700337 if (view instanceof RootViewSurfaceTaker) {
338 mSurfaceHolderCallback =
339 ((RootViewSurfaceTaker)view).willYouTakeTheSurface();
340 if (mSurfaceHolderCallback != null) {
341 mSurfaceHolder = new TakenSurfaceHolder();
Dianne Hackborn289b9b62010-07-09 11:44:11 -0700342 mSurfaceHolder.setFormat(PixelFormat.UNKNOWN);
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700343 }
344 }
Mitsuru Oshima38ed7d772009-07-21 14:39:34 -0700345 Resources resources = mView.getContext().getResources();
346 CompatibilityInfo compatibilityInfo = resources.getCompatibilityInfo();
Mitsuru Oshima589cebe2009-07-22 20:38:58 -0700347 mTranslator = compatibilityInfo.getTranslator();
Mitsuru Oshima38ed7d772009-07-21 14:39:34 -0700348
349 if (mTranslator != null || !compatibilityInfo.supportsScreen()) {
Mitsuru Oshima240f8a72009-07-22 20:39:14 -0700350 mSurface.setCompatibleDisplayMetrics(resources.getDisplayMetrics(),
351 mTranslator);
Mitsuru Oshima38ed7d772009-07-21 14:39:34 -0700352 }
353
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -0700354 boolean restore = false;
Romain Guy35b38ce2009-10-07 13:38:55 -0700355 if (mTranslator != null) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -0700356 restore = true;
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700357 attrs.backup();
358 mTranslator.translateWindowLayout(attrs);
Mitsuru Oshima3d914922009-05-13 22:29:15 -0700359 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700360 if (DEBUG_LAYOUT) Log.d(TAG, "WindowLayout in setView:" + attrs);
361
Mitsuru Oshima1ecf5d22009-07-06 17:20:38 -0700362 if (!compatibilityInfo.supportsScreen()) {
363 attrs.flags |= WindowManager.LayoutParams.FLAG_COMPATIBLE_WINDOW;
364 }
365
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800366 mSoftInputMode = attrs.softInputMode;
367 mWindowAttributesChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800368 mAttachInfo.mRootView = view;
Romain Guy35b38ce2009-10-07 13:38:55 -0700369 mAttachInfo.mScalingRequired = mTranslator != null;
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700370 mAttachInfo.mApplicationScale =
371 mTranslator == null ? 1.0f : mTranslator.applicationScale;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800372 if (panelParentView != null) {
373 mAttachInfo.mPanelParentWindowToken
374 = panelParentView.getApplicationWindowToken();
375 }
376 mAdded = true;
377 int res; /* = WindowManagerImpl.ADD_OKAY; */
Romain Guy8506ab42009-06-11 17:35:47 -0700378
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800379 // Schedule the first layout -before- adding to the window
380 // manager, to make sure we do the relayout before receiving
381 // any other events from the system.
382 requestLayout();
Jeff Brown46b9ac02010-04-22 18:58:52 -0700383 mInputChannel = new InputChannel();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800384 try {
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700385 res = sWindowSession.add(mWindow, mWindowAttributes,
Jeff Brown46b9ac02010-04-22 18:58:52 -0700386 getHostVisibility(), mAttachInfo.mContentInsets,
387 mInputChannel);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800388 } catch (RemoteException e) {
389 mAdded = false;
390 mView = null;
391 mAttachInfo.mRootView = null;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700392 mInputChannel = null;
Joe Onorato86f67862010-11-05 18:57:34 -0700393 mFallbackEventHandler.setView(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800394 unscheduleTraversals();
395 throw new RuntimeException("Adding window failed", e);
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700396 } finally {
397 if (restore) {
398 attrs.restore();
399 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800400 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700401
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700402 if (mTranslator != null) {
403 mTranslator.translateRectInScreenToAppWindow(mAttachInfo.mContentInsets);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700404 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800405 mPendingContentInsets.set(mAttachInfo.mContentInsets);
406 mPendingVisibleInsets.set(0, 0, 0, 0);
Jeff Brownc5ed5912010-07-14 18:48:53 -0700407 if (Config.LOGV) Log.v(TAG, "Added window " + mWindow);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800408 if (res < WindowManagerImpl.ADD_OKAY) {
409 mView = null;
410 mAttachInfo.mRootView = null;
411 mAdded = false;
Joe Onorato86f67862010-11-05 18:57:34 -0700412 mFallbackEventHandler.setView(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800413 unscheduleTraversals();
414 switch (res) {
415 case WindowManagerImpl.ADD_BAD_APP_TOKEN:
416 case WindowManagerImpl.ADD_BAD_SUBWINDOW_TOKEN:
417 throw new WindowManagerImpl.BadTokenException(
418 "Unable to add window -- token " + attrs.token
419 + " is not valid; is your activity running?");
420 case WindowManagerImpl.ADD_NOT_APP_TOKEN:
421 throw new WindowManagerImpl.BadTokenException(
422 "Unable to add window -- token " + attrs.token
423 + " is not for an application");
424 case WindowManagerImpl.ADD_APP_EXITING:
425 throw new WindowManagerImpl.BadTokenException(
426 "Unable to add window -- app for token " + attrs.token
427 + " is exiting");
428 case WindowManagerImpl.ADD_DUPLICATE_ADD:
429 throw new WindowManagerImpl.BadTokenException(
430 "Unable to add window -- window " + mWindow
431 + " has already been added");
432 case WindowManagerImpl.ADD_STARTING_NOT_NEEDED:
433 // Silently ignore -- we would have just removed it
434 // right away, anyway.
435 return;
436 case WindowManagerImpl.ADD_MULTIPLE_SINGLETON:
437 throw new WindowManagerImpl.BadTokenException(
438 "Unable to add window " + mWindow +
439 " -- another window of this type already exists");
440 case WindowManagerImpl.ADD_PERMISSION_DENIED:
441 throw new WindowManagerImpl.BadTokenException(
442 "Unable to add window " + mWindow +
443 " -- permission denied for this window type");
444 }
445 throw new RuntimeException(
446 "Unable to add window -- unknown error code " + res);
447 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700448
Jeff Brown00fa7bd2010-07-02 15:37:36 -0700449 if (view instanceof RootViewSurfaceTaker) {
450 mInputQueueCallback =
451 ((RootViewSurfaceTaker)view).willYouTakeTheInputQueue();
452 }
453 if (mInputQueueCallback != null) {
454 mInputQueue = new InputQueue(mInputChannel);
455 mInputQueueCallback.onInputQueueCreated(mInputQueue);
456 } else {
457 InputQueue.registerInputChannel(mInputChannel, mInputHandler,
458 Looper.myQueue());
Jeff Brown46b9ac02010-04-22 18:58:52 -0700459 }
460
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800461 view.assignParent(this);
462 mAddedTouchMode = (res&WindowManagerImpl.ADD_FLAG_IN_TOUCH_MODE) != 0;
463 mAppVisible = (res&WindowManagerImpl.ADD_FLAG_APP_VISIBLE) != 0;
464 }
465 }
466 }
467
Romain Guy529b60a2010-08-03 18:05:47 -0700468 private void enableHardwareAcceleration(WindowManager.LayoutParams attrs) {
Romain Guye4d01122010-06-16 18:44:05 -0700469 // Only enable hardware acceleration if we are not in the system process
470 // The window manager creates ViewRoots to display animated preview windows
471 // of launching apps and we don't want those to be hardware accelerated
Romain Guy52339202010-09-03 16:04:46 -0700472 if (!HardwareRenderer.sRendererDisabled) {
Romain Guye4d01122010-06-16 18:44:05 -0700473 // Try to enable hardware acceleration if requested
Romain Guy529b60a2010-08-03 18:05:47 -0700474 if (attrs != null &&
475 (attrs.flags & WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED) != 0) {
Romain Guye4d01122010-06-16 18:44:05 -0700476 final boolean translucent = attrs.format != PixelFormat.OPAQUE;
Romain Guyb051e892010-09-28 19:09:36 -0700477 if (mAttachInfo.mHardwareRenderer != null) {
478 mAttachInfo.mHardwareRenderer.destroy(true);
Romain Guy4caa4ed2010-08-25 14:46:24 -0700479 }
Romain Guyb051e892010-09-28 19:09:36 -0700480 mAttachInfo.mHardwareRenderer = HardwareRenderer.createGlRenderer(2, translucent);
Romain Guy53ca03d2010-10-08 18:55:27 -0700481 mAttachInfo.mHardwareAccelerated = mAttachInfo.mHardwareRenderer != null;
Romain Guye4d01122010-06-16 18:44:05 -0700482 }
483 }
484 }
485
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800486 public View getView() {
487 return mView;
488 }
489
490 final WindowLeaked getLocation() {
491 return mLocation;
492 }
493
494 void setLayoutParams(WindowManager.LayoutParams attrs, boolean newView) {
495 synchronized (this) {
The Android Open Source Project10592532009-03-18 17:39:46 -0700496 int oldSoftInputMode = mWindowAttributes.softInputMode;
Mitsuru Oshima5a2b91d2009-07-16 16:30:02 -0700497 // preserve compatible window flag if exists.
498 int compatibleWindowFlag =
499 mWindowAttributes.flags & WindowManager.LayoutParams.FLAG_COMPATIBLE_WINDOW;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800500 mWindowAttributes.copyFrom(attrs);
Mitsuru Oshima5a2b91d2009-07-16 16:30:02 -0700501 mWindowAttributes.flags |= compatibleWindowFlag;
502
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800503 if (newView) {
504 mSoftInputMode = attrs.softInputMode;
505 requestLayout();
506 }
The Android Open Source Project10592532009-03-18 17:39:46 -0700507 // Don't lose the mode we last auto-computed.
508 if ((attrs.softInputMode&WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST)
509 == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED) {
510 mWindowAttributes.softInputMode = (mWindowAttributes.softInputMode
511 & ~WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST)
512 | (oldSoftInputMode
513 & WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST);
514 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800515 mWindowAttributesChanged = true;
516 scheduleTraversals();
517 }
518 }
519
520 void handleAppVisibility(boolean visible) {
521 if (mAppVisible != visible) {
522 mAppVisible = visible;
523 scheduleTraversals();
524 }
525 }
526
527 void handleGetNewSurface() {
528 mNewSurfaceNeeded = true;
529 mFullRedrawNeeded = true;
530 scheduleTraversals();
531 }
532
533 /**
534 * {@inheritDoc}
535 */
536 public void requestLayout() {
537 checkThread();
538 mLayoutRequested = true;
539 scheduleTraversals();
540 }
541
542 /**
543 * {@inheritDoc}
544 */
545 public boolean isLayoutRequested() {
546 return mLayoutRequested;
547 }
548
549 public void invalidateChild(View child, Rect dirty) {
550 checkThread();
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700551 if (DEBUG_DRAW) Log.v(TAG, "Invalidate child: " + dirty);
Chet Haase70d4ba12010-10-06 09:46:45 -0700552 if (dirty == null) {
553 // Fast invalidation for GL-enabled applications; GL must redraw everything
554 invalidate();
555 return;
556 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700557 if (mCurScrollY != 0 || mTranslator != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800558 mTempRect.set(dirty);
Romain Guy1e095972009-07-07 11:22:45 -0700559 dirty = mTempRect;
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700560 if (mCurScrollY != 0) {
Romain Guy1e095972009-07-07 11:22:45 -0700561 dirty.offset(0, -mCurScrollY);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700562 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700563 if (mTranslator != null) {
Romain Guy1e095972009-07-07 11:22:45 -0700564 mTranslator.translateRectInAppWindowToScreen(dirty);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700565 }
Romain Guy1e095972009-07-07 11:22:45 -0700566 if (mAttachInfo.mScalingRequired) {
567 dirty.inset(-1, -1);
568 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800569 }
570 mDirty.union(dirty);
571 if (!mWillDrawSoon) {
572 scheduleTraversals();
573 }
574 }
Romain Guy0d9275e2010-10-26 14:22:30 -0700575
576 void invalidate() {
577 mDirty.set(0, 0, mWidth, mHeight);
578 scheduleTraversals();
579 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800580
581 public ViewParent getParent() {
582 return null;
583 }
584
585 public ViewParent invalidateChildInParent(final int[] location, final Rect dirty) {
586 invalidateChild(null, dirty);
587 return null;
588 }
589
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700590 public boolean getChildVisibleRect(View child, Rect r, android.graphics.Point offset) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800591 if (child != mView) {
592 throw new RuntimeException("child is not mine, honest!");
593 }
594 // Note: don't apply scroll offset, because we want to know its
595 // visibility in the virtual canvas being given to the view hierarchy.
596 return r.intersect(0, 0, mWidth, mHeight);
597 }
598
599 public void bringChildToFront(View child) {
600 }
601
602 public void scheduleTraversals() {
603 if (!mTraversalScheduled) {
604 mTraversalScheduled = true;
605 sendEmptyMessage(DO_TRAVERSAL);
606 }
607 }
608
609 public void unscheduleTraversals() {
610 if (mTraversalScheduled) {
611 mTraversalScheduled = false;
612 removeMessages(DO_TRAVERSAL);
613 }
614 }
615
616 int getHostVisibility() {
617 return mAppVisible ? mView.getVisibility() : View.GONE;
618 }
Romain Guy8506ab42009-06-11 17:35:47 -0700619
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800620 private void performTraversals() {
621 // cache mView since it is used so much below...
622 final View host = mView;
623
624 if (DBG) {
625 System.out.println("======================================");
626 System.out.println("performTraversals");
627 host.debug();
628 }
629
630 if (host == null || !mAdded)
631 return;
632
633 mTraversalScheduled = false;
634 mWillDrawSoon = true;
635 boolean windowResizesToFitContent = false;
636 boolean fullRedrawNeeded = mFullRedrawNeeded;
637 boolean newSurface = false;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700638 boolean surfaceChanged = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800639 WindowManager.LayoutParams lp = mWindowAttributes;
640
641 int desiredWindowWidth;
642 int desiredWindowHeight;
643 int childWidthMeasureSpec;
644 int childHeightMeasureSpec;
645
646 final View.AttachInfo attachInfo = mAttachInfo;
647
648 final int viewVisibility = getHostVisibility();
649 boolean viewVisibilityChanged = mViewVisibility != viewVisibility
650 || mNewSurfaceNeeded;
651
652 WindowManager.LayoutParams params = null;
653 if (mWindowAttributesChanged) {
654 mWindowAttributesChanged = false;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700655 surfaceChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800656 params = lp;
657 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700658 Rect frame = mWinFrame;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800659 if (mFirst) {
660 fullRedrawNeeded = true;
661 mLayoutRequested = true;
662
Romain Guy8506ab42009-06-11 17:35:47 -0700663 DisplayMetrics packageMetrics =
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700664 mView.getContext().getResources().getDisplayMetrics();
665 desiredWindowWidth = packageMetrics.widthPixels;
666 desiredWindowHeight = packageMetrics.heightPixels;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800667
668 // For the very first time, tell the view hierarchy that it
669 // is attached to the window. Note that at this point the surface
670 // object is not initialized to its backing store, but soon it
671 // will be (assuming the window is visible).
672 attachInfo.mSurface = mSurface;
Dianne Hackborn289b9b62010-07-09 11:44:11 -0700673 attachInfo.mTranslucentWindow = PixelFormat.formatHasAlpha(lp.format);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800674 attachInfo.mHasWindowFocus = false;
675 attachInfo.mWindowVisibility = viewVisibility;
676 attachInfo.mRecomputeGlobalAttributes = false;
677 attachInfo.mKeepScreenOn = false;
678 viewVisibilityChanged = false;
Dianne Hackborn694f79b2010-03-17 19:44:59 -0700679 mLastConfiguration.setTo(host.getResources().getConfiguration());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800680 host.dispatchAttachedToWindow(attachInfo, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800681 //Log.i(TAG, "Screen on initialized: " + attachInfo.mKeepScreenOn);
svetoslavganov75986cf2009-05-14 22:28:01 -0700682
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800683 } else {
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700684 desiredWindowWidth = frame.width();
685 desiredWindowHeight = frame.height();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800686 if (desiredWindowWidth != mWidth || desiredWindowHeight != mHeight) {
Jeff Brownc5ed5912010-07-14 18:48:53 -0700687 if (DEBUG_ORIENTATION) Log.v(TAG,
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700688 "View " + host + " resized to: " + frame);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800689 fullRedrawNeeded = true;
690 mLayoutRequested = true;
691 windowResizesToFitContent = true;
692 }
693 }
694
695 if (viewVisibilityChanged) {
696 attachInfo.mWindowVisibility = viewVisibility;
697 host.dispatchWindowVisibilityChanged(viewVisibility);
698 if (viewVisibility != View.VISIBLE || mNewSurfaceNeeded) {
Romain Guyb051e892010-09-28 19:09:36 -0700699 if (mAttachInfo.mHardwareRenderer != null) {
700 mAttachInfo.mHardwareRenderer.destroy(false);
Romain Guy4caa4ed2010-08-25 14:46:24 -0700701 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800702 }
703 if (viewVisibility == View.GONE) {
704 // After making a window gone, we will count it as being
705 // shown for the first time the next time it gets focus.
706 mHasHadWindowFocus = false;
707 }
708 }
709
710 boolean insetsChanged = false;
Romain Guy8506ab42009-06-11 17:35:47 -0700711
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800712 if (mLayoutRequested) {
Romain Guy15df6702009-08-17 20:17:30 -0700713 // Execute enqueued actions on every layout in case a view that was detached
714 // enqueued an action after being detached
715 getRunQueue().executeActions(attachInfo.mHandler);
716
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800717 if (mFirst) {
718 host.fitSystemWindows(mAttachInfo.mContentInsets);
719 // make sure touch mode code executes by setting cached value
720 // to opposite of the added touch mode.
721 mAttachInfo.mInTouchMode = !mAddedTouchMode;
Romain Guy2d4cff62010-04-09 15:39:00 -0700722 ensureTouchModeLocally(mAddedTouchMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800723 } else {
724 if (!mAttachInfo.mContentInsets.equals(mPendingContentInsets)) {
725 mAttachInfo.mContentInsets.set(mPendingContentInsets);
726 host.fitSystemWindows(mAttachInfo.mContentInsets);
727 insetsChanged = true;
728 if (DEBUG_LAYOUT) Log.v(TAG, "Content insets changing to: "
729 + mAttachInfo.mContentInsets);
730 }
731 if (!mAttachInfo.mVisibleInsets.equals(mPendingVisibleInsets)) {
732 mAttachInfo.mVisibleInsets.set(mPendingVisibleInsets);
733 if (DEBUG_LAYOUT) Log.v(TAG, "Visible insets changing to: "
734 + mAttachInfo.mVisibleInsets);
735 }
736 if (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT
737 || lp.height == ViewGroup.LayoutParams.WRAP_CONTENT) {
738 windowResizesToFitContent = true;
739
Romain Guy8506ab42009-06-11 17:35:47 -0700740 DisplayMetrics packageMetrics =
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700741 mView.getContext().getResources().getDisplayMetrics();
742 desiredWindowWidth = packageMetrics.widthPixels;
743 desiredWindowHeight = packageMetrics.heightPixels;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800744 }
745 }
746
747 childWidthMeasureSpec = getRootMeasureSpec(desiredWindowWidth, lp.width);
748 childHeightMeasureSpec = getRootMeasureSpec(desiredWindowHeight, lp.height);
749
750 // Ask host how big it wants to be
Jeff Brownc5ed5912010-07-14 18:48:53 -0700751 if (DEBUG_ORIENTATION || DEBUG_LAYOUT) Log.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800752 "Measuring " + host + " in display " + desiredWindowWidth
753 + "x" + desiredWindowHeight + "...");
754 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
755
756 if (DBG) {
757 System.out.println("======================================");
758 System.out.println("performTraversals -- after measure");
759 host.debug();
760 }
761 }
762
763 if (attachInfo.mRecomputeGlobalAttributes) {
764 //Log.i(TAG, "Computing screen on!");
765 attachInfo.mRecomputeGlobalAttributes = false;
766 boolean oldVal = attachInfo.mKeepScreenOn;
767 attachInfo.mKeepScreenOn = false;
768 host.dispatchCollectViewAttributes(0);
769 if (attachInfo.mKeepScreenOn != oldVal) {
770 params = lp;
771 //Log.i(TAG, "Keep screen on changed: " + attachInfo.mKeepScreenOn);
772 }
773 }
774
775 if (mFirst || attachInfo.mViewVisibilityChanged) {
776 attachInfo.mViewVisibilityChanged = false;
777 int resizeMode = mSoftInputMode &
778 WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST;
779 // If we are in auto resize mode, then we need to determine
780 // what mode to use now.
781 if (resizeMode == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED) {
782 final int N = attachInfo.mScrollContainers.size();
783 for (int i=0; i<N; i++) {
784 if (attachInfo.mScrollContainers.get(i).isShown()) {
785 resizeMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE;
786 }
787 }
788 if (resizeMode == 0) {
789 resizeMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN;
790 }
791 if ((lp.softInputMode &
792 WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) != resizeMode) {
793 lp.softInputMode = (lp.softInputMode &
794 ~WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) |
795 resizeMode;
796 params = lp;
797 }
798 }
799 }
Romain Guy8506ab42009-06-11 17:35:47 -0700800
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800801 if (params != null && (host.mPrivateFlags & View.REQUEST_TRANSPARENT_REGIONS) != 0) {
802 if (!PixelFormat.formatHasAlpha(params.format)) {
803 params.format = PixelFormat.TRANSLUCENT;
804 }
805 }
806
807 boolean windowShouldResize = mLayoutRequested && windowResizesToFitContent
Romain Guy2e4f4262010-04-06 11:07:52 -0700808 && ((mWidth != host.mMeasuredWidth || mHeight != host.mMeasuredHeight)
809 || (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT &&
810 frame.width() < desiredWindowWidth && frame.width() != mWidth)
811 || (lp.height == ViewGroup.LayoutParams.WRAP_CONTENT &&
812 frame.height() < desiredWindowHeight && frame.height() != mHeight));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800813
814 final boolean computesInternalInsets =
815 attachInfo.mTreeObserver.hasComputeInternalInsetsListeners();
Romain Guy812ccbe2010-06-01 14:07:24 -0700816
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800817 boolean insetsPending = false;
818 int relayoutResult = 0;
Romain Guy812ccbe2010-06-01 14:07:24 -0700819
820 if (mFirst || windowShouldResize || insetsChanged ||
821 viewVisibilityChanged || params != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800822
823 if (viewVisibility == View.VISIBLE) {
824 // If this window is giving internal insets to the window
825 // manager, and it is being added or changing its visibility,
826 // then we want to first give the window manager "fake"
827 // insets to cause it to effectively ignore the content of
828 // the window during layout. This avoids it briefly causing
829 // other windows to resize/move based on the raw frame of the
830 // window, waiting until we can finish laying out this window
831 // and get back to the window manager with the ultimately
832 // computed insets.
Romain Guy812ccbe2010-06-01 14:07:24 -0700833 insetsPending = computesInternalInsets && (mFirst || viewVisibilityChanged);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800834 }
835
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700836 if (mSurfaceHolder != null) {
837 mSurfaceHolder.mSurfaceLock.lock();
838 mDrawingAllowed = true;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700839 }
Romain Guy812ccbe2010-06-01 14:07:24 -0700840
Romain Guyc361da82010-10-25 15:29:10 -0700841 boolean hwInitialized = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800842 boolean contentInsetsChanged = false;
Romain Guy13922e02009-05-12 17:56:14 -0700843 boolean visibleInsetsChanged;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700844 boolean hadSurface = mSurface.isValid();
Romain Guy812ccbe2010-06-01 14:07:24 -0700845
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800846 try {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800847 int fl = 0;
848 if (params != null) {
849 fl = params.flags;
850 if (attachInfo.mKeepScreenOn) {
851 params.flags |= WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
852 }
853 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700854 if (DEBUG_LAYOUT) {
855 Log.i(TAG, "host=w:" + host.mMeasuredWidth + ", h:" +
856 host.mMeasuredHeight + ", params=" + params);
857 }
858 relayoutResult = relayoutWindow(params, viewVisibility, insetsPending);
859
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800860 if (params != null) {
861 params.flags = fl;
862 }
863
864 if (DEBUG_LAYOUT) Log.v(TAG, "relayout: frame=" + frame.toShortString()
865 + " content=" + mPendingContentInsets.toShortString()
866 + " visible=" + mPendingVisibleInsets.toShortString()
867 + " surface=" + mSurface);
Romain Guy8506ab42009-06-11 17:35:47 -0700868
Dianne Hackborn694f79b2010-03-17 19:44:59 -0700869 if (mPendingConfiguration.seq != 0) {
870 if (DEBUG_CONFIGURATION) Log.v(TAG, "Visible with new config: "
871 + mPendingConfiguration);
872 updateConfiguration(mPendingConfiguration, !mFirst);
873 mPendingConfiguration.seq = 0;
874 }
875
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800876 contentInsetsChanged = !mPendingContentInsets.equals(
877 mAttachInfo.mContentInsets);
878 visibleInsetsChanged = !mPendingVisibleInsets.equals(
879 mAttachInfo.mVisibleInsets);
880 if (contentInsetsChanged) {
881 mAttachInfo.mContentInsets.set(mPendingContentInsets);
882 host.fitSystemWindows(mAttachInfo.mContentInsets);
883 if (DEBUG_LAYOUT) Log.v(TAG, "Content insets changing to: "
884 + mAttachInfo.mContentInsets);
885 }
886 if (visibleInsetsChanged) {
887 mAttachInfo.mVisibleInsets.set(mPendingVisibleInsets);
888 if (DEBUG_LAYOUT) Log.v(TAG, "Visible insets changing to: "
889 + mAttachInfo.mVisibleInsets);
890 }
891
892 if (!hadSurface) {
893 if (mSurface.isValid()) {
894 // If we are creating a new surface, then we need to
895 // completely redraw it. Also, when we get to the
896 // point of drawing it we will hold off and schedule
897 // a new traversal instead. This is so we can tell the
898 // window manager about all of the windows being displayed
899 // before actually drawing them, so it can display then
900 // all at once.
901 newSurface = true;
902 fullRedrawNeeded = true;
Jack Palevich61a6e682009-10-09 17:37:50 -0700903 mPreviousTransparentRegion.setEmpty();
Romain Guy8506ab42009-06-11 17:35:47 -0700904
Romain Guyb051e892010-09-28 19:09:36 -0700905 if (mAttachInfo.mHardwareRenderer != null) {
Romain Guyc361da82010-10-25 15:29:10 -0700906 hwInitialized = mAttachInfo.mHardwareRenderer.initialize(mHolder);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800907 }
908 }
909 } else if (!mSurface.isValid()) {
910 // If the surface has been removed, then reset the scroll
911 // positions.
912 mLastScrolledFocus = null;
913 mScrollY = mCurScrollY = 0;
914 if (mScroller != null) {
915 mScroller.abortAnimation();
916 }
917 }
918 } catch (RemoteException e) {
919 }
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700920
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800921 if (DEBUG_ORIENTATION) Log.v(
Jeff Brownc5ed5912010-07-14 18:48:53 -0700922 TAG, "Relayout returned: frame=" + frame + ", surface=" + mSurface);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800923
924 attachInfo.mWindowLeft = frame.left;
925 attachInfo.mWindowTop = frame.top;
926
927 // !!FIXME!! This next section handles the case where we did not get the
928 // window size we asked for. We should avoid this by getting a maximum size from
929 // the window session beforehand.
930 mWidth = frame.width();
931 mHeight = frame.height();
932
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700933 if (mSurfaceHolder != null) {
934 // The app owns the surface; tell it about what is going on.
935 if (mSurface.isValid()) {
936 // XXX .copyFrom() doesn't work!
937 //mSurfaceHolder.mSurface.copyFrom(mSurface);
938 mSurfaceHolder.mSurface = mSurface;
939 }
940 mSurfaceHolder.mSurfaceLock.unlock();
941 if (mSurface.isValid()) {
942 if (!hadSurface) {
943 mSurfaceHolder.ungetCallbacks();
944
945 mIsCreating = true;
946 mSurfaceHolderCallback.surfaceCreated(mSurfaceHolder);
947 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
948 if (callbacks != null) {
949 for (SurfaceHolder.Callback c : callbacks) {
950 c.surfaceCreated(mSurfaceHolder);
951 }
952 }
953 surfaceChanged = true;
Romain Guyc361da82010-10-25 15:29:10 -0700954
955 if (mAttachInfo.mHardwareRenderer != null) {
956 // This will bail out early if already initialized
957 mAttachInfo.mHardwareRenderer.initialize(mHolder);
958 }
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700959 }
960 if (surfaceChanged) {
961 mSurfaceHolderCallback.surfaceChanged(mSurfaceHolder,
962 lp.format, mWidth, mHeight);
963 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
964 if (callbacks != null) {
965 for (SurfaceHolder.Callback c : callbacks) {
966 c.surfaceChanged(mSurfaceHolder, lp.format,
967 mWidth, mHeight);
968 }
969 }
970 }
971 mIsCreating = false;
972 } else if (hadSurface) {
973 mSurfaceHolder.ungetCallbacks();
974 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
975 mSurfaceHolderCallback.surfaceDestroyed(mSurfaceHolder);
976 if (callbacks != null) {
977 for (SurfaceHolder.Callback c : callbacks) {
978 c.surfaceDestroyed(mSurfaceHolder);
979 }
980 }
981 mSurfaceHolder.mSurfaceLock.lock();
982 // Make surface invalid.
983 //mSurfaceHolder.mSurface.copyFrom(mSurface);
984 mSurfaceHolder.mSurface = new Surface();
985 mSurfaceHolder.mSurfaceLock.unlock();
986 }
987 }
Romain Guy53389bd2010-09-07 17:16:32 -0700988
Romain Guyc361da82010-10-25 15:29:10 -0700989 if (hwInitialized || (windowShouldResize && mAttachInfo.mHardwareRenderer != null)) {
Romain Guyb051e892010-09-28 19:09:36 -0700990 mAttachInfo.mHardwareRenderer.setup(mWidth, mHeight);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800991 }
992
993 boolean focusChangedDueToTouchMode = ensureTouchModeLocally(
Romain Guy2d4cff62010-04-09 15:39:00 -0700994 (relayoutResult&WindowManagerImpl.RELAYOUT_IN_TOUCH_MODE) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800995 if (focusChangedDueToTouchMode || mWidth != host.mMeasuredWidth
996 || mHeight != host.mMeasuredHeight || contentInsetsChanged) {
997 childWidthMeasureSpec = getRootMeasureSpec(mWidth, lp.width);
998 childHeightMeasureSpec = getRootMeasureSpec(mHeight, lp.height);
999
1000 if (DEBUG_LAYOUT) Log.v(TAG, "Ooops, something changed! mWidth="
1001 + mWidth + " measuredWidth=" + host.mMeasuredWidth
1002 + " mHeight=" + mHeight
1003 + " measuredHeight" + host.mMeasuredHeight
1004 + " coveredInsetsChanged=" + contentInsetsChanged);
Romain Guy8506ab42009-06-11 17:35:47 -07001005
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001006 // Ask host how big it wants to be
1007 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
1008
1009 // Implementation of weights from WindowManager.LayoutParams
1010 // We just grow the dimensions as needed and re-measure if
1011 // needs be
1012 int width = host.mMeasuredWidth;
1013 int height = host.mMeasuredHeight;
1014 boolean measureAgain = false;
1015
1016 if (lp.horizontalWeight > 0.0f) {
1017 width += (int) ((mWidth - width) * lp.horizontalWeight);
1018 childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(width,
1019 MeasureSpec.EXACTLY);
1020 measureAgain = true;
1021 }
1022 if (lp.verticalWeight > 0.0f) {
1023 height += (int) ((mHeight - height) * lp.verticalWeight);
1024 childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(height,
1025 MeasureSpec.EXACTLY);
1026 measureAgain = true;
1027 }
1028
1029 if (measureAgain) {
1030 if (DEBUG_LAYOUT) Log.v(TAG,
1031 "And hey let's measure once more: width=" + width
1032 + " height=" + height);
1033 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
1034 }
1035
1036 mLayoutRequested = true;
1037 }
1038 }
1039
1040 final boolean didLayout = mLayoutRequested;
1041 boolean triggerGlobalLayoutListener = didLayout
1042 || attachInfo.mRecomputeGlobalAttributes;
1043 if (didLayout) {
1044 mLayoutRequested = false;
1045 mScrollMayChange = true;
1046 if (DEBUG_ORIENTATION || DEBUG_LAYOUT) Log.v(
Jeff Brownc5ed5912010-07-14 18:48:53 -07001047 TAG, "Laying out " + host + " to (" +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001048 host.mMeasuredWidth + ", " + host.mMeasuredHeight + ")");
Romain Guy13922e02009-05-12 17:56:14 -07001049 long startTime = 0L;
Romain Guy5429e1d2010-09-07 12:38:00 -07001050 if (ViewDebug.DEBUG_PROFILE_LAYOUT) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001051 startTime = SystemClock.elapsedRealtime();
1052 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001053 host.layout(0, 0, host.mMeasuredWidth, host.mMeasuredHeight);
1054
Romain Guy13922e02009-05-12 17:56:14 -07001055 if (Config.DEBUG && ViewDebug.consistencyCheckEnabled) {
1056 if (!host.dispatchConsistencyCheck(ViewDebug.CONSISTENCY_LAYOUT)) {
1057 throw new IllegalStateException("The view hierarchy is an inconsistent state,"
1058 + "please refer to the logs with the tag "
1059 + ViewDebug.CONSISTENCY_LOG_TAG + " for more infomation.");
1060 }
1061 }
1062
Romain Guy5429e1d2010-09-07 12:38:00 -07001063 if (ViewDebug.DEBUG_PROFILE_LAYOUT) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001064 EventLog.writeEvent(60001, SystemClock.elapsedRealtime() - startTime);
1065 }
1066
1067 // By this point all views have been sized and positionned
1068 // We can compute the transparent area
1069
1070 if ((host.mPrivateFlags & View.REQUEST_TRANSPARENT_REGIONS) != 0) {
1071 // start out transparent
1072 // TODO: AVOID THAT CALL BY CACHING THE RESULT?
1073 host.getLocationInWindow(mTmpLocation);
1074 mTransparentRegion.set(mTmpLocation[0], mTmpLocation[1],
1075 mTmpLocation[0] + host.mRight - host.mLeft,
1076 mTmpLocation[1] + host.mBottom - host.mTop);
1077
1078 host.gatherTransparentRegion(mTransparentRegion);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001079 if (mTranslator != null) {
1080 mTranslator.translateRegionInWindowToScreen(mTransparentRegion);
1081 }
1082
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001083 if (!mTransparentRegion.equals(mPreviousTransparentRegion)) {
1084 mPreviousTransparentRegion.set(mTransparentRegion);
1085 // reconfigure window manager
1086 try {
1087 sWindowSession.setTransparentRegion(mWindow, mTransparentRegion);
1088 } catch (RemoteException e) {
1089 }
1090 }
1091 }
1092
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001093 if (DBG) {
1094 System.out.println("======================================");
1095 System.out.println("performTraversals -- after setFrame");
1096 host.debug();
1097 }
1098 }
1099
1100 if (triggerGlobalLayoutListener) {
1101 attachInfo.mRecomputeGlobalAttributes = false;
1102 attachInfo.mTreeObserver.dispatchOnGlobalLayout();
1103 }
1104
1105 if (computesInternalInsets) {
1106 ViewTreeObserver.InternalInsetsInfo insets = attachInfo.mGivenInternalInsets;
1107 final Rect givenContent = attachInfo.mGivenInternalInsets.contentInsets;
1108 final Rect givenVisible = attachInfo.mGivenInternalInsets.visibleInsets;
1109 givenContent.left = givenContent.top = givenContent.right
1110 = givenContent.bottom = givenVisible.left = givenVisible.top
1111 = givenVisible.right = givenVisible.bottom = 0;
1112 attachInfo.mTreeObserver.dispatchOnComputeInternalInsets(insets);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001113 Rect contentInsets = insets.contentInsets;
1114 Rect visibleInsets = insets.visibleInsets;
1115 if (mTranslator != null) {
1116 contentInsets = mTranslator.getTranslatedContentInsets(contentInsets);
1117 visibleInsets = mTranslator.getTranslatedVisbileInsets(visibleInsets);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001118 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001119 if (insetsPending || !mLastGivenInsets.equals(insets)) {
1120 mLastGivenInsets.set(insets);
1121 try {
1122 sWindowSession.setInsets(mWindow, insets.mTouchableInsets,
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001123 contentInsets, visibleInsets);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001124 } catch (RemoteException e) {
1125 }
1126 }
1127 }
Romain Guy8506ab42009-06-11 17:35:47 -07001128
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001129 if (mFirst) {
1130 // handle first focus request
1131 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: mView.hasFocus()="
1132 + mView.hasFocus());
1133 if (mView != null) {
1134 if (!mView.hasFocus()) {
1135 mView.requestFocus(View.FOCUS_FORWARD);
1136 mFocusedView = mRealFocusedView = mView.findFocus();
1137 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: requested focused view="
1138 + mFocusedView);
1139 } else {
1140 mRealFocusedView = mView.findFocus();
1141 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: existing focused view="
1142 + mRealFocusedView);
1143 }
1144 }
1145 }
1146
1147 mFirst = false;
1148 mWillDrawSoon = false;
1149 mNewSurfaceNeeded = false;
1150 mViewVisibility = viewVisibility;
1151
1152 if (mAttachInfo.mHasWindowFocus) {
1153 final boolean imTarget = WindowManager.LayoutParams
1154 .mayUseInputMethod(mWindowAttributes.flags);
1155 if (imTarget != mLastWasImTarget) {
1156 mLastWasImTarget = imTarget;
1157 InputMethodManager imm = InputMethodManager.peekInstance();
1158 if (imm != null && imTarget) {
1159 imm.startGettingWindowFocus(mView);
1160 imm.onWindowFocus(mView, mView.findFocus(),
1161 mWindowAttributes.softInputMode,
1162 !mHasHadWindowFocus, mWindowAttributes.flags);
1163 }
1164 }
1165 }
Romain Guy8506ab42009-06-11 17:35:47 -07001166
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001167 boolean cancelDraw = attachInfo.mTreeObserver.dispatchOnPreDraw();
1168
1169 if (!cancelDraw && !newSurface) {
1170 mFullRedrawNeeded = false;
1171 draw(fullRedrawNeeded);
1172
1173 if ((relayoutResult&WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0
1174 || mReportNextDraw) {
1175 if (LOCAL_LOGV) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001176 Log.v(TAG, "FINISHED DRAWING: " + mWindowAttributes.getTitle());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001177 }
1178 mReportNextDraw = false;
Dianne Hackbornd76b67c2010-07-13 17:48:30 -07001179 if (mSurfaceHolder != null && mSurface.isValid()) {
1180 mSurfaceHolderCallback.surfaceRedrawNeeded(mSurfaceHolder);
1181 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
1182 if (callbacks != null) {
1183 for (SurfaceHolder.Callback c : callbacks) {
1184 if (c instanceof SurfaceHolder.Callback2) {
1185 ((SurfaceHolder.Callback2)c).surfaceRedrawNeeded(
1186 mSurfaceHolder);
1187 }
1188 }
1189 }
1190 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001191 try {
1192 sWindowSession.finishDrawing(mWindow);
1193 } catch (RemoteException e) {
1194 }
1195 }
1196 } else {
1197 // We were supposed to report when we are done drawing. Since we canceled the
1198 // draw, remember it here.
1199 if ((relayoutResult&WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0) {
1200 mReportNextDraw = true;
1201 }
1202 if (fullRedrawNeeded) {
1203 mFullRedrawNeeded = true;
1204 }
1205 // Try again
1206 scheduleTraversals();
1207 }
1208 }
1209
1210 public void requestTransparentRegion(View child) {
1211 // the test below should not fail unless someone is messing with us
1212 checkThread();
1213 if (mView == child) {
1214 mView.mPrivateFlags |= View.REQUEST_TRANSPARENT_REGIONS;
1215 // Need to make sure we re-evaluate the window attributes next
1216 // time around, to ensure the window has the correct format.
1217 mWindowAttributesChanged = true;
1218 }
1219 }
1220
1221 /**
1222 * Figures out the measure spec for the root view in a window based on it's
1223 * layout params.
1224 *
1225 * @param windowSize
1226 * The available width or height of the window
1227 *
1228 * @param rootDimension
1229 * The layout params for one dimension (width or height) of the
1230 * window.
1231 *
1232 * @return The measure spec to use to measure the root view.
1233 */
1234 private int getRootMeasureSpec(int windowSize, int rootDimension) {
1235 int measureSpec;
1236 switch (rootDimension) {
1237
Romain Guy980a9382010-01-08 15:06:28 -08001238 case ViewGroup.LayoutParams.MATCH_PARENT:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001239 // Window can't resize. Force root view to be windowSize.
1240 measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.EXACTLY);
1241 break;
1242 case ViewGroup.LayoutParams.WRAP_CONTENT:
1243 // Window can resize. Set max size for root view.
1244 measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.AT_MOST);
1245 break;
1246 default:
1247 // Window wants to be an exact size. Force root view to be that size.
1248 measureSpec = MeasureSpec.makeMeasureSpec(rootDimension, MeasureSpec.EXACTLY);
1249 break;
1250 }
1251 return measureSpec;
1252 }
1253
1254 private void draw(boolean fullRedrawNeeded) {
1255 Surface surface = mSurface;
1256 if (surface == null || !surface.isValid()) {
1257 return;
1258 }
1259
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001260 if (!sFirstDrawComplete) {
1261 synchronized (sFirstDrawHandlers) {
1262 sFirstDrawComplete = true;
Romain Guy812ccbe2010-06-01 14:07:24 -07001263 final int count = sFirstDrawHandlers.size();
1264 for (int i = 0; i< count; i++) {
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001265 post(sFirstDrawHandlers.get(i));
1266 }
1267 }
1268 }
1269
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001270 scrollToRectOrFocus(null, false);
1271
1272 if (mAttachInfo.mViewScrollChanged) {
1273 mAttachInfo.mViewScrollChanged = false;
1274 mAttachInfo.mTreeObserver.dispatchOnScrollChanged();
1275 }
Romain Guy8506ab42009-06-11 17:35:47 -07001276
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001277 int yoff;
Romain Guy5bcdff42009-05-14 21:27:18 -07001278 final boolean scrolling = mScroller != null && mScroller.computeScrollOffset();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001279 if (scrolling) {
1280 yoff = mScroller.getCurrY();
1281 } else {
1282 yoff = mScrollY;
1283 }
1284 if (mCurScrollY != yoff) {
1285 mCurScrollY = yoff;
1286 fullRedrawNeeded = true;
1287 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001288 float appScale = mAttachInfo.mApplicationScale;
1289 boolean scalingRequired = mAttachInfo.mScalingRequired;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001290
1291 Rect dirty = mDirty;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001292 if (mSurfaceHolder != null) {
1293 // The app owns the surface, we won't draw.
1294 dirty.setEmpty();
1295 return;
1296 }
Romain Guy58ef7fb2010-09-13 12:52:37 -07001297
1298 if (fullRedrawNeeded) {
1299 mAttachInfo.mIgnoreDirtyState = true;
1300 dirty.union(0, 0, (int) (mWidth * appScale + 0.5f), (int) (mHeight * appScale + 0.5f));
1301 }
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001302
Romain Guyb051e892010-09-28 19:09:36 -07001303 if (mAttachInfo.mHardwareRenderer != null && mAttachInfo.mHardwareRenderer.isEnabled()) {
Romain Guyfd507262010-10-10 15:42:49 -07001304 if (!dirty.isEmpty() || mIsAnimating) {
Romain Guy101e2ae2010-10-11 12:41:21 -07001305 mIsAnimating = false;
Romain Guyfd507262010-10-10 15:42:49 -07001306 dirty.setEmpty();
Romain Guy101e2ae2010-10-11 12:41:21 -07001307 mAttachInfo.mHardwareRenderer.draw(mView, mAttachInfo, yoff);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001308 }
Romain Guy812ccbe2010-06-01 14:07:24 -07001309
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001310 if (scrolling) {
1311 mFullRedrawNeeded = true;
1312 scheduleTraversals();
1313 }
Romain Guy812ccbe2010-06-01 14:07:24 -07001314
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001315 return;
1316 }
1317
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001318 if (DEBUG_ORIENTATION || DEBUG_DRAW) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001319 Log.v(TAG, "Draw " + mView + "/"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001320 + mWindowAttributes.getTitle()
1321 + ": dirty={" + dirty.left + "," + dirty.top
1322 + "," + dirty.right + "," + dirty.bottom + "} surface="
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001323 + surface + " surface.isValid()=" + surface.isValid() + ", appScale:" +
1324 appScale + ", width=" + mWidth + ", height=" + mHeight);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001325 }
1326
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001327 if (!dirty.isEmpty() || mIsAnimating) {
1328 Canvas canvas;
1329 try {
1330 int left = dirty.left;
1331 int top = dirty.top;
1332 int right = dirty.right;
1333 int bottom = dirty.bottom;
1334 canvas = surface.lockCanvas(dirty);
Romain Guy5bcdff42009-05-14 21:27:18 -07001335
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001336 if (left != dirty.left || top != dirty.top || right != dirty.right ||
1337 bottom != dirty.bottom) {
1338 mAttachInfo.mIgnoreDirtyState = true;
1339 }
1340
1341 // TODO: Do this in native
1342 canvas.setDensity(mDensity);
1343 } catch (Surface.OutOfResourcesException e) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001344 Log.e(TAG, "OutOfResourcesException locking surface", e);
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001345 // TODO: we should ask the window manager to do something!
1346 // for now we just do nothing
1347 return;
1348 } catch (IllegalArgumentException e) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001349 Log.e(TAG, "IllegalArgumentException locking surface", e);
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001350 // TODO: we should ask the window manager to do something!
1351 // for now we just do nothing
1352 return;
Romain Guy5bcdff42009-05-14 21:27:18 -07001353 }
1354
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001355 try {
1356 if (!dirty.isEmpty() || mIsAnimating) {
1357 long startTime = 0L;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001358
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001359 if (DEBUG_ORIENTATION || DEBUG_DRAW) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001360 Log.v(TAG, "Surface " + surface + " drawing to bitmap w="
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001361 + canvas.getWidth() + ", h=" + canvas.getHeight());
1362 //canvas.drawARGB(255, 255, 0, 0);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001363 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001364
Romain Guy5429e1d2010-09-07 12:38:00 -07001365 if (ViewDebug.DEBUG_PROFILE_DRAWING) {
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001366 startTime = SystemClock.elapsedRealtime();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001367 }
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001368
1369 // If this bitmap's format includes an alpha channel, we
1370 // need to clear it before drawing so that the child will
1371 // properly re-composite its drawing on a transparent
1372 // background. This automatically respects the clip/dirty region
1373 // or
1374 // If we are applying an offset, we need to clear the area
1375 // where the offset doesn't appear to avoid having garbage
1376 // left in the blank areas.
1377 if (!canvas.isOpaque() || yoff != 0) {
1378 canvas.drawColor(0, PorterDuff.Mode.CLEAR);
1379 }
1380
1381 dirty.setEmpty();
1382 mIsAnimating = false;
1383 mAttachInfo.mDrawingTime = SystemClock.uptimeMillis();
1384 mView.mPrivateFlags |= View.DRAWN;
1385
1386 if (DEBUG_DRAW) {
1387 Context cxt = mView.getContext();
1388 Log.i(TAG, "Drawing: package:" + cxt.getPackageName() +
1389 ", metrics=" + cxt.getResources().getDisplayMetrics() +
1390 ", compatibilityInfo=" + cxt.getResources().getCompatibilityInfo());
1391 }
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001392 try {
1393 canvas.translate(0, -yoff);
1394 if (mTranslator != null) {
1395 mTranslator.translateCanvas(canvas);
1396 }
1397 canvas.setScreenDensity(scalingRequired
1398 ? DisplayMetrics.DENSITY_DEVICE : 0);
1399 mView.draw(canvas);
1400 } finally {
1401 mAttachInfo.mIgnoreDirtyState = false;
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001402 }
1403
1404 if (Config.DEBUG && ViewDebug.consistencyCheckEnabled) {
1405 mView.dispatchConsistencyCheck(ViewDebug.CONSISTENCY_DRAWING);
1406 }
1407
Romain Guy5429e1d2010-09-07 12:38:00 -07001408 if (SHOW_FPS || ViewDebug.DEBUG_SHOW_FPS) {
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001409 int now = (int)SystemClock.elapsedRealtime();
1410 if (sDrawTime != 0) {
1411 nativeShowFPS(canvas, now - sDrawTime);
1412 }
1413 sDrawTime = now;
1414 }
1415
Romain Guy5429e1d2010-09-07 12:38:00 -07001416 if (ViewDebug.DEBUG_PROFILE_DRAWING) {
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001417 EventLog.writeEvent(60000, SystemClock.elapsedRealtime() - startTime);
1418 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001419 }
1420
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001421 } finally {
1422 surface.unlockCanvasAndPost(canvas);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001423 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001424 }
1425
1426 if (LOCAL_LOGV) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001427 Log.v(TAG, "Surface " + surface + " unlockCanvasAndPost");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001428 }
Romain Guy8506ab42009-06-11 17:35:47 -07001429
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001430 if (scrolling) {
1431 mFullRedrawNeeded = true;
1432 scheduleTraversals();
1433 }
1434 }
1435
1436 boolean scrollToRectOrFocus(Rect rectangle, boolean immediate) {
1437 final View.AttachInfo attachInfo = mAttachInfo;
1438 final Rect ci = attachInfo.mContentInsets;
1439 final Rect vi = attachInfo.mVisibleInsets;
1440 int scrollY = 0;
1441 boolean handled = false;
Romain Guy8506ab42009-06-11 17:35:47 -07001442
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001443 if (vi.left > ci.left || vi.top > ci.top
1444 || vi.right > ci.right || vi.bottom > ci.bottom) {
1445 // We'll assume that we aren't going to change the scroll
1446 // offset, since we want to avoid that unless it is actually
1447 // going to make the focus visible... otherwise we scroll
1448 // all over the place.
1449 scrollY = mScrollY;
1450 // We can be called for two different situations: during a draw,
1451 // to update the scroll position if the focus has changed (in which
1452 // case 'rectangle' is null), or in response to a
1453 // requestChildRectangleOnScreen() call (in which case 'rectangle'
1454 // is non-null and we just want to scroll to whatever that
1455 // rectangle is).
1456 View focus = mRealFocusedView;
Romain Guye8b16522009-07-14 13:06:42 -07001457
1458 // When in touch mode, focus points to the previously focused view,
1459 // which may have been removed from the view hierarchy. The following
Joe Onoratob71193b2009-11-24 18:34:42 -05001460 // line checks whether the view is still in our hierarchy.
1461 if (focus == null || focus.mAttachInfo != mAttachInfo) {
Romain Guye8b16522009-07-14 13:06:42 -07001462 mRealFocusedView = null;
1463 return false;
1464 }
1465
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001466 if (focus != mLastScrolledFocus) {
1467 // If the focus has changed, then ignore any requests to scroll
1468 // to a rectangle; first we want to make sure the entire focus
1469 // view is visible.
1470 rectangle = null;
1471 }
1472 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Eval scroll: focus=" + focus
1473 + " rectangle=" + rectangle + " ci=" + ci
1474 + " vi=" + vi);
1475 if (focus == mLastScrolledFocus && !mScrollMayChange
1476 && rectangle == null) {
1477 // Optimization: if the focus hasn't changed since last
1478 // time, and no layout has happened, then just leave things
1479 // as they are.
1480 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Keeping scroll y="
1481 + mScrollY + " vi=" + vi.toShortString());
1482 } else if (focus != null) {
1483 // We need to determine if the currently focused view is
1484 // within the visible part of the window and, if not, apply
1485 // a pan so it can be seen.
1486 mLastScrolledFocus = focus;
1487 mScrollMayChange = false;
1488 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Need to scroll?");
1489 // Try to find the rectangle from the focus view.
1490 if (focus.getGlobalVisibleRect(mVisRect, null)) {
1491 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Root w="
1492 + mView.getWidth() + " h=" + mView.getHeight()
1493 + " ci=" + ci.toShortString()
1494 + " vi=" + vi.toShortString());
1495 if (rectangle == null) {
1496 focus.getFocusedRect(mTempRect);
1497 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Focus " + focus
1498 + ": focusRect=" + mTempRect.toShortString());
Dianne Hackborn1c6a8942010-03-23 16:34:20 -07001499 if (mView instanceof ViewGroup) {
1500 ((ViewGroup) mView).offsetDescendantRectToMyCoords(
1501 focus, mTempRect);
1502 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001503 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1504 "Focus in window: focusRect="
1505 + mTempRect.toShortString()
1506 + " visRect=" + mVisRect.toShortString());
1507 } else {
1508 mTempRect.set(rectangle);
1509 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1510 "Request scroll to rect: "
1511 + mTempRect.toShortString()
1512 + " visRect=" + mVisRect.toShortString());
1513 }
1514 if (mTempRect.intersect(mVisRect)) {
1515 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1516 "Focus window visible rect: "
1517 + mTempRect.toShortString());
1518 if (mTempRect.height() >
1519 (mView.getHeight()-vi.top-vi.bottom)) {
1520 // If the focus simply is not going to fit, then
1521 // best is probably just to leave things as-is.
1522 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1523 "Too tall; leaving scrollY=" + scrollY);
1524 } else if ((mTempRect.top-scrollY) < vi.top) {
1525 scrollY -= vi.top - (mTempRect.top-scrollY);
1526 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1527 "Top covered; scrollY=" + scrollY);
1528 } else if ((mTempRect.bottom-scrollY)
1529 > (mView.getHeight()-vi.bottom)) {
1530 scrollY += (mTempRect.bottom-scrollY)
1531 - (mView.getHeight()-vi.bottom);
1532 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1533 "Bottom covered; scrollY=" + scrollY);
1534 }
1535 handled = true;
1536 }
1537 }
1538 }
1539 }
Romain Guy8506ab42009-06-11 17:35:47 -07001540
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001541 if (scrollY != mScrollY) {
1542 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Pan scroll changed: old="
1543 + mScrollY + " , new=" + scrollY);
1544 if (!immediate) {
1545 if (mScroller == null) {
1546 mScroller = new Scroller(mView.getContext());
1547 }
1548 mScroller.startScroll(0, mScrollY, 0, scrollY-mScrollY);
1549 } else if (mScroller != null) {
1550 mScroller.abortAnimation();
1551 }
1552 mScrollY = scrollY;
1553 }
Romain Guy8506ab42009-06-11 17:35:47 -07001554
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001555 return handled;
1556 }
Romain Guy8506ab42009-06-11 17:35:47 -07001557
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001558 public void requestChildFocus(View child, View focused) {
1559 checkThread();
1560 if (mFocusedView != focused) {
1561 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(mFocusedView, focused);
1562 scheduleTraversals();
1563 }
1564 mFocusedView = mRealFocusedView = focused;
1565 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Request child focus: focus now "
1566 + mFocusedView);
1567 }
1568
1569 public void clearChildFocus(View child) {
1570 checkThread();
1571
1572 View oldFocus = mFocusedView;
1573
1574 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Clearing child focus");
1575 mFocusedView = mRealFocusedView = null;
1576 if (mView != null && !mView.hasFocus()) {
1577 // If a view gets the focus, the listener will be invoked from requestChildFocus()
1578 if (!mView.requestFocus(View.FOCUS_FORWARD)) {
1579 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
1580 }
1581 } else if (oldFocus != null) {
1582 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
1583 }
1584 }
1585
1586
1587 public void focusableViewAvailable(View v) {
1588 checkThread();
1589
1590 if (mView != null && !mView.hasFocus()) {
1591 v.requestFocus();
1592 } else {
1593 // the one case where will transfer focus away from the current one
1594 // is if the current view is a view group that prefers to give focus
1595 // to its children first AND the view is a descendant of it.
1596 mFocusedView = mView.findFocus();
1597 boolean descendantsHaveDibsOnFocus =
1598 (mFocusedView instanceof ViewGroup) &&
1599 (((ViewGroup) mFocusedView).getDescendantFocusability() ==
1600 ViewGroup.FOCUS_AFTER_DESCENDANTS);
1601 if (descendantsHaveDibsOnFocus && isViewDescendantOf(v, mFocusedView)) {
1602 // If a view gets the focus, the listener will be invoked from requestChildFocus()
1603 v.requestFocus();
1604 }
1605 }
1606 }
1607
1608 public void recomputeViewAttributes(View child) {
1609 checkThread();
1610 if (mView == child) {
1611 mAttachInfo.mRecomputeGlobalAttributes = true;
1612 if (!mWillDrawSoon) {
1613 scheduleTraversals();
1614 }
1615 }
1616 }
1617
1618 void dispatchDetachedFromWindow() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001619 if (mView != null) {
1620 mView.dispatchDetachedFromWindow();
1621 }
1622
1623 mView = null;
1624 mAttachInfo.mRootView = null;
Mathias Agopian5583dc62009-07-09 16:28:11 -07001625 mAttachInfo.mSurface = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001626
Romain Guy29d89972010-09-22 16:10:57 -07001627 destroyHardwareRenderer();
Romain Guy4caa4ed2010-08-25 14:46:24 -07001628
Dianne Hackborn0586a1b2009-09-06 21:08:27 -07001629 mSurface.release();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001630
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001631 if (mInputChannel != null) {
1632 if (mInputQueueCallback != null) {
1633 mInputQueueCallback.onInputQueueDestroyed(mInputQueue);
1634 mInputQueueCallback = null;
1635 } else {
1636 InputQueue.unregisterInputChannel(mInputChannel);
Jeff Brown46b9ac02010-04-22 18:58:52 -07001637 }
1638 }
1639
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001640 try {
1641 sWindowSession.remove(mWindow);
1642 } catch (RemoteException e) {
1643 }
Jeff Brown349703e2010-06-22 01:27:15 -07001644
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001645 // Dispose the input channel after removing the window so the Window Manager
1646 // doesn't interpret the input channel being closed as an abnormal termination.
1647 if (mInputChannel != null) {
1648 mInputChannel.dispose();
1649 mInputChannel = null;
Jeff Brown349703e2010-06-22 01:27:15 -07001650 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001651 }
Romain Guy8506ab42009-06-11 17:35:47 -07001652
Dianne Hackborn694f79b2010-03-17 19:44:59 -07001653 void updateConfiguration(Configuration config, boolean force) {
1654 if (DEBUG_CONFIGURATION) Log.v(TAG,
1655 "Applying new config to window "
1656 + mWindowAttributes.getTitle()
1657 + ": " + config);
1658 synchronized (sConfigCallbacks) {
1659 for (int i=sConfigCallbacks.size()-1; i>=0; i--) {
1660 sConfigCallbacks.get(i).onConfigurationChanged(config);
1661 }
1662 }
1663 if (mView != null) {
1664 // At this point the resources have been updated to
1665 // have the most recent config, whatever that is. Use
1666 // the on in them which may be newer.
1667 if (mView != null) {
1668 config = mView.getResources().getConfiguration();
1669 }
1670 if (force || mLastConfiguration.diff(config) != 0) {
1671 mLastConfiguration.setTo(config);
1672 mView.dispatchConfigurationChanged(config);
1673 }
1674 }
1675 }
1676
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001677 /**
1678 * Return true if child is an ancestor of parent, (or equal to the parent).
1679 */
1680 private static boolean isViewDescendantOf(View child, View parent) {
1681 if (child == parent) {
1682 return true;
1683 }
1684
1685 final ViewParent theParent = child.getParent();
1686 return (theParent instanceof ViewGroup) && isViewDescendantOf((View) theParent, parent);
1687 }
1688
Romain Guycdb86672010-03-18 18:54:50 -07001689 private static void forceLayout(View view) {
1690 view.forceLayout();
1691 if (view instanceof ViewGroup) {
1692 ViewGroup group = (ViewGroup) view;
1693 final int count = group.getChildCount();
1694 for (int i = 0; i < count; i++) {
1695 forceLayout(group.getChildAt(i));
1696 }
1697 }
1698 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001699
1700 public final static int DO_TRAVERSAL = 1000;
1701 public final static int DIE = 1001;
1702 public final static int RESIZED = 1002;
1703 public final static int RESIZED_REPORT = 1003;
1704 public final static int WINDOW_FOCUS_CHANGED = 1004;
1705 public final static int DISPATCH_KEY = 1005;
1706 public final static int DISPATCH_POINTER = 1006;
1707 public final static int DISPATCH_TRACKBALL = 1007;
1708 public final static int DISPATCH_APP_VISIBILITY = 1008;
1709 public final static int DISPATCH_GET_NEW_SURFACE = 1009;
1710 public final static int FINISHED_EVENT = 1010;
1711 public final static int DISPATCH_KEY_FROM_IME = 1011;
1712 public final static int FINISH_INPUT_CONNECTION = 1012;
1713 public final static int CHECK_FOCUS = 1013;
Dianne Hackbornffa42482009-09-23 22:20:11 -07001714 public final static int CLOSE_SYSTEM_DIALOGS = 1014;
Christopher Tatea53146c2010-09-07 11:57:52 -07001715 public final static int DISPATCH_DRAG_EVENT = 1015;
Chris Tate91e9bb32010-10-12 12:58:43 -07001716 public final static int DISPATCH_DRAG_LOCATION_EVENT = 1016;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001717
1718 @Override
1719 public void handleMessage(Message msg) {
1720 switch (msg.what) {
1721 case View.AttachInfo.INVALIDATE_MSG:
1722 ((View) msg.obj).invalidate();
1723 break;
1724 case View.AttachInfo.INVALIDATE_RECT_MSG:
1725 final View.AttachInfo.InvalidateInfo info = (View.AttachInfo.InvalidateInfo) msg.obj;
1726 info.target.invalidate(info.left, info.top, info.right, info.bottom);
1727 info.release();
1728 break;
1729 case DO_TRAVERSAL:
1730 if (mProfile) {
1731 Debug.startMethodTracing("ViewRoot");
1732 }
1733
1734 performTraversals();
1735
1736 if (mProfile) {
1737 Debug.stopMethodTracing();
1738 mProfile = false;
1739 }
1740 break;
1741 case FINISHED_EVENT:
1742 handleFinishedEvent(msg.arg1, msg.arg2 != 0);
1743 break;
1744 case DISPATCH_KEY:
1745 if (LOCAL_LOGV) Log.v(
Jeff Brownc5ed5912010-07-14 18:48:53 -07001746 TAG, "Dispatching key "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001747 + msg.obj + " to " + mView);
Jeff Brown92ff1dd2010-08-11 16:16:06 -07001748 deliverKeyEvent((KeyEvent)msg.obj, msg.arg1 != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001749 break;
The Android Open Source Project10592532009-03-18 17:39:46 -07001750 case DISPATCH_POINTER: {
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001751 MotionEvent event = (MotionEvent) msg.obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001752 try {
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001753 deliverPointerEvent(event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001754 } finally {
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001755 event.recycle();
Jeff Brown93ed4e32010-09-23 13:51:48 -07001756 if (msg.arg1 != 0) {
1757 finishInputEvent();
1758 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001759 if (LOCAL_LOGV || WATCH_POINTER) Log.i(TAG, "Done dispatching!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001760 }
The Android Open Source Project10592532009-03-18 17:39:46 -07001761 } break;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001762 case DISPATCH_TRACKBALL: {
1763 MotionEvent event = (MotionEvent) msg.obj;
1764 try {
1765 deliverTrackballEvent(event);
1766 } finally {
1767 event.recycle();
Jeff Brown93ed4e32010-09-23 13:51:48 -07001768 if (msg.arg1 != 0) {
1769 finishInputEvent();
1770 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001771 }
1772 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001773 case DISPATCH_APP_VISIBILITY:
1774 handleAppVisibility(msg.arg1 != 0);
1775 break;
1776 case DISPATCH_GET_NEW_SURFACE:
1777 handleGetNewSurface();
1778 break;
1779 case RESIZED:
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001780 ResizedInfo ri = (ResizedInfo)msg.obj;
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001781
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001782 if (mWinFrame.width() == msg.arg1 && mWinFrame.height() == msg.arg2
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001783 && mPendingContentInsets.equals(ri.coveredInsets)
Dianne Hackbornd49258f2010-03-26 00:44:29 -07001784 && mPendingVisibleInsets.equals(ri.visibleInsets)
1785 && ((ResizedInfo)msg.obj).newConfig == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001786 break;
1787 }
1788 // fall through...
1789 case RESIZED_REPORT:
1790 if (mAdded) {
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001791 Configuration config = ((ResizedInfo)msg.obj).newConfig;
1792 if (config != null) {
Dianne Hackborn694f79b2010-03-17 19:44:59 -07001793 updateConfiguration(config, false);
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001794 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001795 mWinFrame.left = 0;
1796 mWinFrame.right = msg.arg1;
1797 mWinFrame.top = 0;
1798 mWinFrame.bottom = msg.arg2;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001799 mPendingContentInsets.set(((ResizedInfo)msg.obj).coveredInsets);
1800 mPendingVisibleInsets.set(((ResizedInfo)msg.obj).visibleInsets);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001801 if (msg.what == RESIZED_REPORT) {
1802 mReportNextDraw = true;
1803 }
Romain Guycdb86672010-03-18 18:54:50 -07001804
1805 if (mView != null) {
1806 forceLayout(mView);
1807 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001808 requestLayout();
1809 }
1810 break;
1811 case WINDOW_FOCUS_CHANGED: {
1812 if (mAdded) {
1813 boolean hasWindowFocus = msg.arg1 != 0;
1814 mAttachInfo.mHasWindowFocus = hasWindowFocus;
1815 if (hasWindowFocus) {
1816 boolean inTouchMode = msg.arg2 != 0;
Romain Guy2d4cff62010-04-09 15:39:00 -07001817 ensureTouchModeLocally(inTouchMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001818
Romain Guyc361da82010-10-25 15:29:10 -07001819 if (mAttachInfo.mHardwareRenderer != null &&
1820 mSurface != null && mSurface.isValid()) {
Romain Guyb051e892010-09-28 19:09:36 -07001821 mAttachInfo.mHardwareRenderer.initializeIfNeeded(mWidth, mHeight,
1822 mAttachInfo, mHolder);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001823 }
1824 }
Romain Guy8506ab42009-06-11 17:35:47 -07001825
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001826 mLastWasImTarget = WindowManager.LayoutParams
1827 .mayUseInputMethod(mWindowAttributes.flags);
Romain Guy8506ab42009-06-11 17:35:47 -07001828
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001829 InputMethodManager imm = InputMethodManager.peekInstance();
1830 if (mView != null) {
1831 if (hasWindowFocus && imm != null && mLastWasImTarget) {
1832 imm.startGettingWindowFocus(mView);
1833 }
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07001834 mAttachInfo.mKeyDispatchState.reset();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001835 mView.dispatchWindowFocusChanged(hasWindowFocus);
1836 }
svetoslavganov75986cf2009-05-14 22:28:01 -07001837
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001838 // Note: must be done after the focus change callbacks,
1839 // so all of the view state is set up correctly.
1840 if (hasWindowFocus) {
1841 if (imm != null && mLastWasImTarget) {
1842 imm.onWindowFocus(mView, mView.findFocus(),
1843 mWindowAttributes.softInputMode,
1844 !mHasHadWindowFocus, mWindowAttributes.flags);
1845 }
1846 // Clear the forward bit. We can just do this directly, since
1847 // the window manager doesn't care about it.
1848 mWindowAttributes.softInputMode &=
1849 ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
1850 ((WindowManager.LayoutParams)mView.getLayoutParams())
1851 .softInputMode &=
1852 ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
1853 mHasHadWindowFocus = true;
1854 }
svetoslavganov75986cf2009-05-14 22:28:01 -07001855
1856 if (hasWindowFocus && mView != null) {
1857 sendAccessibilityEvents();
1858 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001859 }
1860 } break;
1861 case DIE:
Dianne Hackborn94d69142009-09-28 22:14:42 -07001862 doDie();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001863 break;
The Android Open Source Project10592532009-03-18 17:39:46 -07001864 case DISPATCH_KEY_FROM_IME: {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001865 if (LOCAL_LOGV) Log.v(
Jeff Brownc5ed5912010-07-14 18:48:53 -07001866 TAG, "Dispatching key "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001867 + msg.obj + " from IME to " + mView);
The Android Open Source Project10592532009-03-18 17:39:46 -07001868 KeyEvent event = (KeyEvent)msg.obj;
1869 if ((event.getFlags()&KeyEvent.FLAG_FROM_SYSTEM) != 0) {
1870 // The IME is trying to say this event is from the
1871 // system! Bad bad bad!
Romain Guy812ccbe2010-06-01 14:07:24 -07001872 event = KeyEvent.changeFlags(event, event.getFlags() & ~KeyEvent.FLAG_FROM_SYSTEM);
The Android Open Source Project10592532009-03-18 17:39:46 -07001873 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001874 deliverKeyEventToViewHierarchy((KeyEvent)msg.obj, false);
The Android Open Source Project10592532009-03-18 17:39:46 -07001875 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001876 case FINISH_INPUT_CONNECTION: {
1877 InputMethodManager imm = InputMethodManager.peekInstance();
1878 if (imm != null) {
1879 imm.reportFinishInputConnection((InputConnection)msg.obj);
1880 }
1881 } break;
1882 case CHECK_FOCUS: {
1883 InputMethodManager imm = InputMethodManager.peekInstance();
1884 if (imm != null) {
1885 imm.checkFocus();
1886 }
1887 } break;
Dianne Hackbornffa42482009-09-23 22:20:11 -07001888 case CLOSE_SYSTEM_DIALOGS: {
1889 if (mView != null) {
1890 mView.onCloseSystemDialogs((String)msg.obj);
1891 }
1892 } break;
Chris Tate91e9bb32010-10-12 12:58:43 -07001893 case DISPATCH_DRAG_EVENT:
1894 case DISPATCH_DRAG_LOCATION_EVENT: {
Christopher Tatea53146c2010-09-07 11:57:52 -07001895 handleDragEvent((DragEvent)msg.obj);
1896 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001897 }
1898 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07001899
Jeff Brown93ed4e32010-09-23 13:51:48 -07001900 private void startInputEvent(Runnable finishedCallback) {
1901 if (mFinishedCallback != null) {
1902 Slog.w(TAG, "Received a new input event from the input queue but there is "
1903 + "already an unfinished input event in progress.");
1904 }
1905
1906 mFinishedCallback = finishedCallback;
1907 }
1908
1909 private void finishInputEvent() {
1910 if (LOCAL_LOGV) Log.v(TAG, "Telling window manager input event is finished");
Jeff Brown92ff1dd2010-08-11 16:16:06 -07001911
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001912 if (mFinishedCallback != null) {
1913 mFinishedCallback.run();
1914 mFinishedCallback = null;
Jeff Brown92ff1dd2010-08-11 16:16:06 -07001915 } else {
Jeff Brown93ed4e32010-09-23 13:51:48 -07001916 Slog.w(TAG, "Attempted to tell the input queue that the current input event "
1917 + "is finished but there is no input event actually in progress.");
Jeff Brown46b9ac02010-04-22 18:58:52 -07001918 }
1919 }
1920
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001921 /**
1922 * Something in the current window tells us we need to change the touch mode. For
1923 * example, we are not in touch mode, and the user touches the screen.
1924 *
1925 * If the touch mode has changed, tell the window manager, and handle it locally.
1926 *
1927 * @param inTouchMode Whether we want to be in touch mode.
1928 * @return True if the touch mode changed and focus changed was changed as a result
1929 */
1930 boolean ensureTouchMode(boolean inTouchMode) {
1931 if (DBG) Log.d("touchmode", "ensureTouchMode(" + inTouchMode + "), current "
1932 + "touch mode is " + mAttachInfo.mInTouchMode);
1933 if (mAttachInfo.mInTouchMode == inTouchMode) return false;
1934
1935 // tell the window manager
1936 try {
1937 sWindowSession.setInTouchMode(inTouchMode);
1938 } catch (RemoteException e) {
1939 throw new RuntimeException(e);
1940 }
1941
1942 // handle the change
Romain Guy2d4cff62010-04-09 15:39:00 -07001943 return ensureTouchModeLocally(inTouchMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001944 }
1945
1946 /**
1947 * Ensure that the touch mode for this window is set, and if it is changing,
1948 * take the appropriate action.
1949 * @param inTouchMode Whether we want to be in touch mode.
1950 * @return True if the touch mode changed and focus changed was changed as a result
1951 */
Romain Guy2d4cff62010-04-09 15:39:00 -07001952 private boolean ensureTouchModeLocally(boolean inTouchMode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001953 if (DBG) Log.d("touchmode", "ensureTouchModeLocally(" + inTouchMode + "), current "
1954 + "touch mode is " + mAttachInfo.mInTouchMode);
1955
1956 if (mAttachInfo.mInTouchMode == inTouchMode) return false;
1957
1958 mAttachInfo.mInTouchMode = inTouchMode;
1959 mAttachInfo.mTreeObserver.dispatchOnTouchModeChanged(inTouchMode);
1960
Romain Guy2d4cff62010-04-09 15:39:00 -07001961 return (inTouchMode) ? enterTouchMode() : leaveTouchMode();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001962 }
1963
1964 private boolean enterTouchMode() {
1965 if (mView != null) {
1966 if (mView.hasFocus()) {
1967 // note: not relying on mFocusedView here because this could
1968 // be when the window is first being added, and mFocused isn't
1969 // set yet.
1970 final View focused = mView.findFocus();
1971 if (focused != null && !focused.isFocusableInTouchMode()) {
1972
1973 final ViewGroup ancestorToTakeFocus =
1974 findAncestorToTakeFocusInTouchMode(focused);
1975 if (ancestorToTakeFocus != null) {
1976 // there is an ancestor that wants focus after its descendants that
1977 // is focusable in touch mode.. give it focus
1978 return ancestorToTakeFocus.requestFocus();
1979 } else {
1980 // nothing appropriate to have focus in touch mode, clear it out
1981 mView.unFocus();
1982 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(focused, null);
1983 mFocusedView = null;
1984 return true;
1985 }
1986 }
1987 }
1988 }
1989 return false;
1990 }
1991
1992
1993 /**
1994 * Find an ancestor of focused that wants focus after its descendants and is
1995 * focusable in touch mode.
1996 * @param focused The currently focused view.
1997 * @return An appropriate view, or null if no such view exists.
1998 */
1999 private ViewGroup findAncestorToTakeFocusInTouchMode(View focused) {
2000 ViewParent parent = focused.getParent();
2001 while (parent instanceof ViewGroup) {
2002 final ViewGroup vgParent = (ViewGroup) parent;
2003 if (vgParent.getDescendantFocusability() == ViewGroup.FOCUS_AFTER_DESCENDANTS
2004 && vgParent.isFocusableInTouchMode()) {
2005 return vgParent;
2006 }
2007 if (vgParent.isRootNamespace()) {
2008 return null;
2009 } else {
2010 parent = vgParent.getParent();
2011 }
2012 }
2013 return null;
2014 }
2015
2016 private boolean leaveTouchMode() {
2017 if (mView != null) {
2018 if (mView.hasFocus()) {
2019 // i learned the hard way to not trust mFocusedView :)
2020 mFocusedView = mView.findFocus();
2021 if (!(mFocusedView instanceof ViewGroup)) {
2022 // some view has focus, let it keep it
2023 return false;
2024 } else if (((ViewGroup)mFocusedView).getDescendantFocusability() !=
2025 ViewGroup.FOCUS_AFTER_DESCENDANTS) {
2026 // some view group has focus, and doesn't prefer its children
2027 // over itself for focus, so let them keep it.
2028 return false;
2029 }
2030 }
2031
2032 // find the best view to give focus to in this brave new non-touch-mode
2033 // world
2034 final View focused = focusSearch(null, View.FOCUS_DOWN);
2035 if (focused != null) {
2036 return focused.requestFocus(View.FOCUS_DOWN);
2037 }
2038 }
2039 return false;
2040 }
2041
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002042 private void deliverPointerEvent(MotionEvent event) {
2043 if (mTranslator != null) {
2044 mTranslator.translateEventInScreenToAppWindow(event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002045 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002046
2047 boolean handled;
2048 if (mView != null && mAdded) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002049
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002050 // enter touch mode on the down
2051 boolean isDown = event.getAction() == MotionEvent.ACTION_DOWN;
2052 if (isDown) {
2053 ensureTouchMode(true);
2054 }
2055 if(Config.LOGV) {
2056 captureMotionLog("captureDispatchPointer", event);
2057 }
2058 if (mCurScrollY != 0) {
2059 event.offsetLocation(0, mCurScrollY);
2060 }
2061 if (MEASURE_LATENCY) {
2062 lt.sample("A Dispatching TouchEvents", System.nanoTime() - event.getEventTimeNano());
2063 }
Christopher Tate2c095f32010-10-04 14:13:40 -07002064 // cache for possible drag-initiation
2065 mLastTouchPoint.x = event.getRawX();
2066 mLastTouchPoint.y = event.getRawY();
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002067 handled = mView.dispatchTouchEvent(event);
2068 if (MEASURE_LATENCY) {
2069 lt.sample("B Dispatched TouchEvents ", System.nanoTime() - event.getEventTimeNano());
2070 }
2071 if (!handled && isDown) {
2072 int edgeSlop = mViewConfiguration.getScaledEdgeSlop();
2073
2074 final int edgeFlags = event.getEdgeFlags();
2075 int direction = View.FOCUS_UP;
2076 int x = (int)event.getX();
2077 int y = (int)event.getY();
2078 final int[] deltas = new int[2];
2079
2080 if ((edgeFlags & MotionEvent.EDGE_TOP) != 0) {
2081 direction = View.FOCUS_DOWN;
2082 if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
2083 deltas[0] = edgeSlop;
2084 x += edgeSlop;
2085 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
2086 deltas[0] = -edgeSlop;
2087 x -= edgeSlop;
2088 }
2089 } else if ((edgeFlags & MotionEvent.EDGE_BOTTOM) != 0) {
2090 direction = View.FOCUS_UP;
2091 if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
2092 deltas[0] = edgeSlop;
2093 x += edgeSlop;
2094 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
2095 deltas[0] = -edgeSlop;
2096 x -= edgeSlop;
2097 }
2098 } else if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
2099 direction = View.FOCUS_RIGHT;
2100 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
2101 direction = View.FOCUS_LEFT;
2102 }
2103
2104 if (edgeFlags != 0 && mView instanceof ViewGroup) {
2105 View nearest = FocusFinder.getInstance().findNearestTouchable(
2106 ((ViewGroup) mView), x, y, direction, deltas);
2107 if (nearest != null) {
2108 event.offsetLocation(deltas[0], deltas[1]);
2109 event.setEdgeFlags(0);
2110 mView.dispatchTouchEvent(event);
2111 }
2112 }
2113 }
2114 }
2115 }
2116
2117 private void deliverTrackballEvent(MotionEvent event) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002118 if (DEBUG_TRACKBALL) Log.v(TAG, "Motion event:" + event);
2119
2120 boolean handled = false;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002121 if (mView != null && mAdded) {
2122 handled = mView.dispatchTrackballEvent(event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002123 if (handled) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002124 // If we reach this, we delivered a trackball event to mView and
2125 // mView consumed it. Because we will not translate the trackball
2126 // event into a key event, touch mode will not exit, so we exit
2127 // touch mode here.
2128 ensureTouchMode(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002129 return;
2130 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002131
2132 // Otherwise we could do something here, like changing the focus
2133 // or something?
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002134 }
2135
2136 final TrackballAxis x = mTrackballAxisX;
2137 final TrackballAxis y = mTrackballAxisY;
2138
2139 long curTime = SystemClock.uptimeMillis();
2140 if ((mLastTrackballTime+MAX_TRACKBALL_DELAY) < curTime) {
2141 // It has been too long since the last movement,
2142 // so restart at the beginning.
2143 x.reset(0);
2144 y.reset(0);
2145 mLastTrackballTime = curTime;
2146 }
2147
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002148 final int action = event.getAction();
2149 final int metastate = event.getMetaState();
2150 switch (action) {
2151 case MotionEvent.ACTION_DOWN:
2152 x.reset(2);
2153 y.reset(2);
2154 deliverKeyEvent(new KeyEvent(curTime, curTime,
2155 KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_CENTER,
2156 0, metastate), false);
2157 break;
2158 case MotionEvent.ACTION_UP:
2159 x.reset(2);
2160 y.reset(2);
2161 deliverKeyEvent(new KeyEvent(curTime, curTime,
2162 KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_CENTER,
2163 0, metastate), false);
2164 break;
2165 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002166
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002167 if (DEBUG_TRACKBALL) Log.v(TAG, "TB X=" + x.position + " step="
2168 + x.step + " dir=" + x.dir + " acc=" + x.acceleration
2169 + " move=" + event.getX()
2170 + " / Y=" + y.position + " step="
2171 + y.step + " dir=" + y.dir + " acc=" + y.acceleration
2172 + " move=" + event.getY());
2173 final float xOff = x.collect(event.getX(), event.getEventTime(), "X");
2174 final float yOff = y.collect(event.getY(), event.getEventTime(), "Y");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002175
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002176 // Generate DPAD events based on the trackball movement.
2177 // We pick the axis that has moved the most as the direction of
2178 // the DPAD. When we generate DPAD events for one axis, then the
2179 // other axis is reset -- we don't want to perform DPAD jumps due
2180 // to slight movements in the trackball when making major movements
2181 // along the other axis.
2182 int keycode = 0;
2183 int movement = 0;
2184 float accel = 1;
2185 if (xOff > yOff) {
2186 movement = x.generate((2/event.getXPrecision()));
2187 if (movement != 0) {
2188 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_RIGHT
2189 : KeyEvent.KEYCODE_DPAD_LEFT;
2190 accel = x.acceleration;
2191 y.reset(2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002192 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002193 } else if (yOff > 0) {
2194 movement = y.generate((2/event.getYPrecision()));
2195 if (movement != 0) {
2196 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_DOWN
2197 : KeyEvent.KEYCODE_DPAD_UP;
2198 accel = y.acceleration;
2199 x.reset(2);
2200 }
2201 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002202
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002203 if (keycode != 0) {
2204 if (movement < 0) movement = -movement;
2205 int accelMovement = (int)(movement * accel);
2206 if (DEBUG_TRACKBALL) Log.v(TAG, "Move: movement=" + movement
2207 + " accelMovement=" + accelMovement
2208 + " accel=" + accel);
2209 if (accelMovement > movement) {
2210 if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: "
2211 + keycode);
2212 movement--;
2213 deliverKeyEvent(new KeyEvent(curTime, curTime,
2214 KeyEvent.ACTION_MULTIPLE, keycode,
2215 accelMovement-movement, metastate), false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002216 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002217 while (movement > 0) {
2218 if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: "
2219 + keycode);
2220 movement--;
2221 curTime = SystemClock.uptimeMillis();
2222 deliverKeyEvent(new KeyEvent(curTime, curTime,
2223 KeyEvent.ACTION_DOWN, keycode, 0, event.getMetaState()), false);
2224 deliverKeyEvent(new KeyEvent(curTime, curTime,
2225 KeyEvent.ACTION_UP, keycode, 0, metastate), false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002226 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002227 mLastTrackballTime = curTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002228 }
2229 }
2230
2231 /**
2232 * @param keyCode The key code
2233 * @return True if the key is directional.
2234 */
2235 static boolean isDirectional(int keyCode) {
2236 switch (keyCode) {
2237 case KeyEvent.KEYCODE_DPAD_LEFT:
2238 case KeyEvent.KEYCODE_DPAD_RIGHT:
2239 case KeyEvent.KEYCODE_DPAD_UP:
2240 case KeyEvent.KEYCODE_DPAD_DOWN:
2241 return true;
2242 }
2243 return false;
2244 }
2245
2246 /**
2247 * Returns true if this key is a keyboard key.
2248 * @param keyEvent The key event.
2249 * @return whether this key is a keyboard key.
2250 */
2251 private static boolean isKeyboardKey(KeyEvent keyEvent) {
2252 final int convertedKey = keyEvent.getUnicodeChar();
2253 return convertedKey > 0;
2254 }
2255
2256
2257
2258 /**
2259 * See if the key event means we should leave touch mode (and leave touch
2260 * mode if so).
2261 * @param event The key event.
2262 * @return Whether this key event should be consumed (meaning the act of
2263 * leaving touch mode alone is considered the event).
2264 */
2265 private boolean checkForLeavingTouchModeAndConsume(KeyEvent event) {
Adam Powell51a6bee2010-03-15 14:07:28 -07002266 final int action = event.getAction();
2267 if (action != KeyEvent.ACTION_DOWN && action != KeyEvent.ACTION_MULTIPLE) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002268 return false;
2269 }
2270 if ((event.getFlags()&KeyEvent.FLAG_KEEP_TOUCH_MODE) != 0) {
2271 return false;
2272 }
2273
2274 // only relevant if we are in touch mode
2275 if (!mAttachInfo.mInTouchMode) {
2276 return false;
2277 }
2278
2279 // if something like an edit text has focus and the user is typing,
2280 // leave touch mode
2281 //
2282 // note: the condition of not being a keyboard key is kind of a hacky
2283 // approximation of whether we think the focused view will want the
2284 // key; if we knew for sure whether the focused view would consume
2285 // the event, that would be better.
2286 if (isKeyboardKey(event) && mView != null && mView.hasFocus()) {
2287 mFocusedView = mView.findFocus();
2288 if ((mFocusedView instanceof ViewGroup)
2289 && ((ViewGroup) mFocusedView).getDescendantFocusability() ==
2290 ViewGroup.FOCUS_AFTER_DESCENDANTS) {
2291 // something has focus, but is holding it weakly as a container
2292 return false;
2293 }
2294 if (ensureTouchMode(false)) {
2295 throw new IllegalStateException("should not have changed focus "
2296 + "when leaving touch mode while a view has focus.");
2297 }
2298 return false;
2299 }
2300
2301 if (isDirectional(event.getKeyCode())) {
2302 // no view has focus, so we leave touch mode (and find something
2303 // to give focus to). the event is consumed if we were able to
2304 // find something to give focus to.
2305 return ensureTouchMode(false);
2306 }
2307 return false;
2308 }
2309
2310 /**
Romain Guy8506ab42009-06-11 17:35:47 -07002311 * log motion events
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002312 */
2313 private static void captureMotionLog(String subTag, MotionEvent ev) {
Romain Guy8506ab42009-06-11 17:35:47 -07002314 //check dynamic switch
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002315 if (ev == null ||
2316 SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_EVENT, 0) == 0) {
2317 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002318 }
Romain Guy8506ab42009-06-11 17:35:47 -07002319
2320 StringBuilder sb = new StringBuilder(subTag + ": ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002321 sb.append(ev.getDownTime()).append(',');
2322 sb.append(ev.getEventTime()).append(',');
2323 sb.append(ev.getAction()).append(',');
Romain Guy8506ab42009-06-11 17:35:47 -07002324 sb.append(ev.getX()).append(',');
2325 sb.append(ev.getY()).append(',');
2326 sb.append(ev.getPressure()).append(',');
2327 sb.append(ev.getSize()).append(',');
2328 sb.append(ev.getMetaState()).append(',');
2329 sb.append(ev.getXPrecision()).append(',');
2330 sb.append(ev.getYPrecision()).append(',');
2331 sb.append(ev.getDeviceId()).append(',');
2332 sb.append(ev.getEdgeFlags());
2333 Log.d(TAG, sb.toString());
2334 }
2335 /**
2336 * log motion events
2337 */
2338 private static void captureKeyLog(String subTag, KeyEvent ev) {
2339 //check dynamic switch
2340 if (ev == null ||
2341 SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_EVENT, 0) == 0) {
2342 return;
2343 }
2344 StringBuilder sb = new StringBuilder(subTag + ": ");
2345 sb.append(ev.getDownTime()).append(',');
2346 sb.append(ev.getEventTime()).append(',');
2347 sb.append(ev.getAction()).append(',');
2348 sb.append(ev.getKeyCode()).append(',');
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002349 sb.append(ev.getRepeatCount()).append(',');
2350 sb.append(ev.getMetaState()).append(',');
2351 sb.append(ev.getDeviceId()).append(',');
2352 sb.append(ev.getScanCode());
Romain Guy8506ab42009-06-11 17:35:47 -07002353 Log.d(TAG, sb.toString());
2354 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002355
2356 int enqueuePendingEvent(Object event, boolean sendDone) {
2357 int seq = mPendingEventSeq+1;
2358 if (seq < 0) seq = 0;
2359 mPendingEventSeq = seq;
2360 mPendingEvents.put(seq, event);
2361 return sendDone ? seq : -seq;
2362 }
2363
2364 Object retrievePendingEvent(int seq) {
2365 if (seq < 0) seq = -seq;
2366 Object event = mPendingEvents.get(seq);
2367 if (event != null) {
2368 mPendingEvents.remove(seq);
2369 }
2370 return event;
2371 }
Romain Guy8506ab42009-06-11 17:35:47 -07002372
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002373 private void deliverKeyEvent(KeyEvent event, boolean sendDone) {
2374 // If mView is null, we just consume the key event because it doesn't
2375 // make sense to do anything else with it.
Romain Guy812ccbe2010-06-01 14:07:24 -07002376 boolean handled = mView == null || mView.dispatchKeyEventPreIme(event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002377 if (handled) {
2378 if (sendDone) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07002379 finishInputEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002380 }
2381 return;
2382 }
2383 // If it is possible for this window to interact with the input
2384 // method window, then we want to first dispatch our key events
2385 // to the input method.
2386 if (mLastWasImTarget) {
2387 InputMethodManager imm = InputMethodManager.peekInstance();
2388 if (imm != null && mView != null) {
2389 int seq = enqueuePendingEvent(event, sendDone);
2390 if (DEBUG_IMF) Log.v(TAG, "Sending key event to IME: seq="
2391 + seq + " event=" + event);
2392 imm.dispatchKeyEvent(mView.getContext(), seq, event,
2393 mInputMethodCallback);
2394 return;
2395 }
2396 }
2397 deliverKeyEventToViewHierarchy(event, sendDone);
2398 }
2399
2400 void handleFinishedEvent(int seq, boolean handled) {
2401 final KeyEvent event = (KeyEvent)retrievePendingEvent(seq);
2402 if (DEBUG_IMF) Log.v(TAG, "IME finished event: seq=" + seq
2403 + " handled=" + handled + " event=" + event);
2404 if (event != null) {
2405 final boolean sendDone = seq >= 0;
2406 if (!handled) {
2407 deliverKeyEventToViewHierarchy(event, sendDone);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002408 } else if (sendDone) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07002409 finishInputEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002410 } else {
Jeff Brownc5ed5912010-07-14 18:48:53 -07002411 Log.w(TAG, "handleFinishedEvent(seq=" + seq
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002412 + " handled=" + handled + " ev=" + event
2413 + ") neither delivering nor finishing key");
2414 }
2415 }
2416 }
Romain Guy8506ab42009-06-11 17:35:47 -07002417
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002418 private void deliverKeyEventToViewHierarchy(KeyEvent event, boolean sendDone) {
2419 try {
2420 if (mView != null && mAdded) {
2421 final int action = event.getAction();
2422 boolean isDown = (action == KeyEvent.ACTION_DOWN);
2423
2424 if (checkForLeavingTouchModeAndConsume(event)) {
2425 return;
Romain Guy8506ab42009-06-11 17:35:47 -07002426 }
2427
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002428 if (Config.LOGV) {
2429 captureKeyLog("captureDispatchKeyEvent", event);
2430 }
Joe Onorato86f67862010-11-05 18:57:34 -07002431 mFallbackEventHandler.preDispatchKeyEvent(event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002432 boolean keyHandled = mView.dispatchKeyEvent(event);
2433
Joe Onorato86f67862010-11-05 18:57:34 -07002434 if (!keyHandled) {
2435 mFallbackEventHandler.dispatchKeyEvent(event);
2436 }
2437
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002438 if (!keyHandled && isDown) {
2439 int direction = 0;
2440 switch (event.getKeyCode()) {
2441 case KeyEvent.KEYCODE_DPAD_LEFT:
2442 direction = View.FOCUS_LEFT;
2443 break;
2444 case KeyEvent.KEYCODE_DPAD_RIGHT:
2445 direction = View.FOCUS_RIGHT;
2446 break;
2447 case KeyEvent.KEYCODE_DPAD_UP:
2448 direction = View.FOCUS_UP;
2449 break;
2450 case KeyEvent.KEYCODE_DPAD_DOWN:
2451 direction = View.FOCUS_DOWN;
2452 break;
2453 }
2454
2455 if (direction != 0) {
2456
2457 View focused = mView != null ? mView.findFocus() : null;
2458 if (focused != null) {
2459 View v = focused.focusSearch(direction);
2460 boolean focusPassed = false;
2461 if (v != null && v != focused) {
2462 // do the math the get the interesting rect
2463 // of previous focused into the coord system of
2464 // newly focused view
2465 focused.getFocusedRect(mTempRect);
Dianne Hackborn1c6a8942010-03-23 16:34:20 -07002466 if (mView instanceof ViewGroup) {
2467 ((ViewGroup) mView).offsetDescendantRectToMyCoords(
2468 focused, mTempRect);
2469 ((ViewGroup) mView).offsetRectIntoDescendantCoords(
2470 v, mTempRect);
2471 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002472 focusPassed = v.requestFocus(direction, mTempRect);
2473 }
2474
2475 if (!focusPassed) {
2476 mView.dispatchUnhandledMove(focused, direction);
2477 } else {
2478 playSoundEffect(SoundEffectConstants.getContantForFocusDirection(direction));
2479 }
2480 }
2481 }
2482 }
2483 }
2484
2485 } finally {
2486 if (sendDone) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07002487 finishInputEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002488 }
2489 // Let the exception fall through -- the looper will catch
2490 // it and take care of the bad app for us.
2491 }
2492 }
2493
Christopher Tatea53146c2010-09-07 11:57:52 -07002494 /* drag/drop */
2495 private void handleDragEvent(DragEvent event) {
2496 // From the root, only drag start/end/location are dispatched. entered/exited
2497 // are determined and dispatched by the viewgroup hierarchy, who then report
2498 // that back here for ultimate reporting back to the framework.
2499 if (mView != null && mAdded) {
2500 final int what = event.mAction;
2501
2502 if (what == DragEvent.ACTION_DRAG_EXITED) {
2503 // A direct EXITED event means that the window manager knows we've just crossed
2504 // a window boundary, so the current drag target within this one must have
2505 // just been exited. Send it the usual notifications and then we're done
2506 // for now.
Chris Tate9d1ab882010-11-02 15:55:39 -07002507 mView.dispatchDragEvent(event);
Christopher Tatea53146c2010-09-07 11:57:52 -07002508 } else {
2509 // Cache the drag description when the operation starts, then fill it in
2510 // on subsequent calls as a convenience
2511 if (what == DragEvent.ACTION_DRAG_STARTED) {
Chris Tate9d1ab882010-11-02 15:55:39 -07002512 mCurrentDragView = null; // Start the current-recipient tracking
Christopher Tatea53146c2010-09-07 11:57:52 -07002513 mDragDescription = event.mClipDescription;
2514 } else {
2515 event.mClipDescription = mDragDescription;
2516 }
2517
2518 // For events with a [screen] location, translate into window coordinates
2519 if ((what == DragEvent.ACTION_DRAG_LOCATION) || (what == DragEvent.ACTION_DROP)) {
2520 mDragPoint.set(event.mX, event.mY);
2521 if (mTranslator != null) {
2522 mTranslator.translatePointInScreenToAppWindow(mDragPoint);
2523 }
2524
2525 if (mCurScrollY != 0) {
2526 mDragPoint.offset(0, mCurScrollY);
2527 }
2528
2529 event.mX = mDragPoint.x;
2530 event.mY = mDragPoint.y;
2531 }
2532
2533 // Remember who the current drag target is pre-dispatch
2534 final View prevDragView = mCurrentDragView;
2535
2536 // Now dispatch the drag/drop event
Chris Tated4533f12010-10-19 15:15:08 -07002537 boolean result = mView.dispatchDragEvent(event);
Christopher Tatea53146c2010-09-07 11:57:52 -07002538
2539 // If we changed apparent drag target, tell the OS about it
2540 if (prevDragView != mCurrentDragView) {
2541 try {
2542 if (prevDragView != null) {
2543 sWindowSession.dragRecipientExited(mWindow);
2544 }
2545 if (mCurrentDragView != null) {
2546 sWindowSession.dragRecipientEntered(mWindow);
2547 }
2548 } catch (RemoteException e) {
2549 Slog.e(TAG, "Unable to note drag target change");
2550 }
Christopher Tatea53146c2010-09-07 11:57:52 -07002551 }
Chris Tated4533f12010-10-19 15:15:08 -07002552
2553 // Report the drop result if necessary
2554 if (what == DragEvent.ACTION_DROP) {
2555 try {
2556 Log.i(TAG, "Reporting drop result: " + result);
2557 sWindowSession.reportDropResult(mWindow, result);
2558 } catch (RemoteException e) {
2559 Log.e(TAG, "Unable to report drop result");
2560 }
2561 }
Christopher Tatea53146c2010-09-07 11:57:52 -07002562 }
2563 }
2564 event.recycle();
2565 }
2566
Christopher Tate2c095f32010-10-04 14:13:40 -07002567 public void getLastTouchPoint(Point outLocation) {
2568 outLocation.x = (int) mLastTouchPoint.x;
2569 outLocation.y = (int) mLastTouchPoint.y;
2570 }
2571
Chris Tate9d1ab882010-11-02 15:55:39 -07002572 public void setDragFocus(View newDragTarget) {
Christopher Tatea53146c2010-09-07 11:57:52 -07002573 if (mCurrentDragView != newDragTarget) {
Chris Tate048691c2010-10-12 17:39:18 -07002574 mCurrentDragView = newDragTarget;
Christopher Tatea53146c2010-09-07 11:57:52 -07002575 }
Christopher Tatea53146c2010-09-07 11:57:52 -07002576 }
2577
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002578 private AudioManager getAudioManager() {
2579 if (mView == null) {
2580 throw new IllegalStateException("getAudioManager called when there is no mView");
2581 }
2582 if (mAudioManager == null) {
2583 mAudioManager = (AudioManager) mView.getContext().getSystemService(Context.AUDIO_SERVICE);
2584 }
2585 return mAudioManager;
2586 }
2587
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002588 private int relayoutWindow(WindowManager.LayoutParams params, int viewVisibility,
2589 boolean insetsPending) throws RemoteException {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002590
2591 float appScale = mAttachInfo.mApplicationScale;
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002592 boolean restore = false;
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002593 if (params != null && mTranslator != null) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07002594 restore = true;
2595 params.backup();
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002596 mTranslator.translateWindowLayout(params);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002597 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002598 if (params != null) {
2599 if (DBG) Log.d(TAG, "WindowLayout in layoutWindow:" + params);
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002600 }
Dianne Hackborn694f79b2010-03-17 19:44:59 -07002601 mPendingConfiguration.seq = 0;
Dianne Hackbornf123e492010-09-24 11:16:23 -07002602 //Log.d(TAG, ">>>>>> CALLING relayout");
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002603 int relayoutResult = sWindowSession.relayout(
2604 mWindow, params,
Mitsuru Oshima61324e52009-07-21 15:40:36 -07002605 (int) (mView.mMeasuredWidth * appScale + 0.5f),
2606 (int) (mView.mMeasuredHeight * appScale + 0.5f),
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002607 viewVisibility, insetsPending, mWinFrame,
Dianne Hackborn694f79b2010-03-17 19:44:59 -07002608 mPendingContentInsets, mPendingVisibleInsets,
2609 mPendingConfiguration, mSurface);
Dianne Hackbornf123e492010-09-24 11:16:23 -07002610 //Log.d(TAG, "<<<<<< BACK FROM relayout");
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002611 if (restore) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07002612 params.restore();
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002613 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002614
2615 if (mTranslator != null) {
2616 mTranslator.translateRectInScreenToAppWinFrame(mWinFrame);
2617 mTranslator.translateRectInScreenToAppWindow(mPendingContentInsets);
2618 mTranslator.translateRectInScreenToAppWindow(mPendingVisibleInsets);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002619 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002620 return relayoutResult;
2621 }
Romain Guy8506ab42009-06-11 17:35:47 -07002622
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002623 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002624 * {@inheritDoc}
2625 */
2626 public void playSoundEffect(int effectId) {
2627 checkThread();
2628
Jean-Michel Trivi13b18fd2010-05-05 09:18:15 -07002629 try {
2630 final AudioManager audioManager = getAudioManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002631
Jean-Michel Trivi13b18fd2010-05-05 09:18:15 -07002632 switch (effectId) {
2633 case SoundEffectConstants.CLICK:
2634 audioManager.playSoundEffect(AudioManager.FX_KEY_CLICK);
2635 return;
2636 case SoundEffectConstants.NAVIGATION_DOWN:
2637 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_DOWN);
2638 return;
2639 case SoundEffectConstants.NAVIGATION_LEFT:
2640 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_LEFT);
2641 return;
2642 case SoundEffectConstants.NAVIGATION_RIGHT:
2643 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_RIGHT);
2644 return;
2645 case SoundEffectConstants.NAVIGATION_UP:
2646 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_UP);
2647 return;
2648 default:
2649 throw new IllegalArgumentException("unknown effect id " + effectId +
2650 " not defined in " + SoundEffectConstants.class.getCanonicalName());
2651 }
2652 } catch (IllegalStateException e) {
2653 // Exception thrown by getAudioManager() when mView is null
2654 Log.e(TAG, "FATAL EXCEPTION when attempting to play sound effect: " + e);
2655 e.printStackTrace();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002656 }
2657 }
2658
2659 /**
2660 * {@inheritDoc}
2661 */
2662 public boolean performHapticFeedback(int effectId, boolean always) {
2663 try {
2664 return sWindowSession.performHapticFeedback(mWindow, effectId, always);
2665 } catch (RemoteException e) {
2666 return false;
2667 }
2668 }
2669
2670 /**
2671 * {@inheritDoc}
2672 */
2673 public View focusSearch(View focused, int direction) {
2674 checkThread();
2675 if (!(mView instanceof ViewGroup)) {
2676 return null;
2677 }
2678 return FocusFinder.getInstance().findNextFocus((ViewGroup) mView, focused, direction);
2679 }
2680
2681 public void debug() {
2682 mView.debug();
2683 }
2684
2685 public void die(boolean immediate) {
Dianne Hackborn94d69142009-09-28 22:14:42 -07002686 if (immediate) {
2687 doDie();
2688 } else {
2689 sendEmptyMessage(DIE);
2690 }
2691 }
2692
2693 void doDie() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002694 checkThread();
Jeff Brownb75fa302010-07-15 23:47:29 -07002695 if (LOCAL_LOGV) Log.v(TAG, "DIE in " + this + " of " + mSurface);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002696 synchronized (this) {
2697 if (mAdded && !mFirst) {
Romain Guy29d89972010-09-22 16:10:57 -07002698 destroyHardwareRenderer();
2699
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002700 int viewVisibility = mView.getVisibility();
2701 boolean viewVisibilityChanged = mViewVisibility != viewVisibility;
2702 if (mWindowAttributesChanged || viewVisibilityChanged) {
2703 // If layout params have been changed, first give them
2704 // to the window manager to make sure it has the correct
2705 // animation info.
2706 try {
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002707 if ((relayoutWindow(mWindowAttributes, viewVisibility, false)
2708 & WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002709 sWindowSession.finishDrawing(mWindow);
2710 }
2711 } catch (RemoteException e) {
2712 }
2713 }
2714
Dianne Hackborn0586a1b2009-09-06 21:08:27 -07002715 mSurface.release();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002716 }
2717 if (mAdded) {
2718 mAdded = false;
Dianne Hackborn94d69142009-09-28 22:14:42 -07002719 dispatchDetachedFromWindow();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002720 }
2721 }
2722 }
2723
Romain Guy29d89972010-09-22 16:10:57 -07002724 private void destroyHardwareRenderer() {
Romain Guyb051e892010-09-28 19:09:36 -07002725 if (mAttachInfo.mHardwareRenderer != null) {
2726 mAttachInfo.mHardwareRenderer.destroy(true);
2727 mAttachInfo.mHardwareRenderer = null;
Romain Guy29d89972010-09-22 16:10:57 -07002728 mAttachInfo.mHardwareAccelerated = false;
2729 }
2730 }
2731
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002732 public void dispatchFinishedEvent(int seq, boolean handled) {
2733 Message msg = obtainMessage(FINISHED_EVENT);
2734 msg.arg1 = seq;
2735 msg.arg2 = handled ? 1 : 0;
2736 sendMessage(msg);
2737 }
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002738
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002739 public void dispatchResized(int w, int h, Rect coveredInsets,
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002740 Rect visibleInsets, boolean reportDraw, Configuration newConfig) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002741 if (DEBUG_LAYOUT) Log.v(TAG, "Resizing " + this + ": w=" + w
2742 + " h=" + h + " coveredInsets=" + coveredInsets.toShortString()
2743 + " visibleInsets=" + visibleInsets.toShortString()
2744 + " reportDraw=" + reportDraw);
2745 Message msg = obtainMessage(reportDraw ? RESIZED_REPORT :RESIZED);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002746 if (mTranslator != null) {
2747 mTranslator.translateRectInScreenToAppWindow(coveredInsets);
2748 mTranslator.translateRectInScreenToAppWindow(visibleInsets);
2749 w *= mTranslator.applicationInvertedScale;
2750 h *= mTranslator.applicationInvertedScale;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002751 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002752 msg.arg1 = w;
2753 msg.arg2 = h;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002754 ResizedInfo ri = new ResizedInfo();
2755 ri.coveredInsets = new Rect(coveredInsets);
2756 ri.visibleInsets = new Rect(visibleInsets);
2757 ri.newConfig = newConfig;
2758 msg.obj = ri;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002759 sendMessage(msg);
2760 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002761
2762 private Runnable mFinishedCallback;
2763
2764 private final InputHandler mInputHandler = new InputHandler() {
2765 public void handleKey(KeyEvent event, Runnable finishedCallback) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07002766 startInputEvent(finishedCallback);
Jeff Brown92ff1dd2010-08-11 16:16:06 -07002767 dispatchKey(event, true);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002768 }
2769
Jeff Brownc5ed5912010-07-14 18:48:53 -07002770 public void handleMotion(MotionEvent event, Runnable finishedCallback) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07002771 startInputEvent(finishedCallback);
2772 dispatchMotion(event, true);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002773 }
2774 };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002775
2776 public void dispatchKey(KeyEvent event) {
Jeff Brown92ff1dd2010-08-11 16:16:06 -07002777 dispatchKey(event, false);
2778 }
2779
2780 private void dispatchKey(KeyEvent event, boolean sendDone) {
2781 //noinspection ConstantConditions
2782 if (false && event.getAction() == KeyEvent.ACTION_DOWN) {
2783 if (event.getKeyCode() == KeyEvent.KEYCODE_CAMERA) {
Romain Guy812ccbe2010-06-01 14:07:24 -07002784 if (DBG) Log.d("keydisp", "===================================================");
2785 if (DBG) Log.d("keydisp", "Focused view Hierarchy is:");
2786
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002787 debug();
2788
Romain Guy812ccbe2010-06-01 14:07:24 -07002789 if (DBG) Log.d("keydisp", "===================================================");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002790 }
2791 }
2792
2793 Message msg = obtainMessage(DISPATCH_KEY);
2794 msg.obj = event;
Jeff Brown92ff1dd2010-08-11 16:16:06 -07002795 msg.arg1 = sendDone ? 1 : 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002796
2797 if (LOCAL_LOGV) Log.v(
Jeff Brownc5ed5912010-07-14 18:48:53 -07002798 TAG, "sending key " + event + " to " + mView);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002799
2800 sendMessageAtTime(msg, event.getEventTime());
2801 }
Jeff Brownc5ed5912010-07-14 18:48:53 -07002802
2803 public void dispatchMotion(MotionEvent event) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07002804 dispatchMotion(event, false);
2805 }
2806
2807 private void dispatchMotion(MotionEvent event, boolean sendDone) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07002808 int source = event.getSource();
2809 if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07002810 dispatchPointer(event, sendDone);
Jeff Brownc5ed5912010-07-14 18:48:53 -07002811 } else if ((source & InputDevice.SOURCE_CLASS_TRACKBALL) != 0) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07002812 dispatchTrackball(event, sendDone);
Jeff Brownc5ed5912010-07-14 18:48:53 -07002813 } else {
2814 // TODO
2815 Log.v(TAG, "Dropping unsupported motion event (unimplemented): " + event);
Jeff Brown93ed4e32010-09-23 13:51:48 -07002816 if (sendDone) {
2817 finishInputEvent();
2818 }
Jeff Brownc5ed5912010-07-14 18:48:53 -07002819 }
2820 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002821
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002822 public void dispatchPointer(MotionEvent event) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07002823 dispatchPointer(event, false);
2824 }
2825
2826 private void dispatchPointer(MotionEvent event, boolean sendDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002827 Message msg = obtainMessage(DISPATCH_POINTER);
2828 msg.obj = event;
Jeff Brown93ed4e32010-09-23 13:51:48 -07002829 msg.arg1 = sendDone ? 1 : 0;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002830 sendMessageAtTime(msg, event.getEventTime());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002831 }
2832
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002833 public void dispatchTrackball(MotionEvent event) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07002834 dispatchTrackball(event, false);
2835 }
2836
2837 private void dispatchTrackball(MotionEvent event, boolean sendDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002838 Message msg = obtainMessage(DISPATCH_TRACKBALL);
2839 msg.obj = event;
Jeff Brown93ed4e32010-09-23 13:51:48 -07002840 msg.arg1 = sendDone ? 1 : 0;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002841 sendMessageAtTime(msg, event.getEventTime());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002842 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002843
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002844 public void dispatchAppVisibility(boolean visible) {
2845 Message msg = obtainMessage(DISPATCH_APP_VISIBILITY);
2846 msg.arg1 = visible ? 1 : 0;
2847 sendMessage(msg);
2848 }
2849
2850 public void dispatchGetNewSurface() {
2851 Message msg = obtainMessage(DISPATCH_GET_NEW_SURFACE);
2852 sendMessage(msg);
2853 }
2854
2855 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
2856 Message msg = Message.obtain();
2857 msg.what = WINDOW_FOCUS_CHANGED;
2858 msg.arg1 = hasFocus ? 1 : 0;
2859 msg.arg2 = inTouchMode ? 1 : 0;
2860 sendMessage(msg);
2861 }
2862
Dianne Hackbornffa42482009-09-23 22:20:11 -07002863 public void dispatchCloseSystemDialogs(String reason) {
2864 Message msg = Message.obtain();
2865 msg.what = CLOSE_SYSTEM_DIALOGS;
2866 msg.obj = reason;
2867 sendMessage(msg);
2868 }
Christopher Tatea53146c2010-09-07 11:57:52 -07002869
2870 public void dispatchDragEvent(DragEvent event) {
Chris Tate91e9bb32010-10-12 12:58:43 -07002871 final int what;
2872 if (event.getAction() == DragEvent.ACTION_DRAG_LOCATION) {
2873 what = DISPATCH_DRAG_LOCATION_EVENT;
2874 removeMessages(what);
2875 } else {
2876 what = DISPATCH_DRAG_EVENT;
2877 }
2878 Message msg = obtainMessage(what, event);
Christopher Tatea53146c2010-09-07 11:57:52 -07002879 sendMessage(msg);
2880 }
2881
svetoslavganov75986cf2009-05-14 22:28:01 -07002882 /**
2883 * The window is getting focus so if there is anything focused/selected
2884 * send an {@link AccessibilityEvent} to announce that.
2885 */
2886 private void sendAccessibilityEvents() {
2887 if (!AccessibilityManager.getInstance(mView.getContext()).isEnabled()) {
2888 return;
2889 }
2890 mView.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
2891 View focusedView = mView.findFocus();
2892 if (focusedView != null && focusedView != mView) {
2893 focusedView.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
2894 }
2895 }
2896
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002897 public boolean showContextMenuForChild(View originalView) {
2898 return false;
2899 }
2900
Adam Powell6e346362010-07-23 10:18:23 -07002901 public ActionMode startActionModeForChild(View originalView, ActionMode.Callback callback) {
2902 return null;
2903 }
2904
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002905 public void createContextMenu(ContextMenu menu) {
2906 }
2907
2908 public void childDrawableStateChanged(View child) {
2909 }
2910
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002911 void checkThread() {
2912 if (mThread != Thread.currentThread()) {
2913 throw new CalledFromWrongThreadException(
2914 "Only the original thread that created a view hierarchy can touch its views.");
2915 }
2916 }
2917
2918 public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
2919 // ViewRoot never intercepts touch event, so this can be a no-op
2920 }
2921
2922 public boolean requestChildRectangleOnScreen(View child, Rect rectangle,
2923 boolean immediate) {
2924 return scrollToRectOrFocus(rectangle, immediate);
2925 }
Romain Guy8506ab42009-06-11 17:35:47 -07002926
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07002927 class TakenSurfaceHolder extends BaseSurfaceHolder {
2928 @Override
2929 public boolean onAllowLockCanvas() {
2930 return mDrawingAllowed;
2931 }
2932
2933 @Override
2934 public void onRelayoutContainer() {
2935 // Not currently interesting -- from changing between fixed and layout size.
2936 }
2937
2938 public void setFormat(int format) {
2939 ((RootViewSurfaceTaker)mView).setSurfaceFormat(format);
2940 }
2941
2942 public void setType(int type) {
2943 ((RootViewSurfaceTaker)mView).setSurfaceType(type);
2944 }
2945
2946 @Override
2947 public void onUpdateSurface() {
2948 // We take care of format and type changes on our own.
2949 throw new IllegalStateException("Shouldn't be here");
2950 }
2951
2952 public boolean isCreating() {
2953 return mIsCreating;
2954 }
2955
2956 @Override
2957 public void setFixedSize(int width, int height) {
2958 throw new UnsupportedOperationException(
2959 "Currently only support sizing from layout");
2960 }
2961
2962 public void setKeepScreenOn(boolean screenOn) {
2963 ((RootViewSurfaceTaker)mView).setSurfaceKeepScreenOn(screenOn);
2964 }
2965 }
2966
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002967 static class InputMethodCallback extends IInputMethodCallback.Stub {
2968 private WeakReference<ViewRoot> mViewRoot;
2969
2970 public InputMethodCallback(ViewRoot viewRoot) {
2971 mViewRoot = new WeakReference<ViewRoot>(viewRoot);
2972 }
Romain Guy8506ab42009-06-11 17:35:47 -07002973
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002974 public void finishedEvent(int seq, boolean handled) {
2975 final ViewRoot viewRoot = mViewRoot.get();
2976 if (viewRoot != null) {
2977 viewRoot.dispatchFinishedEvent(seq, handled);
2978 }
2979 }
2980
2981 public void sessionCreated(IInputMethodSession session) throws RemoteException {
2982 // Stub -- not for use in the client.
2983 }
2984 }
Romain Guy8506ab42009-06-11 17:35:47 -07002985
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002986 static class W extends IWindow.Stub {
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002987 private final WeakReference<ViewRoot> mViewRoot;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002988
Romain Guyfb8b7632010-08-23 21:05:08 -07002989 W(ViewRoot viewRoot) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002990 mViewRoot = new WeakReference<ViewRoot>(viewRoot);
2991 }
2992
Romain Guyfb8b7632010-08-23 21:05:08 -07002993 public void resized(int w, int h, Rect coveredInsets, Rect visibleInsets,
2994 boolean reportDraw, Configuration newConfig) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002995 final ViewRoot viewRoot = mViewRoot.get();
2996 if (viewRoot != null) {
Romain Guyfb8b7632010-08-23 21:05:08 -07002997 viewRoot.dispatchResized(w, h, coveredInsets, visibleInsets, reportDraw, newConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002998 }
2999 }
3000
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003001 public void dispatchAppVisibility(boolean visible) {
3002 final ViewRoot viewRoot = mViewRoot.get();
3003 if (viewRoot != null) {
3004 viewRoot.dispatchAppVisibility(visible);
3005 }
3006 }
3007
3008 public void dispatchGetNewSurface() {
3009 final ViewRoot viewRoot = mViewRoot.get();
3010 if (viewRoot != null) {
3011 viewRoot.dispatchGetNewSurface();
3012 }
3013 }
3014
3015 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
3016 final ViewRoot viewRoot = mViewRoot.get();
3017 if (viewRoot != null) {
3018 viewRoot.windowFocusChanged(hasFocus, inTouchMode);
3019 }
3020 }
3021
3022 private static int checkCallingPermission(String permission) {
3023 if (!Process.supportsProcesses()) {
3024 return PackageManager.PERMISSION_GRANTED;
3025 }
3026
3027 try {
3028 return ActivityManagerNative.getDefault().checkPermission(
3029 permission, Binder.getCallingPid(), Binder.getCallingUid());
3030 } catch (RemoteException e) {
3031 return PackageManager.PERMISSION_DENIED;
3032 }
3033 }
3034
3035 public void executeCommand(String command, String parameters, ParcelFileDescriptor out) {
3036 final ViewRoot viewRoot = mViewRoot.get();
3037 if (viewRoot != null) {
3038 final View view = viewRoot.mView;
3039 if (view != null) {
3040 if (checkCallingPermission(Manifest.permission.DUMP) !=
3041 PackageManager.PERMISSION_GRANTED) {
3042 throw new SecurityException("Insufficient permissions to invoke"
3043 + " executeCommand() from pid=" + Binder.getCallingPid()
3044 + ", uid=" + Binder.getCallingUid());
3045 }
3046
3047 OutputStream clientStream = null;
3048 try {
3049 clientStream = new ParcelFileDescriptor.AutoCloseOutputStream(out);
3050 ViewDebug.dispatchCommand(view, command, parameters, clientStream);
3051 } catch (IOException e) {
3052 e.printStackTrace();
3053 } finally {
3054 if (clientStream != null) {
3055 try {
3056 clientStream.close();
3057 } catch (IOException e) {
3058 e.printStackTrace();
3059 }
3060 }
3061 }
3062 }
3063 }
3064 }
Dianne Hackborn72c82ab2009-08-11 21:13:54 -07003065
Dianne Hackbornffa42482009-09-23 22:20:11 -07003066 public void closeSystemDialogs(String reason) {
3067 final ViewRoot viewRoot = mViewRoot.get();
3068 if (viewRoot != null) {
3069 viewRoot.dispatchCloseSystemDialogs(reason);
3070 }
3071 }
3072
Marco Nelissenbf6956b2009-11-09 15:21:13 -08003073 public void dispatchWallpaperOffsets(float x, float y, float xStep, float yStep,
3074 boolean sync) {
Dianne Hackborn19382ac2009-09-11 21:13:37 -07003075 if (sync) {
3076 try {
3077 sWindowSession.wallpaperOffsetsComplete(asBinder());
3078 } catch (RemoteException e) {
3079 }
3080 }
Dianne Hackborn72c82ab2009-08-11 21:13:54 -07003081 }
Dianne Hackborn75804932009-10-20 20:15:20 -07003082
3083 public void dispatchWallpaperCommand(String action, int x, int y,
3084 int z, Bundle extras, boolean sync) {
3085 if (sync) {
3086 try {
3087 sWindowSession.wallpaperCommandComplete(asBinder(), null);
3088 } catch (RemoteException e) {
3089 }
3090 }
3091 }
Christopher Tatea53146c2010-09-07 11:57:52 -07003092
3093 /* Drag/drop */
3094 public void dispatchDragEvent(DragEvent event) {
3095 final ViewRoot viewRoot = mViewRoot.get();
3096 if (viewRoot != null) {
3097 viewRoot.dispatchDragEvent(event);
3098 }
3099 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003100 }
3101
3102 /**
3103 * Maintains state information for a single trackball axis, generating
3104 * discrete (DPAD) movements based on raw trackball motion.
3105 */
3106 static final class TrackballAxis {
3107 /**
3108 * The maximum amount of acceleration we will apply.
3109 */
3110 static final float MAX_ACCELERATION = 20;
Romain Guy8506ab42009-06-11 17:35:47 -07003111
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003112 /**
3113 * The maximum amount of time (in milliseconds) between events in order
3114 * for us to consider the user to be doing fast trackball movements,
3115 * and thus apply an acceleration.
3116 */
3117 static final long FAST_MOVE_TIME = 150;
Romain Guy8506ab42009-06-11 17:35:47 -07003118
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003119 /**
3120 * Scaling factor to the time (in milliseconds) between events to how
3121 * much to multiple/divide the current acceleration. When movement
3122 * is < FAST_MOVE_TIME this multiplies the acceleration; when >
3123 * FAST_MOVE_TIME it divides it.
3124 */
3125 static final float ACCEL_MOVE_SCALING_FACTOR = (1.0f/40);
Romain Guy8506ab42009-06-11 17:35:47 -07003126
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003127 float position;
3128 float absPosition;
3129 float acceleration = 1;
3130 long lastMoveTime = 0;
3131 int step;
3132 int dir;
3133 int nonAccelMovement;
3134
3135 void reset(int _step) {
3136 position = 0;
3137 acceleration = 1;
3138 lastMoveTime = 0;
3139 step = _step;
3140 dir = 0;
3141 }
3142
3143 /**
3144 * Add trackball movement into the state. If the direction of movement
3145 * has been reversed, the state is reset before adding the
3146 * movement (so that you don't have to compensate for any previously
3147 * collected movement before see the result of the movement in the
3148 * new direction).
3149 *
3150 * @return Returns the absolute value of the amount of movement
3151 * collected so far.
3152 */
3153 float collect(float off, long time, String axis) {
3154 long normTime;
3155 if (off > 0) {
3156 normTime = (long)(off * FAST_MOVE_TIME);
3157 if (dir < 0) {
3158 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to positive!");
3159 position = 0;
3160 step = 0;
3161 acceleration = 1;
3162 lastMoveTime = 0;
3163 }
3164 dir = 1;
3165 } else if (off < 0) {
3166 normTime = (long)((-off) * FAST_MOVE_TIME);
3167 if (dir > 0) {
3168 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to negative!");
3169 position = 0;
3170 step = 0;
3171 acceleration = 1;
3172 lastMoveTime = 0;
3173 }
3174 dir = -1;
3175 } else {
3176 normTime = 0;
3177 }
Romain Guy8506ab42009-06-11 17:35:47 -07003178
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003179 // The number of milliseconds between each movement that is
3180 // considered "normal" and will not result in any acceleration
3181 // or deceleration, scaled by the offset we have here.
3182 if (normTime > 0) {
3183 long delta = time - lastMoveTime;
3184 lastMoveTime = time;
3185 float acc = acceleration;
3186 if (delta < normTime) {
3187 // The user is scrolling rapidly, so increase acceleration.
3188 float scale = (normTime-delta) * ACCEL_MOVE_SCALING_FACTOR;
3189 if (scale > 1) acc *= scale;
3190 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " accelerate: off="
3191 + off + " normTime=" + normTime + " delta=" + delta
3192 + " scale=" + scale + " acc=" + acc);
3193 acceleration = acc < MAX_ACCELERATION ? acc : MAX_ACCELERATION;
3194 } else {
3195 // The user is scrolling slowly, so decrease acceleration.
3196 float scale = (delta-normTime) * ACCEL_MOVE_SCALING_FACTOR;
3197 if (scale > 1) acc /= scale;
3198 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " deccelerate: off="
3199 + off + " normTime=" + normTime + " delta=" + delta
3200 + " scale=" + scale + " acc=" + acc);
3201 acceleration = acc > 1 ? acc : 1;
3202 }
3203 }
3204 position += off;
3205 return (absPosition = Math.abs(position));
3206 }
3207
3208 /**
3209 * Generate the number of discrete movement events appropriate for
3210 * the currently collected trackball movement.
3211 *
3212 * @param precision The minimum movement required to generate the
3213 * first discrete movement.
3214 *
3215 * @return Returns the number of discrete movements, either positive
3216 * or negative, or 0 if there is not enough trackball movement yet
3217 * for a discrete movement.
3218 */
3219 int generate(float precision) {
3220 int movement = 0;
3221 nonAccelMovement = 0;
3222 do {
3223 final int dir = position >= 0 ? 1 : -1;
3224 switch (step) {
3225 // If we are going to execute the first step, then we want
3226 // to do this as soon as possible instead of waiting for
3227 // a full movement, in order to make things look responsive.
3228 case 0:
3229 if (absPosition < precision) {
3230 return movement;
3231 }
3232 movement += dir;
3233 nonAccelMovement += dir;
3234 step = 1;
3235 break;
3236 // If we have generated the first movement, then we need
3237 // to wait for the second complete trackball motion before
3238 // generating the second discrete movement.
3239 case 1:
3240 if (absPosition < 2) {
3241 return movement;
3242 }
3243 movement += dir;
3244 nonAccelMovement += dir;
3245 position += dir > 0 ? -2 : 2;
3246 absPosition = Math.abs(position);
3247 step = 2;
3248 break;
3249 // After the first two, we generate discrete movements
3250 // consistently with the trackball, applying an acceleration
3251 // if the trackball is moving quickly. This is a simple
3252 // acceleration on top of what we already compute based
3253 // on how quickly the wheel is being turned, to apply
3254 // a longer increasing acceleration to continuous movement
3255 // in one direction.
3256 default:
3257 if (absPosition < 1) {
3258 return movement;
3259 }
3260 movement += dir;
3261 position += dir >= 0 ? -1 : 1;
3262 absPosition = Math.abs(position);
3263 float acc = acceleration;
3264 acc *= 1.1f;
3265 acceleration = acc < MAX_ACCELERATION ? acc : acceleration;
3266 break;
3267 }
3268 } while (true);
3269 }
3270 }
3271
3272 public static final class CalledFromWrongThreadException extends AndroidRuntimeException {
3273 public CalledFromWrongThreadException(String msg) {
3274 super(msg);
3275 }
3276 }
3277
3278 private SurfaceHolder mHolder = new SurfaceHolder() {
3279 // we only need a SurfaceHolder for opengl. it would be nice
3280 // to implement everything else though, especially the callback
3281 // support (opengl doesn't make use of it right now, but eventually
3282 // will).
3283 public Surface getSurface() {
3284 return mSurface;
3285 }
3286
3287 public boolean isCreating() {
3288 return false;
3289 }
3290
3291 public void addCallback(Callback callback) {
3292 }
3293
3294 public void removeCallback(Callback callback) {
3295 }
3296
3297 public void setFixedSize(int width, int height) {
3298 }
3299
3300 public void setSizeFromLayout() {
3301 }
3302
3303 public void setFormat(int format) {
3304 }
3305
3306 public void setType(int type) {
3307 }
3308
3309 public void setKeepScreenOn(boolean screenOn) {
3310 }
3311
3312 public Canvas lockCanvas() {
3313 return null;
3314 }
3315
3316 public Canvas lockCanvas(Rect dirty) {
3317 return null;
3318 }
3319
3320 public void unlockCanvasAndPost(Canvas canvas) {
3321 }
3322 public Rect getSurfaceFrame() {
3323 return null;
3324 }
3325 };
3326
3327 static RunQueue getRunQueue() {
3328 RunQueue rq = sRunQueues.get();
3329 if (rq != null) {
3330 return rq;
3331 }
3332 rq = new RunQueue();
3333 sRunQueues.set(rq);
3334 return rq;
3335 }
Romain Guy8506ab42009-06-11 17:35:47 -07003336
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003337 /**
3338 * @hide
3339 */
3340 static final class RunQueue {
3341 private final ArrayList<HandlerAction> mActions = new ArrayList<HandlerAction>();
3342
3343 void post(Runnable action) {
3344 postDelayed(action, 0);
3345 }
3346
3347 void postDelayed(Runnable action, long delayMillis) {
3348 HandlerAction handlerAction = new HandlerAction();
3349 handlerAction.action = action;
3350 handlerAction.delay = delayMillis;
3351
3352 synchronized (mActions) {
3353 mActions.add(handlerAction);
3354 }
3355 }
3356
3357 void removeCallbacks(Runnable action) {
3358 final HandlerAction handlerAction = new HandlerAction();
3359 handlerAction.action = action;
3360
3361 synchronized (mActions) {
3362 final ArrayList<HandlerAction> actions = mActions;
3363
3364 while (actions.remove(handlerAction)) {
3365 // Keep going
3366 }
3367 }
3368 }
3369
3370 void executeActions(Handler handler) {
3371 synchronized (mActions) {
3372 final ArrayList<HandlerAction> actions = mActions;
3373 final int count = actions.size();
3374
3375 for (int i = 0; i < count; i++) {
3376 final HandlerAction handlerAction = actions.get(i);
3377 handler.postDelayed(handlerAction.action, handlerAction.delay);
3378 }
3379
Romain Guy15df6702009-08-17 20:17:30 -07003380 actions.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003381 }
3382 }
3383
3384 private static class HandlerAction {
3385 Runnable action;
3386 long delay;
3387
3388 @Override
3389 public boolean equals(Object o) {
3390 if (this == o) return true;
3391 if (o == null || getClass() != o.getClass()) return false;
3392
3393 HandlerAction that = (HandlerAction) o;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003394 return !(action != null ? !action.equals(that.action) : that.action != null);
3395
3396 }
3397
3398 @Override
3399 public int hashCode() {
3400 int result = action != null ? action.hashCode() : 0;
3401 result = 31 * result + (int) (delay ^ (delay >>> 32));
3402 return result;
3403 }
3404 }
3405 }
3406
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003407 private static native void nativeShowFPS(Canvas canvas, int durationMillis);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003408}