blob: d9321416ab97598971b06de9ff56a4cb81c3b966 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.view;
18
Romain Guy6b7bd242010-10-06 19:49:23 -070019import android.Manifest;
20import android.app.ActivityManagerNative;
21import android.content.ClipDescription;
22import android.content.ComponentCallbacks;
23import android.content.Context;
24import android.content.pm.PackageManager;
25import android.content.res.CompatibilityInfo;
26import android.content.res.Configuration;
27import android.content.res.Resources;
Dianne Hackborn0f761d62010-11-30 22:06:10 -080028import android.graphics.Bitmap;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080029import android.graphics.Canvas;
Dianne Hackborn0f761d62010-11-30 22:06:10 -080030import android.graphics.Paint;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080031import android.graphics.PixelFormat;
Christopher Tate2c095f32010-10-04 14:13:40 -070032import android.graphics.Point;
Christopher Tatea53146c2010-09-07 11:57:52 -070033import android.graphics.PointF;
Romain Guy6b7bd242010-10-06 19:49:23 -070034import android.graphics.PorterDuff;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080035import android.graphics.Rect;
36import android.graphics.Region;
Romain Guy6b7bd242010-10-06 19:49:23 -070037import android.media.AudioManager;
38import android.os.Binder;
39import android.os.Bundle;
40import android.os.Debug;
41import android.os.Handler;
42import android.os.LatencyTimer;
43import android.os.Looper;
44import android.os.Message;
45import android.os.ParcelFileDescriptor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080046import android.os.Process;
Romain Guy6b7bd242010-10-06 19:49:23 -070047import android.os.RemoteException;
48import android.os.ServiceManager;
49import android.os.SystemClock;
50import android.os.SystemProperties;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080051import android.util.AndroidRuntimeException;
52import android.util.Config;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -070053import android.util.DisplayMetrics;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080054import android.util.EventLog;
Romain Guy6b7bd242010-10-06 19:49:23 -070055import android.util.Log;
Chet Haase949dbf72010-08-11 18:41:06 -070056import android.util.Slog;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080057import android.util.SparseArray;
Dianne Hackborn711e62a2010-11-29 16:38:22 -080058import android.util.TypedValue;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080059import android.view.View.MeasureSpec;
svetoslavganov75986cf2009-05-14 22:28:01 -070060import android.view.accessibility.AccessibilityEvent;
61import android.view.accessibility.AccessibilityManager;
Dianne Hackborn0f761d62010-11-30 22:06:10 -080062import android.view.animation.AccelerateDecelerateInterpolator;
63import android.view.animation.Interpolator;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080064import android.view.inputmethod.InputConnection;
65import android.view.inputmethod.InputMethodManager;
66import android.widget.Scroller;
Joe Onorato86f67862010-11-05 18:57:34 -070067import com.android.internal.policy.PolicyManager;
Romain Guy6b7bd242010-10-06 19:49:23 -070068import com.android.internal.view.BaseSurfaceHolder;
69import com.android.internal.view.IInputMethodCallback;
70import com.android.internal.view.IInputMethodSession;
71import com.android.internal.view.RootViewSurfaceTaker;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080072
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080073import java.io.IOException;
74import java.io.OutputStream;
Romain Guy6b7bd242010-10-06 19:49:23 -070075import java.lang.ref.WeakReference;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080076import java.util.ArrayList;
77
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080078/**
79 * The top of a view hierarchy, implementing the needed protocol between View
80 * and the WindowManager. This is for the most part an internal implementation
81 * detail of {@link WindowManagerImpl}.
82 *
83 * {@hide}
84 */
Romain Guy812ccbe2010-06-01 14:07:24 -070085@SuppressWarnings({"EmptyCatchBlock", "PointlessBooleanExpression"})
Dianne Hackborn0f761d62010-11-30 22:06:10 -080086public final class ViewRoot extends Handler implements ViewParent,
87 View.AttachInfo.Callbacks, HardwareRenderer.HardwareDrawCallbacks {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080088 private static final String TAG = "ViewRoot";
89 private static final boolean DBG = false;
Mike Reedfd716532009-10-12 14:42:56 -040090 private static final boolean SHOW_FPS = false;
Romain Guy812ccbe2010-06-01 14:07:24 -070091 private static final boolean LOCAL_LOGV = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080092 /** @noinspection PointlessBooleanExpression*/
93 private static final boolean DEBUG_DRAW = false || LOCAL_LOGV;
94 private static final boolean DEBUG_LAYOUT = false || LOCAL_LOGV;
Dianne Hackborn711e62a2010-11-29 16:38:22 -080095 private static final boolean DEBUG_DIALOG = false || LOCAL_LOGV;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080096 private static final boolean DEBUG_INPUT_RESIZE = false || LOCAL_LOGV;
97 private static final boolean DEBUG_ORIENTATION = false || LOCAL_LOGV;
98 private static final boolean DEBUG_TRACKBALL = false || LOCAL_LOGV;
99 private static final boolean DEBUG_IMF = false || LOCAL_LOGV;
Dianne Hackborn694f79b2010-03-17 19:44:59 -0700100 private static final boolean DEBUG_CONFIGURATION = false || LOCAL_LOGV;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800101 private static final boolean WATCH_POINTER = false;
102
Michael Chan53071d62009-05-13 17:29:48 -0700103 private static final boolean MEASURE_LATENCY = false;
104 private static LatencyTimer lt;
105
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800106 /**
107 * Maximum time we allow the user to roll the trackball enough to generate
108 * a key event, before resetting the counters.
109 */
110 static final int MAX_TRACKBALL_DELAY = 250;
111
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800112 static IWindowSession sWindowSession;
113
114 static final Object mStaticInit = new Object();
115 static boolean mInitialized = false;
116
117 static final ThreadLocal<RunQueue> sRunQueues = new ThreadLocal<RunQueue>();
118
Dianne Hackborn2a9094d2010-02-03 19:20:09 -0800119 static final ArrayList<Runnable> sFirstDrawHandlers = new ArrayList<Runnable>();
120 static boolean sFirstDrawComplete = false;
121
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800122 static final ArrayList<ComponentCallbacks> sConfigCallbacks
123 = new ArrayList<ComponentCallbacks>();
124
Romain Guy8506ab42009-06-11 17:35:47 -0700125 private static int sDrawTime;
Romain Guy13922e02009-05-12 17:56:14 -0700126
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800127 long mLastTrackballTime = 0;
128 final TrackballAxis mTrackballAxisX = new TrackballAxis();
129 final TrackballAxis mTrackballAxisY = new TrackballAxis();
130
131 final int[] mTmpLocation = new int[2];
Romain Guy8506ab42009-06-11 17:35:47 -0700132
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800133 final TypedValue mTmpValue = new TypedValue();
134
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800135 final InputMethodCallback mInputMethodCallback;
136 final SparseArray<Object> mPendingEvents = new SparseArray<Object>();
137 int mPendingEventSeq = 0;
Romain Guy8506ab42009-06-11 17:35:47 -0700138
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800139 final Thread mThread;
140
141 final WindowLeaked mLocation;
142
143 final WindowManager.LayoutParams mWindowAttributes = new WindowManager.LayoutParams();
144
145 final W mWindow;
146
147 View mView;
148 View mFocusedView;
149 View mRealFocusedView; // this is not set to null in touch mode
150 int mViewVisibility;
151 boolean mAppVisible = true;
152
Dianne Hackbornd76b67c2010-07-13 17:48:30 -0700153 SurfaceHolder.Callback2 mSurfaceHolderCallback;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700154 BaseSurfaceHolder mSurfaceHolder;
155 boolean mIsCreating;
156 boolean mDrawingAllowed;
157
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800158 final Region mTransparentRegion;
159 final Region mPreviousTransparentRegion;
160
161 int mWidth;
162 int mHeight;
163 Rect mDirty; // will be a graphics.Region soon
Romain Guybb93d552009-03-24 21:04:15 -0700164 boolean mIsAnimating;
Romain Guy8506ab42009-06-11 17:35:47 -0700165
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700166 CompatibilityInfo.Translator mTranslator;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800167
168 final View.AttachInfo mAttachInfo;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700169 InputChannel mInputChannel;
Dianne Hackborn1e4b9f32010-06-23 14:10:57 -0700170 InputQueue.Callback mInputQueueCallback;
171 InputQueue mInputQueue;
Joe Onorato86f67862010-11-05 18:57:34 -0700172 FallbackEventHandler mFallbackEventHandler;
Dianne Hackborna95e4cb2010-06-18 18:09:33 -0700173
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800174 final Rect mTempRect; // used in the transaction to not thrash the heap.
175 final Rect mVisRect; // used to retrieve visible rect of focused view.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800176
177 boolean mTraversalScheduled;
178 boolean mWillDrawSoon;
179 boolean mLayoutRequested;
180 boolean mFirst;
181 boolean mReportNextDraw;
182 boolean mFullRedrawNeeded;
183 boolean mNewSurfaceNeeded;
184 boolean mHasHadWindowFocus;
185 boolean mLastWasImTarget;
186
187 boolean mWindowAttributesChanged = false;
188
189 // These can be accessed by any thread, must be protected with a lock.
Mathias Agopian5583dc62009-07-09 16:28:11 -0700190 // Surface can never be reassigned or cleared (use Surface.clear()).
191 private final Surface mSurface = new Surface();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800192
193 boolean mAdded;
194 boolean mAddedTouchMode;
195
196 /*package*/ int mAddNesting;
197
198 // These are accessed by multiple threads.
199 final Rect mWinFrame; // frame given by window manager.
200
201 final Rect mPendingVisibleInsets = new Rect();
202 final Rect mPendingContentInsets = new Rect();
203 final ViewTreeObserver.InternalInsetsInfo mLastGivenInsets
204 = new ViewTreeObserver.InternalInsetsInfo();
205
Dianne Hackborn694f79b2010-03-17 19:44:59 -0700206 final Configuration mLastConfiguration = new Configuration();
207 final Configuration mPendingConfiguration = new Configuration();
208
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800209 class ResizedInfo {
210 Rect coveredInsets;
211 Rect visibleInsets;
212 Configuration newConfig;
213 }
214
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800215 boolean mScrollMayChange;
216 int mSoftInputMode;
217 View mLastScrolledFocus;
218 int mScrollY;
219 int mCurScrollY;
220 Scroller mScroller;
Dianne Hackborn0f761d62010-11-30 22:06:10 -0800221 Bitmap mResizeBitmap;
222 long mResizeBitmapStartTime;
223 int mResizeBitmapDuration;
224 static final Interpolator mResizeInterpolator = new AccelerateDecelerateInterpolator();
Romain Guy8506ab42009-06-11 17:35:47 -0700225
Romain Guy8506ab42009-06-11 17:35:47 -0700226 final ViewConfiguration mViewConfiguration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800227
Christopher Tatea53146c2010-09-07 11:57:52 -0700228 /* Drag/drop */
229 ClipDescription mDragDescription;
230 View mCurrentDragView;
Christopher Tate7fb8b562011-01-20 13:46:41 -0800231 volatile Object mLocalDragState;
Christopher Tatea53146c2010-09-07 11:57:52 -0700232 final PointF mDragPoint = new PointF();
Christopher Tate2c095f32010-10-04 14:13:40 -0700233 final PointF mLastTouchPoint = new PointF();
Christopher Tatea53146c2010-09-07 11:57:52 -0700234
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800235 /**
236 * see {@link #playSoundEffect(int)}
237 */
238 AudioManager mAudioManager;
239
Dianne Hackborn11ea3342009-07-22 21:48:55 -0700240 private final int mDensity;
Adam Powellb08013c2010-09-16 16:28:11 -0700241
Dianne Hackborn4c62fc02009-08-08 20:40:27 -0700242 public static IWindowSession getWindowSession(Looper mainLooper) {
243 synchronized (mStaticInit) {
244 if (!mInitialized) {
245 try {
246 InputMethodManager imm = InputMethodManager.getInstance(mainLooper);
247 sWindowSession = IWindowManager.Stub.asInterface(
248 ServiceManager.getService("window"))
249 .openSession(imm.getClient(), imm.getInputContext());
250 mInitialized = true;
251 } catch (RemoteException e) {
252 }
253 }
254 return sWindowSession;
255 }
256 }
257
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800258 public ViewRoot(Context context) {
259 super();
260
Romain Guy812ccbe2010-06-01 14:07:24 -0700261 if (MEASURE_LATENCY) {
262 if (lt == null) {
263 lt = new LatencyTimer(100, 1000);
264 }
Michael Chan53071d62009-05-13 17:29:48 -0700265 }
266
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800267 // Initialize the statics when this class is first instantiated. This is
268 // done here instead of in the static block because Zygote does not
269 // allow the spawning of threads.
Dianne Hackborn4c62fc02009-08-08 20:40:27 -0700270 getWindowSession(context.getMainLooper());
271
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800272 mThread = Thread.currentThread();
273 mLocation = new WindowLeaked(null);
274 mLocation.fillInStackTrace();
275 mWidth = -1;
276 mHeight = -1;
277 mDirty = new Rect();
278 mTempRect = new Rect();
279 mVisRect = new Rect();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800280 mWinFrame = new Rect();
Romain Guyfb8b7632010-08-23 21:05:08 -0700281 mWindow = new W(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800282 mInputMethodCallback = new InputMethodCallback(this);
283 mViewVisibility = View.GONE;
284 mTransparentRegion = new Region();
285 mPreviousTransparentRegion = new Region();
286 mFirst = true; // true for the first time the view is added
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800287 mAdded = false;
288 mAttachInfo = new View.AttachInfo(sWindowSession, mWindow, this, this);
289 mViewConfiguration = ViewConfiguration.get(context);
Dianne Hackborn11ea3342009-07-22 21:48:55 -0700290 mDensity = context.getResources().getDisplayMetrics().densityDpi;
Joe Onorato86f67862010-11-05 18:57:34 -0700291 mFallbackEventHandler = PolicyManager.makeNewFallbackEventHandler(context);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800292 }
293
Dianne Hackborn2a9094d2010-02-03 19:20:09 -0800294 public static void addFirstDrawHandler(Runnable callback) {
295 synchronized (sFirstDrawHandlers) {
296 if (!sFirstDrawComplete) {
297 sFirstDrawHandlers.add(callback);
298 }
299 }
300 }
301
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800302 public static void addConfigCallback(ComponentCallbacks callback) {
303 synchronized (sConfigCallbacks) {
304 sConfigCallbacks.add(callback);
305 }
306 }
307
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800308 // FIXME for perf testing only
309 private boolean mProfile = false;
310
311 /**
312 * Call this to profile the next traversal call.
313 * FIXME for perf testing only. Remove eventually
314 */
315 public void profile() {
316 mProfile = true;
317 }
318
319 /**
320 * Indicates whether we are in touch mode. Calling this method triggers an IPC
321 * call and should be avoided whenever possible.
322 *
323 * @return True, if the device is in touch mode, false otherwise.
324 *
325 * @hide
326 */
327 static boolean isInTouchMode() {
328 if (mInitialized) {
329 try {
330 return sWindowSession.getInTouchMode();
331 } catch (RemoteException e) {
332 }
333 }
334 return false;
335 }
336
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800337 /**
338 * We have one child
339 */
Romain Guye4d01122010-06-16 18:44:05 -0700340 public void setView(View view, WindowManager.LayoutParams attrs, View panelParentView) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800341 synchronized (this) {
342 if (mView == null) {
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700343 mView = view;
Joe Onorato86f67862010-11-05 18:57:34 -0700344 mFallbackEventHandler.setView(view);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700345 mWindowAttributes.copyFrom(attrs);
Mitsuru Oshima1ecf5d22009-07-06 17:20:38 -0700346 attrs = mWindowAttributes;
Romain Guye4d01122010-06-16 18:44:05 -0700347
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700348 if (view instanceof RootViewSurfaceTaker) {
349 mSurfaceHolderCallback =
350 ((RootViewSurfaceTaker)view).willYouTakeTheSurface();
351 if (mSurfaceHolderCallback != null) {
352 mSurfaceHolder = new TakenSurfaceHolder();
Dianne Hackborn289b9b62010-07-09 11:44:11 -0700353 mSurfaceHolder.setFormat(PixelFormat.UNKNOWN);
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700354 }
355 }
Romain Guy1aec9a22011-01-05 09:37:12 -0800356
357 // If the application owns the surface, don't enable hardware acceleration
358 if (mSurfaceHolder == null) {
359 enableHardwareAcceleration(attrs);
360 }
361
Mitsuru Oshima38ed7d772009-07-21 14:39:34 -0700362 Resources resources = mView.getContext().getResources();
363 CompatibilityInfo compatibilityInfo = resources.getCompatibilityInfo();
Mitsuru Oshima589cebe2009-07-22 20:38:58 -0700364 mTranslator = compatibilityInfo.getTranslator();
Mitsuru Oshima38ed7d772009-07-21 14:39:34 -0700365
366 if (mTranslator != null || !compatibilityInfo.supportsScreen()) {
Mitsuru Oshima240f8a72009-07-22 20:39:14 -0700367 mSurface.setCompatibleDisplayMetrics(resources.getDisplayMetrics(),
368 mTranslator);
Mitsuru Oshima38ed7d772009-07-21 14:39:34 -0700369 }
370
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -0700371 boolean restore = false;
Romain Guy35b38ce2009-10-07 13:38:55 -0700372 if (mTranslator != null) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -0700373 restore = true;
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700374 attrs.backup();
375 mTranslator.translateWindowLayout(attrs);
Mitsuru Oshima3d914922009-05-13 22:29:15 -0700376 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700377 if (DEBUG_LAYOUT) Log.d(TAG, "WindowLayout in setView:" + attrs);
378
Mitsuru Oshima1ecf5d22009-07-06 17:20:38 -0700379 if (!compatibilityInfo.supportsScreen()) {
380 attrs.flags |= WindowManager.LayoutParams.FLAG_COMPATIBLE_WINDOW;
381 }
382
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800383 mSoftInputMode = attrs.softInputMode;
384 mWindowAttributesChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800385 mAttachInfo.mRootView = view;
Romain Guy35b38ce2009-10-07 13:38:55 -0700386 mAttachInfo.mScalingRequired = mTranslator != null;
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700387 mAttachInfo.mApplicationScale =
388 mTranslator == null ? 1.0f : mTranslator.applicationScale;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800389 if (panelParentView != null) {
390 mAttachInfo.mPanelParentWindowToken
391 = panelParentView.getApplicationWindowToken();
392 }
393 mAdded = true;
394 int res; /* = WindowManagerImpl.ADD_OKAY; */
Romain Guy8506ab42009-06-11 17:35:47 -0700395
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800396 // Schedule the first layout -before- adding to the window
397 // manager, to make sure we do the relayout before receiving
398 // any other events from the system.
399 requestLayout();
Jeff Brown46b9ac02010-04-22 18:58:52 -0700400 mInputChannel = new InputChannel();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800401 try {
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700402 res = sWindowSession.add(mWindow, mWindowAttributes,
Jeff Brown46b9ac02010-04-22 18:58:52 -0700403 getHostVisibility(), mAttachInfo.mContentInsets,
404 mInputChannel);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800405 } catch (RemoteException e) {
406 mAdded = false;
407 mView = null;
408 mAttachInfo.mRootView = null;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700409 mInputChannel = null;
Joe Onorato86f67862010-11-05 18:57:34 -0700410 mFallbackEventHandler.setView(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800411 unscheduleTraversals();
412 throw new RuntimeException("Adding window failed", e);
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700413 } finally {
414 if (restore) {
415 attrs.restore();
416 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800417 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700418
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700419 if (mTranslator != null) {
420 mTranslator.translateRectInScreenToAppWindow(mAttachInfo.mContentInsets);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700421 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800422 mPendingContentInsets.set(mAttachInfo.mContentInsets);
423 mPendingVisibleInsets.set(0, 0, 0, 0);
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800424 if (DEBUG_LAYOUT) Log.v(TAG, "Added window " + mWindow);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800425 if (res < WindowManagerImpl.ADD_OKAY) {
426 mView = null;
427 mAttachInfo.mRootView = null;
428 mAdded = false;
Joe Onorato86f67862010-11-05 18:57:34 -0700429 mFallbackEventHandler.setView(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800430 unscheduleTraversals();
431 switch (res) {
432 case WindowManagerImpl.ADD_BAD_APP_TOKEN:
433 case WindowManagerImpl.ADD_BAD_SUBWINDOW_TOKEN:
434 throw new WindowManagerImpl.BadTokenException(
435 "Unable to add window -- token " + attrs.token
436 + " is not valid; is your activity running?");
437 case WindowManagerImpl.ADD_NOT_APP_TOKEN:
438 throw new WindowManagerImpl.BadTokenException(
439 "Unable to add window -- token " + attrs.token
440 + " is not for an application");
441 case WindowManagerImpl.ADD_APP_EXITING:
442 throw new WindowManagerImpl.BadTokenException(
443 "Unable to add window -- app for token " + attrs.token
444 + " is exiting");
445 case WindowManagerImpl.ADD_DUPLICATE_ADD:
446 throw new WindowManagerImpl.BadTokenException(
447 "Unable to add window -- window " + mWindow
448 + " has already been added");
449 case WindowManagerImpl.ADD_STARTING_NOT_NEEDED:
450 // Silently ignore -- we would have just removed it
451 // right away, anyway.
452 return;
453 case WindowManagerImpl.ADD_MULTIPLE_SINGLETON:
454 throw new WindowManagerImpl.BadTokenException(
455 "Unable to add window " + mWindow +
456 " -- another window of this type already exists");
457 case WindowManagerImpl.ADD_PERMISSION_DENIED:
458 throw new WindowManagerImpl.BadTokenException(
459 "Unable to add window " + mWindow +
460 " -- permission denied for this window type");
461 }
462 throw new RuntimeException(
463 "Unable to add window -- unknown error code " + res);
464 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700465
Jeff Brown00fa7bd2010-07-02 15:37:36 -0700466 if (view instanceof RootViewSurfaceTaker) {
467 mInputQueueCallback =
468 ((RootViewSurfaceTaker)view).willYouTakeTheInputQueue();
469 }
470 if (mInputQueueCallback != null) {
471 mInputQueue = new InputQueue(mInputChannel);
472 mInputQueueCallback.onInputQueueCreated(mInputQueue);
473 } else {
474 InputQueue.registerInputChannel(mInputChannel, mInputHandler,
475 Looper.myQueue());
Jeff Brown46b9ac02010-04-22 18:58:52 -0700476 }
477
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800478 view.assignParent(this);
479 mAddedTouchMode = (res&WindowManagerImpl.ADD_FLAG_IN_TOUCH_MODE) != 0;
480 mAppVisible = (res&WindowManagerImpl.ADD_FLAG_APP_VISIBLE) != 0;
481 }
482 }
483 }
484
Romain Guy529b60a2010-08-03 18:05:47 -0700485 private void enableHardwareAcceleration(WindowManager.LayoutParams attrs) {
Dianne Hackborn7eec10e2010-11-12 18:03:47 -0800486 mAttachInfo.mHardwareAccelerated = false;
487 mAttachInfo.mHardwareAccelerationRequested = false;
Romain Guy4f6aff32011-01-12 16:21:41 -0800488
Dianne Hackborn7eec10e2010-11-12 18:03:47 -0800489 // Try to enable hardware acceleration if requested
490 if (attrs != null &&
491 (attrs.flags & WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED) != 0) {
492 // Only enable hardware acceleration if we are not in the system process
493 // The window manager creates ViewRoots to display animated preview windows
494 // of launching apps and we don't want those to be hardware accelerated
495 if (!HardwareRenderer.sRendererDisabled) {
Romain Guyff26a0c2011-01-20 11:35:46 -0800496 // Don't enable hardware acceleration when we're not on the main thread
497 if (Looper.getMainLooper() != Looper.myLooper()) {
498 Log.w(HardwareRenderer.LOG_TAG, "Attempting to initialize hardware "
499 + "acceleration outside of the main thread, aborting");
500 return;
501 }
502
Romain Guye4d01122010-06-16 18:44:05 -0700503 final boolean translucent = attrs.format != PixelFormat.OPAQUE;
Romain Guyb051e892010-09-28 19:09:36 -0700504 if (mAttachInfo.mHardwareRenderer != null) {
505 mAttachInfo.mHardwareRenderer.destroy(true);
Romain Guy4caa4ed2010-08-25 14:46:24 -0700506 }
Romain Guyb051e892010-09-28 19:09:36 -0700507 mAttachInfo.mHardwareRenderer = HardwareRenderer.createGlRenderer(2, translucent);
Dianne Hackborn7eec10e2010-11-12 18:03:47 -0800508 mAttachInfo.mHardwareAccelerated = mAttachInfo.mHardwareAccelerationRequested
509 = mAttachInfo.mHardwareRenderer != null;
510 } else if (HardwareRenderer.isAvailable()) {
511 mAttachInfo.mHardwareAccelerationRequested = true;
Romain Guye4d01122010-06-16 18:44:05 -0700512 }
513 }
514 }
515
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800516 public View getView() {
517 return mView;
518 }
519
520 final WindowLeaked getLocation() {
521 return mLocation;
522 }
523
524 void setLayoutParams(WindowManager.LayoutParams attrs, boolean newView) {
525 synchronized (this) {
The Android Open Source Project10592532009-03-18 17:39:46 -0700526 int oldSoftInputMode = mWindowAttributes.softInputMode;
Mitsuru Oshima5a2b91d2009-07-16 16:30:02 -0700527 // preserve compatible window flag if exists.
528 int compatibleWindowFlag =
529 mWindowAttributes.flags & WindowManager.LayoutParams.FLAG_COMPATIBLE_WINDOW;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800530 mWindowAttributes.copyFrom(attrs);
Mitsuru Oshima5a2b91d2009-07-16 16:30:02 -0700531 mWindowAttributes.flags |= compatibleWindowFlag;
532
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800533 if (newView) {
534 mSoftInputMode = attrs.softInputMode;
535 requestLayout();
536 }
The Android Open Source Project10592532009-03-18 17:39:46 -0700537 // Don't lose the mode we last auto-computed.
538 if ((attrs.softInputMode&WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST)
539 == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED) {
540 mWindowAttributes.softInputMode = (mWindowAttributes.softInputMode
541 & ~WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST)
542 | (oldSoftInputMode
543 & WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST);
544 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800545 mWindowAttributesChanged = true;
546 scheduleTraversals();
547 }
548 }
549
550 void handleAppVisibility(boolean visible) {
551 if (mAppVisible != visible) {
552 mAppVisible = visible;
553 scheduleTraversals();
554 }
555 }
556
557 void handleGetNewSurface() {
558 mNewSurfaceNeeded = true;
559 mFullRedrawNeeded = true;
560 scheduleTraversals();
561 }
562
563 /**
564 * {@inheritDoc}
565 */
566 public void requestLayout() {
567 checkThread();
568 mLayoutRequested = true;
569 scheduleTraversals();
570 }
571
572 /**
573 * {@inheritDoc}
574 */
575 public boolean isLayoutRequested() {
576 return mLayoutRequested;
577 }
578
579 public void invalidateChild(View child, Rect dirty) {
580 checkThread();
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700581 if (DEBUG_DRAW) Log.v(TAG, "Invalidate child: " + dirty);
Chet Haase70d4ba12010-10-06 09:46:45 -0700582 if (dirty == null) {
583 // Fast invalidation for GL-enabled applications; GL must redraw everything
584 invalidate();
585 return;
586 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700587 if (mCurScrollY != 0 || mTranslator != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800588 mTempRect.set(dirty);
Romain Guy1e095972009-07-07 11:22:45 -0700589 dirty = mTempRect;
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700590 if (mCurScrollY != 0) {
Romain Guy1e095972009-07-07 11:22:45 -0700591 dirty.offset(0, -mCurScrollY);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700592 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700593 if (mTranslator != null) {
Romain Guy1e095972009-07-07 11:22:45 -0700594 mTranslator.translateRectInAppWindowToScreen(dirty);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700595 }
Romain Guy1e095972009-07-07 11:22:45 -0700596 if (mAttachInfo.mScalingRequired) {
597 dirty.inset(-1, -1);
598 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800599 }
Romain Guy7d695942010-12-01 17:22:29 -0800600 if (!mDirty.isEmpty()) {
601 mAttachInfo.mIgnoreDirtyState = true;
602 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800603 mDirty.union(dirty);
604 if (!mWillDrawSoon) {
605 scheduleTraversals();
606 }
607 }
Romain Guy0d9275e2010-10-26 14:22:30 -0700608
609 void invalidate() {
610 mDirty.set(0, 0, mWidth, mHeight);
611 scheduleTraversals();
612 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800613
614 public ViewParent getParent() {
615 return null;
616 }
617
618 public ViewParent invalidateChildInParent(final int[] location, final Rect dirty) {
619 invalidateChild(null, dirty);
620 return null;
621 }
622
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700623 public boolean getChildVisibleRect(View child, Rect r, android.graphics.Point offset) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800624 if (child != mView) {
625 throw new RuntimeException("child is not mine, honest!");
626 }
627 // Note: don't apply scroll offset, because we want to know its
628 // visibility in the virtual canvas being given to the view hierarchy.
629 return r.intersect(0, 0, mWidth, mHeight);
630 }
631
632 public void bringChildToFront(View child) {
633 }
634
635 public void scheduleTraversals() {
636 if (!mTraversalScheduled) {
637 mTraversalScheduled = true;
638 sendEmptyMessage(DO_TRAVERSAL);
639 }
640 }
641
642 public void unscheduleTraversals() {
643 if (mTraversalScheduled) {
644 mTraversalScheduled = false;
645 removeMessages(DO_TRAVERSAL);
646 }
647 }
648
649 int getHostVisibility() {
650 return mAppVisible ? mView.getVisibility() : View.GONE;
651 }
Romain Guy8506ab42009-06-11 17:35:47 -0700652
Dianne Hackborn0f761d62010-11-30 22:06:10 -0800653 void disposeResizeBitmap() {
654 if (mResizeBitmap != null) {
655 mResizeBitmap.recycle();
656 mResizeBitmap = null;
657 }
658 }
659
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800660 private void performTraversals() {
661 // cache mView since it is used so much below...
662 final View host = mView;
663
664 if (DBG) {
665 System.out.println("======================================");
666 System.out.println("performTraversals");
667 host.debug();
668 }
669
670 if (host == null || !mAdded)
671 return;
672
673 mTraversalScheduled = false;
674 mWillDrawSoon = true;
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800675 boolean windowSizeMayChange = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800676 boolean fullRedrawNeeded = mFullRedrawNeeded;
677 boolean newSurface = false;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700678 boolean surfaceChanged = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800679 WindowManager.LayoutParams lp = mWindowAttributes;
680
681 int desiredWindowWidth;
682 int desiredWindowHeight;
683 int childWidthMeasureSpec;
684 int childHeightMeasureSpec;
685
686 final View.AttachInfo attachInfo = mAttachInfo;
687
688 final int viewVisibility = getHostVisibility();
689 boolean viewVisibilityChanged = mViewVisibility != viewVisibility
690 || mNewSurfaceNeeded;
691
692 WindowManager.LayoutParams params = null;
693 if (mWindowAttributesChanged) {
694 mWindowAttributesChanged = false;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700695 surfaceChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800696 params = lp;
697 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700698 Rect frame = mWinFrame;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800699 if (mFirst) {
700 fullRedrawNeeded = true;
701 mLayoutRequested = true;
702
Romain Guy8506ab42009-06-11 17:35:47 -0700703 DisplayMetrics packageMetrics =
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700704 mView.getContext().getResources().getDisplayMetrics();
705 desiredWindowWidth = packageMetrics.widthPixels;
706 desiredWindowHeight = packageMetrics.heightPixels;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800707
708 // For the very first time, tell the view hierarchy that it
709 // is attached to the window. Note that at this point the surface
710 // object is not initialized to its backing store, but soon it
711 // will be (assuming the window is visible).
712 attachInfo.mSurface = mSurface;
Romain Guyc5d55862011-01-21 19:01:46 -0800713 // We used to use the following condition to choose 32 bits drawing caches:
714 // PixelFormat.hasAlpha(lp.format) || lp.format == PixelFormat.RGBX_8888
715 // However, windows are now always 32 bits by default, so choose 32 bits
716 attachInfo.mUse32BitDrawingCache = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800717 attachInfo.mHasWindowFocus = false;
718 attachInfo.mWindowVisibility = viewVisibility;
719 attachInfo.mRecomputeGlobalAttributes = false;
720 attachInfo.mKeepScreenOn = false;
Joe Onorato664644d2011-01-23 17:53:23 -0800721 attachInfo.mSystemUiVisibility = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800722 viewVisibilityChanged = false;
Dianne Hackborn694f79b2010-03-17 19:44:59 -0700723 mLastConfiguration.setTo(host.getResources().getConfiguration());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800724 host.dispatchAttachedToWindow(attachInfo, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800725 //Log.i(TAG, "Screen on initialized: " + attachInfo.mKeepScreenOn);
svetoslavganov75986cf2009-05-14 22:28:01 -0700726
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800727 } else {
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700728 desiredWindowWidth = frame.width();
729 desiredWindowHeight = frame.height();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800730 if (desiredWindowWidth != mWidth || desiredWindowHeight != mHeight) {
Jeff Brownc5ed5912010-07-14 18:48:53 -0700731 if (DEBUG_ORIENTATION) Log.v(TAG,
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700732 "View " + host + " resized to: " + frame);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800733 fullRedrawNeeded = true;
734 mLayoutRequested = true;
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800735 windowSizeMayChange = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800736 }
737 }
738
739 if (viewVisibilityChanged) {
740 attachInfo.mWindowVisibility = viewVisibility;
741 host.dispatchWindowVisibilityChanged(viewVisibility);
742 if (viewVisibility != View.VISIBLE || mNewSurfaceNeeded) {
Romain Guyb051e892010-09-28 19:09:36 -0700743 if (mAttachInfo.mHardwareRenderer != null) {
744 mAttachInfo.mHardwareRenderer.destroy(false);
Romain Guy4caa4ed2010-08-25 14:46:24 -0700745 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800746 }
747 if (viewVisibility == View.GONE) {
748 // After making a window gone, we will count it as being
749 // shown for the first time the next time it gets focus.
750 mHasHadWindowFocus = false;
751 }
752 }
753
754 boolean insetsChanged = false;
Romain Guy8506ab42009-06-11 17:35:47 -0700755
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800756 if (mLayoutRequested) {
Romain Guy15df6702009-08-17 20:17:30 -0700757 // Execute enqueued actions on every layout in case a view that was detached
758 // enqueued an action after being detached
759 getRunQueue().executeActions(attachInfo.mHandler);
760
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800761 final Resources res = mView.getContext().getResources();
762
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800763 if (mFirst) {
764 host.fitSystemWindows(mAttachInfo.mContentInsets);
765 // make sure touch mode code executes by setting cached value
766 // to opposite of the added touch mode.
767 mAttachInfo.mInTouchMode = !mAddedTouchMode;
Romain Guy2d4cff62010-04-09 15:39:00 -0700768 ensureTouchModeLocally(mAddedTouchMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800769 } else {
770 if (!mAttachInfo.mContentInsets.equals(mPendingContentInsets)) {
Dianne Hackborn0f761d62010-11-30 22:06:10 -0800771 if (mWidth > 0 && mHeight > 0 &&
772 mSurface != null && mSurface.isValid() &&
773 mAttachInfo.mHardwareRenderer != null &&
774 mAttachInfo.mHardwareRenderer.isEnabled() &&
775 lp != null && !PixelFormat.formatHasAlpha(lp.format)) {
776
777 disposeResizeBitmap();
778
779 boolean completed = false;
780 try {
781 mResizeBitmap = Bitmap.createBitmap(mWidth, mHeight,
782 Bitmap.Config.ARGB_8888);
783 mResizeBitmap.setHasAlpha(false);
784 Canvas canvas = new Canvas(mResizeBitmap);
785 int yoff;
786 final boolean scrolling = mScroller != null
787 && mScroller.computeScrollOffset();
788 if (scrolling) {
789 yoff = mScroller.getCurrY();
790 mScroller.abortAnimation();
791 } else {
792 yoff = mScrollY;
793 }
794 canvas.translate(0, -yoff);
795 if (mTranslator != null) {
796 mTranslator.translateCanvas(canvas);
797 }
798 canvas.setScreenDensity(mAttachInfo.mScalingRequired
799 ? DisplayMetrics.DENSITY_DEVICE : 0);
800 mView.draw(canvas);
801 mResizeBitmapStartTime = SystemClock.uptimeMillis();
802 mResizeBitmapDuration = mView.getResources().getInteger(
803 com.android.internal.R.integer.config_mediumAnimTime);
804 completed = true;
805 } catch (OutOfMemoryError e) {
806 Log.w(TAG, "Not enough memory for content change anim buffer", e);
807 } finally {
808 if (!completed) {
809 mResizeBitmap = null;
810 }
811 }
812 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800813 mAttachInfo.mContentInsets.set(mPendingContentInsets);
814 host.fitSystemWindows(mAttachInfo.mContentInsets);
815 insetsChanged = true;
816 if (DEBUG_LAYOUT) Log.v(TAG, "Content insets changing to: "
817 + mAttachInfo.mContentInsets);
818 }
819 if (!mAttachInfo.mVisibleInsets.equals(mPendingVisibleInsets)) {
820 mAttachInfo.mVisibleInsets.set(mPendingVisibleInsets);
821 if (DEBUG_LAYOUT) Log.v(TAG, "Visible insets changing to: "
822 + mAttachInfo.mVisibleInsets);
823 }
824 if (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT
825 || lp.height == ViewGroup.LayoutParams.WRAP_CONTENT) {
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800826 windowSizeMayChange = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800827
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800828 DisplayMetrics packageMetrics = res.getDisplayMetrics();
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700829 desiredWindowWidth = packageMetrics.widthPixels;
830 desiredWindowHeight = packageMetrics.heightPixels;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800831 }
832 }
833
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800834 // Ask host how big it wants to be
Jeff Brownc5ed5912010-07-14 18:48:53 -0700835 if (DEBUG_ORIENTATION || DEBUG_LAYOUT) Log.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800836 "Measuring " + host + " in display " + desiredWindowWidth
837 + "x" + desiredWindowHeight + "...");
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800838
839 boolean goodMeasure = false;
840 if (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT
841 || lp.height == ViewGroup.LayoutParams.WRAP_CONTENT) {
842 // On large screens, we don't want to allow dialogs to just
843 // stretch to fill the entire width of the screen to display
844 // one line of text. First try doing the layout at a smaller
845 // size to see if it will fit.
846 final DisplayMetrics packageMetrics = res.getDisplayMetrics();
847 res.getValue(com.android.internal.R.dimen.config_prefDialogWidth, mTmpValue, true);
848 int baseSize = 0;
849 if (mTmpValue.type == TypedValue.TYPE_DIMENSION) {
850 baseSize = (int)mTmpValue.getDimension(packageMetrics);
851 }
852 if (DEBUG_DIALOG) Log.v(TAG, "Window " + mView + ": baseSize=" + baseSize);
Dianne Hackborn7d3a5bc2010-11-29 22:52:12 -0800853 if (baseSize != 0 && desiredWindowWidth > baseSize) {
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800854 childWidthMeasureSpec = getRootMeasureSpec(baseSize, lp.width);
855 childHeightMeasureSpec = getRootMeasureSpec(desiredWindowHeight, lp.height);
856 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
857 if (DEBUG_DIALOG) Log.v(TAG, "Window " + mView + ": measured ("
Dianne Hackborn189ee182010-12-02 21:48:53 -0800858 + host.getMeasuredWidth() + "," + host.getMeasuredHeight() + ")");
859 if ((host.getMeasuredWidthAndState()&View.MEASURED_STATE_TOO_SMALL) == 0) {
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800860 goodMeasure = true;
861 } else {
862 // Didn't fit in that size... try expanding a bit.
863 baseSize = (baseSize+desiredWindowWidth)/2;
864 if (DEBUG_DIALOG) Log.v(TAG, "Window " + mView + ": next baseSize="
865 + baseSize);
Dianne Hackborn189ee182010-12-02 21:48:53 -0800866 childWidthMeasureSpec = getRootMeasureSpec(baseSize, lp.width);
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800867 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
868 if (DEBUG_DIALOG) Log.v(TAG, "Window " + mView + ": measured ("
Dianne Hackborn189ee182010-12-02 21:48:53 -0800869 + host.getMeasuredWidth() + "," + host.getMeasuredHeight() + ")");
870 if ((host.getMeasuredWidthAndState()&View.MEASURED_STATE_TOO_SMALL) == 0) {
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800871 if (DEBUG_DIALOG) Log.v(TAG, "Good!");
872 goodMeasure = true;
873 }
874 }
875 }
876 }
877
878 if (!goodMeasure) {
879 childWidthMeasureSpec = getRootMeasureSpec(desiredWindowWidth, lp.width);
880 childHeightMeasureSpec = getRootMeasureSpec(desiredWindowHeight, lp.height);
881 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
Adam Powellaa0b92c2010-12-13 22:38:53 -0800882 if (mWidth != host.getMeasuredWidth() || mHeight != host.getMeasuredHeight()) {
883 windowSizeMayChange = true;
884 }
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800885 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800886
887 if (DBG) {
888 System.out.println("======================================");
889 System.out.println("performTraversals -- after measure");
890 host.debug();
891 }
892 }
893
894 if (attachInfo.mRecomputeGlobalAttributes) {
Joe Onorato664644d2011-01-23 17:53:23 -0800895 //Log.i(TAG, "Computing view hierarchy attributes!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800896 attachInfo.mRecomputeGlobalAttributes = false;
Joe Onorato664644d2011-01-23 17:53:23 -0800897 boolean oldScreenOn = attachInfo.mKeepScreenOn;
898 int oldVis = attachInfo.mSystemUiVisibility;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800899 attachInfo.mKeepScreenOn = false;
Joe Onorato664644d2011-01-23 17:53:23 -0800900 attachInfo.mSystemUiVisibility = 0;
901 attachInfo.mHasSystemUiListeners = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800902 host.dispatchCollectViewAttributes(0);
Joe Onorato664644d2011-01-23 17:53:23 -0800903 if (attachInfo.mKeepScreenOn != oldScreenOn ||
904 attachInfo.mSystemUiVisibility != oldVis) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800905 params = lp;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800906 }
907 }
908
909 if (mFirst || attachInfo.mViewVisibilityChanged) {
910 attachInfo.mViewVisibilityChanged = false;
911 int resizeMode = mSoftInputMode &
912 WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST;
913 // If we are in auto resize mode, then we need to determine
914 // what mode to use now.
915 if (resizeMode == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED) {
916 final int N = attachInfo.mScrollContainers.size();
917 for (int i=0; i<N; i++) {
918 if (attachInfo.mScrollContainers.get(i).isShown()) {
919 resizeMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE;
920 }
921 }
922 if (resizeMode == 0) {
923 resizeMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN;
924 }
925 if ((lp.softInputMode &
926 WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) != resizeMode) {
927 lp.softInputMode = (lp.softInputMode &
928 ~WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) |
929 resizeMode;
930 params = lp;
931 }
932 }
933 }
Romain Guy8506ab42009-06-11 17:35:47 -0700934
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800935 if (params != null && (host.mPrivateFlags & View.REQUEST_TRANSPARENT_REGIONS) != 0) {
936 if (!PixelFormat.formatHasAlpha(params.format)) {
937 params.format = PixelFormat.TRANSLUCENT;
938 }
939 }
940
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800941 boolean windowShouldResize = mLayoutRequested && windowSizeMayChange
Dianne Hackborn189ee182010-12-02 21:48:53 -0800942 && ((mWidth != host.getMeasuredWidth() || mHeight != host.getMeasuredHeight())
Romain Guy2e4f4262010-04-06 11:07:52 -0700943 || (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT &&
944 frame.width() < desiredWindowWidth && frame.width() != mWidth)
945 || (lp.height == ViewGroup.LayoutParams.WRAP_CONTENT &&
946 frame.height() < desiredWindowHeight && frame.height() != mHeight));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800947
948 final boolean computesInternalInsets =
949 attachInfo.mTreeObserver.hasComputeInternalInsetsListeners();
Romain Guy812ccbe2010-06-01 14:07:24 -0700950
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800951 boolean insetsPending = false;
952 int relayoutResult = 0;
Romain Guy812ccbe2010-06-01 14:07:24 -0700953
954 if (mFirst || windowShouldResize || insetsChanged ||
955 viewVisibilityChanged || params != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800956
957 if (viewVisibility == View.VISIBLE) {
958 // If this window is giving internal insets to the window
959 // manager, and it is being added or changing its visibility,
960 // then we want to first give the window manager "fake"
961 // insets to cause it to effectively ignore the content of
962 // the window during layout. This avoids it briefly causing
963 // other windows to resize/move based on the raw frame of the
964 // window, waiting until we can finish laying out this window
965 // and get back to the window manager with the ultimately
966 // computed insets.
Romain Guy812ccbe2010-06-01 14:07:24 -0700967 insetsPending = computesInternalInsets && (mFirst || viewVisibilityChanged);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800968 }
969
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700970 if (mSurfaceHolder != null) {
971 mSurfaceHolder.mSurfaceLock.lock();
972 mDrawingAllowed = true;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700973 }
Romain Guy812ccbe2010-06-01 14:07:24 -0700974
Romain Guyc361da82010-10-25 15:29:10 -0700975 boolean hwInitialized = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800976 boolean contentInsetsChanged = false;
Romain Guy13922e02009-05-12 17:56:14 -0700977 boolean visibleInsetsChanged;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700978 boolean hadSurface = mSurface.isValid();
Romain Guy812ccbe2010-06-01 14:07:24 -0700979
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800980 try {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800981 int fl = 0;
982 if (params != null) {
983 fl = params.flags;
984 if (attachInfo.mKeepScreenOn) {
985 params.flags |= WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
986 }
Joe Onorato664644d2011-01-23 17:53:23 -0800987 params.systemUiVisibility = attachInfo.mSystemUiVisibility;
988 params.hasSystemUiListeners = attachInfo.mHasSystemUiListeners;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800989 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700990 if (DEBUG_LAYOUT) {
Dianne Hackborn189ee182010-12-02 21:48:53 -0800991 Log.i(TAG, "host=w:" + host.getMeasuredWidth() + ", h:" +
992 host.getMeasuredHeight() + ", params=" + params);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700993 }
Romain Guy2a83f002011-01-18 18:28:21 -0800994
995 final int surfaceGenerationId = mSurface.getGenerationId();
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700996 relayoutResult = relayoutWindow(params, viewVisibility, insetsPending);
997
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800998 if (params != null) {
999 params.flags = fl;
1000 }
1001
1002 if (DEBUG_LAYOUT) Log.v(TAG, "relayout: frame=" + frame.toShortString()
1003 + " content=" + mPendingContentInsets.toShortString()
1004 + " visible=" + mPendingVisibleInsets.toShortString()
1005 + " surface=" + mSurface);
Romain Guy8506ab42009-06-11 17:35:47 -07001006
Dianne Hackborn694f79b2010-03-17 19:44:59 -07001007 if (mPendingConfiguration.seq != 0) {
1008 if (DEBUG_CONFIGURATION) Log.v(TAG, "Visible with new config: "
1009 + mPendingConfiguration);
1010 updateConfiguration(mPendingConfiguration, !mFirst);
1011 mPendingConfiguration.seq = 0;
1012 }
1013
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001014 contentInsetsChanged = !mPendingContentInsets.equals(
1015 mAttachInfo.mContentInsets);
1016 visibleInsetsChanged = !mPendingVisibleInsets.equals(
1017 mAttachInfo.mVisibleInsets);
1018 if (contentInsetsChanged) {
1019 mAttachInfo.mContentInsets.set(mPendingContentInsets);
1020 host.fitSystemWindows(mAttachInfo.mContentInsets);
1021 if (DEBUG_LAYOUT) Log.v(TAG, "Content insets changing to: "
1022 + mAttachInfo.mContentInsets);
1023 }
1024 if (visibleInsetsChanged) {
1025 mAttachInfo.mVisibleInsets.set(mPendingVisibleInsets);
1026 if (DEBUG_LAYOUT) Log.v(TAG, "Visible insets changing to: "
1027 + mAttachInfo.mVisibleInsets);
1028 }
1029
1030 if (!hadSurface) {
1031 if (mSurface.isValid()) {
1032 // If we are creating a new surface, then we need to
1033 // completely redraw it. Also, when we get to the
1034 // point of drawing it we will hold off and schedule
1035 // a new traversal instead. This is so we can tell the
1036 // window manager about all of the windows being displayed
1037 // before actually drawing them, so it can display then
1038 // all at once.
1039 newSurface = true;
1040 fullRedrawNeeded = true;
Jack Palevich61a6e682009-10-09 17:37:50 -07001041 mPreviousTransparentRegion.setEmpty();
Romain Guy8506ab42009-06-11 17:35:47 -07001042
Romain Guyb051e892010-09-28 19:09:36 -07001043 if (mAttachInfo.mHardwareRenderer != null) {
Romain Guyc361da82010-10-25 15:29:10 -07001044 hwInitialized = mAttachInfo.mHardwareRenderer.initialize(mHolder);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001045 }
1046 }
1047 } else if (!mSurface.isValid()) {
1048 // If the surface has been removed, then reset the scroll
1049 // positions.
1050 mLastScrolledFocus = null;
1051 mScrollY = mCurScrollY = 0;
1052 if (mScroller != null) {
1053 mScroller.abortAnimation();
1054 }
Dianne Hackborn0f761d62010-11-30 22:06:10 -08001055 disposeResizeBitmap();
Romain Guy2a83f002011-01-18 18:28:21 -08001056 } else if (surfaceGenerationId != mSurface.getGenerationId() &&
1057 mSurfaceHolder == null && mAttachInfo.mHardwareRenderer != null) {
1058 mAttachInfo.mHardwareRenderer.updateSurface(mHolder);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001059 }
1060 } catch (RemoteException e) {
1061 }
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001062
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001063 if (DEBUG_ORIENTATION) Log.v(
Jeff Brownc5ed5912010-07-14 18:48:53 -07001064 TAG, "Relayout returned: frame=" + frame + ", surface=" + mSurface);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001065
1066 attachInfo.mWindowLeft = frame.left;
1067 attachInfo.mWindowTop = frame.top;
1068
1069 // !!FIXME!! This next section handles the case where we did not get the
1070 // window size we asked for. We should avoid this by getting a maximum size from
1071 // the window session beforehand.
1072 mWidth = frame.width();
1073 mHeight = frame.height();
1074
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001075 if (mSurfaceHolder != null) {
1076 // The app owns the surface; tell it about what is going on.
1077 if (mSurface.isValid()) {
1078 // XXX .copyFrom() doesn't work!
1079 //mSurfaceHolder.mSurface.copyFrom(mSurface);
1080 mSurfaceHolder.mSurface = mSurface;
1081 }
1082 mSurfaceHolder.mSurfaceLock.unlock();
1083 if (mSurface.isValid()) {
1084 if (!hadSurface) {
1085 mSurfaceHolder.ungetCallbacks();
1086
1087 mIsCreating = true;
1088 mSurfaceHolderCallback.surfaceCreated(mSurfaceHolder);
1089 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
1090 if (callbacks != null) {
1091 for (SurfaceHolder.Callback c : callbacks) {
1092 c.surfaceCreated(mSurfaceHolder);
1093 }
1094 }
1095 surfaceChanged = true;
1096 }
1097 if (surfaceChanged) {
1098 mSurfaceHolderCallback.surfaceChanged(mSurfaceHolder,
1099 lp.format, mWidth, mHeight);
1100 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
1101 if (callbacks != null) {
1102 for (SurfaceHolder.Callback c : callbacks) {
1103 c.surfaceChanged(mSurfaceHolder, lp.format,
1104 mWidth, mHeight);
1105 }
1106 }
1107 }
1108 mIsCreating = false;
1109 } else if (hadSurface) {
1110 mSurfaceHolder.ungetCallbacks();
1111 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
1112 mSurfaceHolderCallback.surfaceDestroyed(mSurfaceHolder);
1113 if (callbacks != null) {
1114 for (SurfaceHolder.Callback c : callbacks) {
1115 c.surfaceDestroyed(mSurfaceHolder);
1116 }
1117 }
1118 mSurfaceHolder.mSurfaceLock.lock();
1119 // Make surface invalid.
1120 //mSurfaceHolder.mSurface.copyFrom(mSurface);
1121 mSurfaceHolder.mSurface = new Surface();
1122 mSurfaceHolder.mSurfaceLock.unlock();
1123 }
1124 }
Romain Guy53389bd2010-09-07 17:16:32 -07001125
Romain Guy6b5108b2011-01-04 16:11:10 -08001126 if (hwInitialized || ((windowShouldResize || params != null) &&
Romain Guydbf78bd2010-12-07 17:04:03 -08001127 mAttachInfo.mHardwareRenderer != null &&
1128 mAttachInfo.mHardwareRenderer.isEnabled())) {
Romain Guyb051e892010-09-28 19:09:36 -07001129 mAttachInfo.mHardwareRenderer.setup(mWidth, mHeight);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001130 }
1131
1132 boolean focusChangedDueToTouchMode = ensureTouchModeLocally(
Romain Guy2d4cff62010-04-09 15:39:00 -07001133 (relayoutResult&WindowManagerImpl.RELAYOUT_IN_TOUCH_MODE) != 0);
Dianne Hackborn189ee182010-12-02 21:48:53 -08001134 if (focusChangedDueToTouchMode || mWidth != host.getMeasuredWidth()
1135 || mHeight != host.getMeasuredHeight() || contentInsetsChanged) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001136 childWidthMeasureSpec = getRootMeasureSpec(mWidth, lp.width);
1137 childHeightMeasureSpec = getRootMeasureSpec(mHeight, lp.height);
1138
1139 if (DEBUG_LAYOUT) Log.v(TAG, "Ooops, something changed! mWidth="
Dianne Hackborn189ee182010-12-02 21:48:53 -08001140 + mWidth + " measuredWidth=" + host.getMeasuredWidth()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001141 + " mHeight=" + mHeight
Dianne Hackbornff801ec2011-01-22 18:05:38 -08001142 + " measuredHeight=" + host.getMeasuredHeight()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001143 + " coveredInsetsChanged=" + contentInsetsChanged);
Romain Guy8506ab42009-06-11 17:35:47 -07001144
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001145 // Ask host how big it wants to be
1146 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
1147
1148 // Implementation of weights from WindowManager.LayoutParams
1149 // We just grow the dimensions as needed and re-measure if
1150 // needs be
Dianne Hackborn189ee182010-12-02 21:48:53 -08001151 int width = host.getMeasuredWidth();
1152 int height = host.getMeasuredHeight();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001153 boolean measureAgain = false;
1154
1155 if (lp.horizontalWeight > 0.0f) {
1156 width += (int) ((mWidth - width) * lp.horizontalWeight);
1157 childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(width,
1158 MeasureSpec.EXACTLY);
1159 measureAgain = true;
1160 }
1161 if (lp.verticalWeight > 0.0f) {
1162 height += (int) ((mHeight - height) * lp.verticalWeight);
1163 childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(height,
1164 MeasureSpec.EXACTLY);
1165 measureAgain = true;
1166 }
1167
1168 if (measureAgain) {
1169 if (DEBUG_LAYOUT) Log.v(TAG,
1170 "And hey let's measure once more: width=" + width
1171 + " height=" + height);
1172 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
1173 }
1174
1175 mLayoutRequested = true;
1176 }
1177 }
1178
1179 final boolean didLayout = mLayoutRequested;
1180 boolean triggerGlobalLayoutListener = didLayout
1181 || attachInfo.mRecomputeGlobalAttributes;
1182 if (didLayout) {
1183 mLayoutRequested = false;
1184 mScrollMayChange = true;
1185 if (DEBUG_ORIENTATION || DEBUG_LAYOUT) Log.v(
Jeff Brownc5ed5912010-07-14 18:48:53 -07001186 TAG, "Laying out " + host + " to (" +
Dianne Hackborn189ee182010-12-02 21:48:53 -08001187 host.getMeasuredWidth() + ", " + host.getMeasuredHeight() + ")");
Romain Guy13922e02009-05-12 17:56:14 -07001188 long startTime = 0L;
Romain Guy5429e1d2010-09-07 12:38:00 -07001189 if (ViewDebug.DEBUG_PROFILE_LAYOUT) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001190 startTime = SystemClock.elapsedRealtime();
1191 }
Dianne Hackborn189ee182010-12-02 21:48:53 -08001192 host.layout(0, 0, host.getMeasuredWidth(), host.getMeasuredHeight());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001193
Romain Guy13922e02009-05-12 17:56:14 -07001194 if (Config.DEBUG && ViewDebug.consistencyCheckEnabled) {
1195 if (!host.dispatchConsistencyCheck(ViewDebug.CONSISTENCY_LAYOUT)) {
1196 throw new IllegalStateException("The view hierarchy is an inconsistent state,"
1197 + "please refer to the logs with the tag "
1198 + ViewDebug.CONSISTENCY_LOG_TAG + " for more infomation.");
1199 }
1200 }
1201
Romain Guy5429e1d2010-09-07 12:38:00 -07001202 if (ViewDebug.DEBUG_PROFILE_LAYOUT) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001203 EventLog.writeEvent(60001, SystemClock.elapsedRealtime() - startTime);
1204 }
1205
1206 // By this point all views have been sized and positionned
1207 // We can compute the transparent area
1208
1209 if ((host.mPrivateFlags & View.REQUEST_TRANSPARENT_REGIONS) != 0) {
1210 // start out transparent
1211 // TODO: AVOID THAT CALL BY CACHING THE RESULT?
1212 host.getLocationInWindow(mTmpLocation);
1213 mTransparentRegion.set(mTmpLocation[0], mTmpLocation[1],
1214 mTmpLocation[0] + host.mRight - host.mLeft,
1215 mTmpLocation[1] + host.mBottom - host.mTop);
1216
1217 host.gatherTransparentRegion(mTransparentRegion);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001218 if (mTranslator != null) {
1219 mTranslator.translateRegionInWindowToScreen(mTransparentRegion);
1220 }
1221
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001222 if (!mTransparentRegion.equals(mPreviousTransparentRegion)) {
1223 mPreviousTransparentRegion.set(mTransparentRegion);
1224 // reconfigure window manager
1225 try {
1226 sWindowSession.setTransparentRegion(mWindow, mTransparentRegion);
1227 } catch (RemoteException e) {
1228 }
1229 }
1230 }
1231
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001232 if (DBG) {
1233 System.out.println("======================================");
1234 System.out.println("performTraversals -- after setFrame");
1235 host.debug();
1236 }
1237 }
1238
1239 if (triggerGlobalLayoutListener) {
1240 attachInfo.mRecomputeGlobalAttributes = false;
1241 attachInfo.mTreeObserver.dispatchOnGlobalLayout();
1242 }
1243
1244 if (computesInternalInsets) {
Jeff Brownfbf09772011-01-16 14:06:57 -08001245 // Clear the original insets.
1246 final ViewTreeObserver.InternalInsetsInfo insets = attachInfo.mGivenInternalInsets;
1247 insets.reset();
1248
1249 // Compute new insets in place.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001250 attachInfo.mTreeObserver.dispatchOnComputeInternalInsets(insets);
Jeff Brownfbf09772011-01-16 14:06:57 -08001251
1252 // Tell the window manager.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001253 if (insetsPending || !mLastGivenInsets.equals(insets)) {
1254 mLastGivenInsets.set(insets);
Jeff Brownfbf09772011-01-16 14:06:57 -08001255
1256 // Translate insets to screen coordinates if needed.
1257 final Rect contentInsets;
1258 final Rect visibleInsets;
1259 final Region touchableRegion;
1260 if (mTranslator != null) {
1261 contentInsets = mTranslator.getTranslatedContentInsets(insets.contentInsets);
1262 visibleInsets = mTranslator.getTranslatedVisibleInsets(insets.visibleInsets);
1263 touchableRegion = mTranslator.getTranslatedTouchableArea(insets.touchableRegion);
1264 } else {
1265 contentInsets = insets.contentInsets;
1266 visibleInsets = insets.visibleInsets;
1267 touchableRegion = insets.touchableRegion;
1268 }
1269
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001270 try {
1271 sWindowSession.setInsets(mWindow, insets.mTouchableInsets,
Jeff Brownfbf09772011-01-16 14:06:57 -08001272 contentInsets, visibleInsets, touchableRegion);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001273 } catch (RemoteException e) {
1274 }
1275 }
1276 }
Romain Guy8506ab42009-06-11 17:35:47 -07001277
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001278 if (mFirst) {
1279 // handle first focus request
1280 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: mView.hasFocus()="
1281 + mView.hasFocus());
1282 if (mView != null) {
1283 if (!mView.hasFocus()) {
1284 mView.requestFocus(View.FOCUS_FORWARD);
1285 mFocusedView = mRealFocusedView = mView.findFocus();
1286 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: requested focused view="
1287 + mFocusedView);
1288 } else {
1289 mRealFocusedView = mView.findFocus();
1290 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: existing focused view="
1291 + mRealFocusedView);
1292 }
1293 }
1294 }
1295
1296 mFirst = false;
1297 mWillDrawSoon = false;
1298 mNewSurfaceNeeded = false;
1299 mViewVisibility = viewVisibility;
1300
1301 if (mAttachInfo.mHasWindowFocus) {
1302 final boolean imTarget = WindowManager.LayoutParams
1303 .mayUseInputMethod(mWindowAttributes.flags);
1304 if (imTarget != mLastWasImTarget) {
1305 mLastWasImTarget = imTarget;
1306 InputMethodManager imm = InputMethodManager.peekInstance();
1307 if (imm != null && imTarget) {
1308 imm.startGettingWindowFocus(mView);
1309 imm.onWindowFocus(mView, mView.findFocus(),
1310 mWindowAttributes.softInputMode,
1311 !mHasHadWindowFocus, mWindowAttributes.flags);
1312 }
1313 }
1314 }
Romain Guy8506ab42009-06-11 17:35:47 -07001315
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001316 boolean cancelDraw = attachInfo.mTreeObserver.dispatchOnPreDraw();
1317
1318 if (!cancelDraw && !newSurface) {
1319 mFullRedrawNeeded = false;
1320 draw(fullRedrawNeeded);
1321
1322 if ((relayoutResult&WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0
1323 || mReportNextDraw) {
1324 if (LOCAL_LOGV) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001325 Log.v(TAG, "FINISHED DRAWING: " + mWindowAttributes.getTitle());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001326 }
1327 mReportNextDraw = false;
Dianne Hackbornd76b67c2010-07-13 17:48:30 -07001328 if (mSurfaceHolder != null && mSurface.isValid()) {
1329 mSurfaceHolderCallback.surfaceRedrawNeeded(mSurfaceHolder);
1330 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
1331 if (callbacks != null) {
1332 for (SurfaceHolder.Callback c : callbacks) {
1333 if (c instanceof SurfaceHolder.Callback2) {
1334 ((SurfaceHolder.Callback2)c).surfaceRedrawNeeded(
1335 mSurfaceHolder);
1336 }
1337 }
1338 }
1339 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001340 try {
1341 sWindowSession.finishDrawing(mWindow);
1342 } catch (RemoteException e) {
1343 }
1344 }
1345 } else {
1346 // We were supposed to report when we are done drawing. Since we canceled the
1347 // draw, remember it here.
1348 if ((relayoutResult&WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0) {
1349 mReportNextDraw = true;
1350 }
1351 if (fullRedrawNeeded) {
1352 mFullRedrawNeeded = true;
1353 }
1354 // Try again
1355 scheduleTraversals();
1356 }
1357 }
1358
1359 public void requestTransparentRegion(View child) {
1360 // the test below should not fail unless someone is messing with us
1361 checkThread();
1362 if (mView == child) {
1363 mView.mPrivateFlags |= View.REQUEST_TRANSPARENT_REGIONS;
1364 // Need to make sure we re-evaluate the window attributes next
1365 // time around, to ensure the window has the correct format.
1366 mWindowAttributesChanged = true;
Mathias Agopian1bd80ad2010-11-04 17:13:39 -07001367 requestLayout();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001368 }
1369 }
1370
1371 /**
1372 * Figures out the measure spec for the root view in a window based on it's
1373 * layout params.
1374 *
1375 * @param windowSize
1376 * The available width or height of the window
1377 *
1378 * @param rootDimension
1379 * The layout params for one dimension (width or height) of the
1380 * window.
1381 *
1382 * @return The measure spec to use to measure the root view.
1383 */
1384 private int getRootMeasureSpec(int windowSize, int rootDimension) {
1385 int measureSpec;
1386 switch (rootDimension) {
1387
Romain Guy980a9382010-01-08 15:06:28 -08001388 case ViewGroup.LayoutParams.MATCH_PARENT:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001389 // Window can't resize. Force root view to be windowSize.
1390 measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.EXACTLY);
1391 break;
1392 case ViewGroup.LayoutParams.WRAP_CONTENT:
1393 // Window can resize. Set max size for root view.
1394 measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.AT_MOST);
1395 break;
1396 default:
1397 // Window wants to be an exact size. Force root view to be that size.
1398 measureSpec = MeasureSpec.makeMeasureSpec(rootDimension, MeasureSpec.EXACTLY);
1399 break;
1400 }
1401 return measureSpec;
1402 }
1403
Dianne Hackborn0f761d62010-11-30 22:06:10 -08001404 int mHardwareYOffset;
1405 int mResizeAlpha;
1406 final Paint mResizePaint = new Paint();
1407
1408 public void onHardwarePreDraw(Canvas canvas) {
1409 canvas.translate(0, -mHardwareYOffset);
1410 }
1411
1412 public void onHardwarePostDraw(Canvas canvas) {
1413 if (mResizeBitmap != null) {
1414 canvas.translate(0, mHardwareYOffset);
1415 mResizePaint.setAlpha(mResizeAlpha);
1416 canvas.drawBitmap(mResizeBitmap, 0, 0, mResizePaint);
1417 }
1418 }
1419
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001420 private void draw(boolean fullRedrawNeeded) {
1421 Surface surface = mSurface;
1422 if (surface == null || !surface.isValid()) {
1423 return;
1424 }
1425
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001426 if (!sFirstDrawComplete) {
1427 synchronized (sFirstDrawHandlers) {
1428 sFirstDrawComplete = true;
Romain Guy812ccbe2010-06-01 14:07:24 -07001429 final int count = sFirstDrawHandlers.size();
1430 for (int i = 0; i< count; i++) {
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001431 post(sFirstDrawHandlers.get(i));
1432 }
1433 }
1434 }
1435
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001436 scrollToRectOrFocus(null, false);
1437
1438 if (mAttachInfo.mViewScrollChanged) {
1439 mAttachInfo.mViewScrollChanged = false;
1440 mAttachInfo.mTreeObserver.dispatchOnScrollChanged();
1441 }
Romain Guy8506ab42009-06-11 17:35:47 -07001442
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001443 int yoff;
Dianne Hackborn0f761d62010-11-30 22:06:10 -08001444 boolean animating = mScroller != null && mScroller.computeScrollOffset();
1445 if (animating) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001446 yoff = mScroller.getCurrY();
1447 } else {
1448 yoff = mScrollY;
1449 }
1450 if (mCurScrollY != yoff) {
1451 mCurScrollY = yoff;
1452 fullRedrawNeeded = true;
1453 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001454 float appScale = mAttachInfo.mApplicationScale;
1455 boolean scalingRequired = mAttachInfo.mScalingRequired;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001456
Dianne Hackborn0f761d62010-11-30 22:06:10 -08001457 int resizeAlpha = 0;
1458 if (mResizeBitmap != null) {
1459 long deltaTime = SystemClock.uptimeMillis() - mResizeBitmapStartTime;
1460 if (deltaTime < mResizeBitmapDuration) {
1461 float amt = deltaTime/(float)mResizeBitmapDuration;
1462 amt = mResizeInterpolator.getInterpolation(amt);
1463 animating = true;
1464 resizeAlpha = 255 - (int)(amt*255);
1465 } else {
1466 disposeResizeBitmap();
1467 }
1468 }
1469
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001470 Rect dirty = mDirty;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001471 if (mSurfaceHolder != null) {
1472 // The app owns the surface, we won't draw.
1473 dirty.setEmpty();
Dianne Hackborn0f761d62010-11-30 22:06:10 -08001474 if (animating) {
1475 if (mScroller != null) {
1476 mScroller.abortAnimation();
1477 }
1478 disposeResizeBitmap();
1479 }
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001480 return;
1481 }
Romain Guy58ef7fb2010-09-13 12:52:37 -07001482
1483 if (fullRedrawNeeded) {
1484 mAttachInfo.mIgnoreDirtyState = true;
1485 dirty.union(0, 0, (int) (mWidth * appScale + 0.5f), (int) (mHeight * appScale + 0.5f));
1486 }
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001487
Romain Guyb051e892010-09-28 19:09:36 -07001488 if (mAttachInfo.mHardwareRenderer != null && mAttachInfo.mHardwareRenderer.isEnabled()) {
Romain Guyfd507262010-10-10 15:42:49 -07001489 if (!dirty.isEmpty() || mIsAnimating) {
Romain Guy101e2ae2010-10-11 12:41:21 -07001490 mIsAnimating = false;
Romain Guyfd507262010-10-10 15:42:49 -07001491 dirty.setEmpty();
Dianne Hackborn0f761d62010-11-30 22:06:10 -08001492 mHardwareYOffset = yoff;
1493 mResizeAlpha = resizeAlpha;
1494 mAttachInfo.mHardwareRenderer.draw(mView, mAttachInfo, this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001495 }
Romain Guy812ccbe2010-06-01 14:07:24 -07001496
Dianne Hackborn0f761d62010-11-30 22:06:10 -08001497 if (animating) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001498 mFullRedrawNeeded = true;
1499 scheduleTraversals();
1500 }
Romain Guy812ccbe2010-06-01 14:07:24 -07001501
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001502 return;
1503 }
1504
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001505 if (DEBUG_ORIENTATION || DEBUG_DRAW) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001506 Log.v(TAG, "Draw " + mView + "/"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001507 + mWindowAttributes.getTitle()
1508 + ": dirty={" + dirty.left + "," + dirty.top
1509 + "," + dirty.right + "," + dirty.bottom + "} surface="
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001510 + surface + " surface.isValid()=" + surface.isValid() + ", appScale:" +
1511 appScale + ", width=" + mWidth + ", height=" + mHeight);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001512 }
1513
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001514 if (!dirty.isEmpty() || mIsAnimating) {
1515 Canvas canvas;
1516 try {
1517 int left = dirty.left;
1518 int top = dirty.top;
1519 int right = dirty.right;
1520 int bottom = dirty.bottom;
1521 canvas = surface.lockCanvas(dirty);
Romain Guy5bcdff42009-05-14 21:27:18 -07001522
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001523 if (left != dirty.left || top != dirty.top || right != dirty.right ||
1524 bottom != dirty.bottom) {
1525 mAttachInfo.mIgnoreDirtyState = true;
1526 }
1527
1528 // TODO: Do this in native
1529 canvas.setDensity(mDensity);
1530 } catch (Surface.OutOfResourcesException e) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001531 Log.e(TAG, "OutOfResourcesException locking surface", e);
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001532 // TODO: we should ask the window manager to do something!
1533 // for now we just do nothing
1534 return;
1535 } catch (IllegalArgumentException e) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001536 Log.e(TAG, "IllegalArgumentException locking surface", e);
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001537 // TODO: we should ask the window manager to do something!
1538 // for now we just do nothing
1539 return;
Romain Guy5bcdff42009-05-14 21:27:18 -07001540 }
1541
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001542 try {
1543 if (!dirty.isEmpty() || mIsAnimating) {
1544 long startTime = 0L;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001545
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001546 if (DEBUG_ORIENTATION || DEBUG_DRAW) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001547 Log.v(TAG, "Surface " + surface + " drawing to bitmap w="
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001548 + canvas.getWidth() + ", h=" + canvas.getHeight());
1549 //canvas.drawARGB(255, 255, 0, 0);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001550 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001551
Romain Guy5429e1d2010-09-07 12:38:00 -07001552 if (ViewDebug.DEBUG_PROFILE_DRAWING) {
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001553 startTime = SystemClock.elapsedRealtime();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001554 }
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001555
1556 // If this bitmap's format includes an alpha channel, we
1557 // need to clear it before drawing so that the child will
1558 // properly re-composite its drawing on a transparent
1559 // background. This automatically respects the clip/dirty region
1560 // or
1561 // If we are applying an offset, we need to clear the area
1562 // where the offset doesn't appear to avoid having garbage
1563 // left in the blank areas.
1564 if (!canvas.isOpaque() || yoff != 0) {
1565 canvas.drawColor(0, PorterDuff.Mode.CLEAR);
1566 }
1567
1568 dirty.setEmpty();
1569 mIsAnimating = false;
1570 mAttachInfo.mDrawingTime = SystemClock.uptimeMillis();
1571 mView.mPrivateFlags |= View.DRAWN;
1572
1573 if (DEBUG_DRAW) {
1574 Context cxt = mView.getContext();
1575 Log.i(TAG, "Drawing: package:" + cxt.getPackageName() +
1576 ", metrics=" + cxt.getResources().getDisplayMetrics() +
1577 ", compatibilityInfo=" + cxt.getResources().getCompatibilityInfo());
1578 }
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001579 try {
1580 canvas.translate(0, -yoff);
1581 if (mTranslator != null) {
1582 mTranslator.translateCanvas(canvas);
1583 }
1584 canvas.setScreenDensity(scalingRequired
1585 ? DisplayMetrics.DENSITY_DEVICE : 0);
1586 mView.draw(canvas);
1587 } finally {
1588 mAttachInfo.mIgnoreDirtyState = false;
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001589 }
1590
1591 if (Config.DEBUG && ViewDebug.consistencyCheckEnabled) {
1592 mView.dispatchConsistencyCheck(ViewDebug.CONSISTENCY_DRAWING);
1593 }
1594
Romain Guy5429e1d2010-09-07 12:38:00 -07001595 if (SHOW_FPS || ViewDebug.DEBUG_SHOW_FPS) {
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001596 int now = (int)SystemClock.elapsedRealtime();
1597 if (sDrawTime != 0) {
1598 nativeShowFPS(canvas, now - sDrawTime);
1599 }
1600 sDrawTime = now;
1601 }
1602
Romain Guy5429e1d2010-09-07 12:38:00 -07001603 if (ViewDebug.DEBUG_PROFILE_DRAWING) {
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001604 EventLog.writeEvent(60000, SystemClock.elapsedRealtime() - startTime);
1605 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001606 }
1607
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001608 } finally {
1609 surface.unlockCanvasAndPost(canvas);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001610 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001611 }
1612
1613 if (LOCAL_LOGV) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001614 Log.v(TAG, "Surface " + surface + " unlockCanvasAndPost");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001615 }
Romain Guy8506ab42009-06-11 17:35:47 -07001616
Dianne Hackborn0f761d62010-11-30 22:06:10 -08001617 if (animating) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001618 mFullRedrawNeeded = true;
1619 scheduleTraversals();
1620 }
1621 }
1622
1623 boolean scrollToRectOrFocus(Rect rectangle, boolean immediate) {
1624 final View.AttachInfo attachInfo = mAttachInfo;
1625 final Rect ci = attachInfo.mContentInsets;
1626 final Rect vi = attachInfo.mVisibleInsets;
1627 int scrollY = 0;
1628 boolean handled = false;
Romain Guy8506ab42009-06-11 17:35:47 -07001629
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001630 if (vi.left > ci.left || vi.top > ci.top
1631 || vi.right > ci.right || vi.bottom > ci.bottom) {
1632 // We'll assume that we aren't going to change the scroll
1633 // offset, since we want to avoid that unless it is actually
1634 // going to make the focus visible... otherwise we scroll
1635 // all over the place.
1636 scrollY = mScrollY;
1637 // We can be called for two different situations: during a draw,
1638 // to update the scroll position if the focus has changed (in which
1639 // case 'rectangle' is null), or in response to a
1640 // requestChildRectangleOnScreen() call (in which case 'rectangle'
1641 // is non-null and we just want to scroll to whatever that
1642 // rectangle is).
1643 View focus = mRealFocusedView;
Romain Guye8b16522009-07-14 13:06:42 -07001644
1645 // When in touch mode, focus points to the previously focused view,
1646 // which may have been removed from the view hierarchy. The following
Joe Onoratob71193b2009-11-24 18:34:42 -05001647 // line checks whether the view is still in our hierarchy.
1648 if (focus == null || focus.mAttachInfo != mAttachInfo) {
Romain Guye8b16522009-07-14 13:06:42 -07001649 mRealFocusedView = null;
1650 return false;
1651 }
1652
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001653 if (focus != mLastScrolledFocus) {
1654 // If the focus has changed, then ignore any requests to scroll
1655 // to a rectangle; first we want to make sure the entire focus
1656 // view is visible.
1657 rectangle = null;
1658 }
1659 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Eval scroll: focus=" + focus
1660 + " rectangle=" + rectangle + " ci=" + ci
1661 + " vi=" + vi);
1662 if (focus == mLastScrolledFocus && !mScrollMayChange
1663 && rectangle == null) {
1664 // Optimization: if the focus hasn't changed since last
1665 // time, and no layout has happened, then just leave things
1666 // as they are.
1667 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Keeping scroll y="
1668 + mScrollY + " vi=" + vi.toShortString());
1669 } else if (focus != null) {
1670 // We need to determine if the currently focused view is
1671 // within the visible part of the window and, if not, apply
1672 // a pan so it can be seen.
1673 mLastScrolledFocus = focus;
1674 mScrollMayChange = false;
1675 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Need to scroll?");
1676 // Try to find the rectangle from the focus view.
1677 if (focus.getGlobalVisibleRect(mVisRect, null)) {
1678 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Root w="
1679 + mView.getWidth() + " h=" + mView.getHeight()
1680 + " ci=" + ci.toShortString()
1681 + " vi=" + vi.toShortString());
1682 if (rectangle == null) {
1683 focus.getFocusedRect(mTempRect);
1684 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Focus " + focus
1685 + ": focusRect=" + mTempRect.toShortString());
Dianne Hackborn1c6a8942010-03-23 16:34:20 -07001686 if (mView instanceof ViewGroup) {
1687 ((ViewGroup) mView).offsetDescendantRectToMyCoords(
1688 focus, mTempRect);
1689 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001690 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1691 "Focus in window: focusRect="
1692 + mTempRect.toShortString()
1693 + " visRect=" + mVisRect.toShortString());
1694 } else {
1695 mTempRect.set(rectangle);
1696 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1697 "Request scroll to rect: "
1698 + mTempRect.toShortString()
1699 + " visRect=" + mVisRect.toShortString());
1700 }
1701 if (mTempRect.intersect(mVisRect)) {
1702 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1703 "Focus window visible rect: "
1704 + mTempRect.toShortString());
1705 if (mTempRect.height() >
1706 (mView.getHeight()-vi.top-vi.bottom)) {
1707 // If the focus simply is not going to fit, then
1708 // best is probably just to leave things as-is.
1709 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1710 "Too tall; leaving scrollY=" + scrollY);
1711 } else if ((mTempRect.top-scrollY) < vi.top) {
1712 scrollY -= vi.top - (mTempRect.top-scrollY);
1713 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1714 "Top covered; scrollY=" + scrollY);
1715 } else if ((mTempRect.bottom-scrollY)
1716 > (mView.getHeight()-vi.bottom)) {
1717 scrollY += (mTempRect.bottom-scrollY)
1718 - (mView.getHeight()-vi.bottom);
1719 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1720 "Bottom covered; scrollY=" + scrollY);
1721 }
1722 handled = true;
1723 }
1724 }
1725 }
1726 }
Romain Guy8506ab42009-06-11 17:35:47 -07001727
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001728 if (scrollY != mScrollY) {
1729 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Pan scroll changed: old="
1730 + mScrollY + " , new=" + scrollY);
Dianne Hackborn0f761d62010-11-30 22:06:10 -08001731 if (!immediate && mResizeBitmap == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001732 if (mScroller == null) {
1733 mScroller = new Scroller(mView.getContext());
1734 }
1735 mScroller.startScroll(0, mScrollY, 0, scrollY-mScrollY);
1736 } else if (mScroller != null) {
1737 mScroller.abortAnimation();
1738 }
1739 mScrollY = scrollY;
1740 }
Romain Guy8506ab42009-06-11 17:35:47 -07001741
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001742 return handled;
1743 }
Romain Guy8506ab42009-06-11 17:35:47 -07001744
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001745 public void requestChildFocus(View child, View focused) {
1746 checkThread();
1747 if (mFocusedView != focused) {
1748 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(mFocusedView, focused);
1749 scheduleTraversals();
1750 }
1751 mFocusedView = mRealFocusedView = focused;
1752 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Request child focus: focus now "
1753 + mFocusedView);
1754 }
1755
1756 public void clearChildFocus(View child) {
1757 checkThread();
1758
1759 View oldFocus = mFocusedView;
1760
1761 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Clearing child focus");
1762 mFocusedView = mRealFocusedView = null;
1763 if (mView != null && !mView.hasFocus()) {
1764 // If a view gets the focus, the listener will be invoked from requestChildFocus()
1765 if (!mView.requestFocus(View.FOCUS_FORWARD)) {
1766 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
1767 }
1768 } else if (oldFocus != null) {
1769 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
1770 }
1771 }
1772
1773
1774 public void focusableViewAvailable(View v) {
1775 checkThread();
1776
1777 if (mView != null && !mView.hasFocus()) {
1778 v.requestFocus();
1779 } else {
1780 // the one case where will transfer focus away from the current one
1781 // is if the current view is a view group that prefers to give focus
1782 // to its children first AND the view is a descendant of it.
1783 mFocusedView = mView.findFocus();
1784 boolean descendantsHaveDibsOnFocus =
1785 (mFocusedView instanceof ViewGroup) &&
1786 (((ViewGroup) mFocusedView).getDescendantFocusability() ==
1787 ViewGroup.FOCUS_AFTER_DESCENDANTS);
1788 if (descendantsHaveDibsOnFocus && isViewDescendantOf(v, mFocusedView)) {
1789 // If a view gets the focus, the listener will be invoked from requestChildFocus()
1790 v.requestFocus();
1791 }
1792 }
1793 }
1794
1795 public void recomputeViewAttributes(View child) {
1796 checkThread();
1797 if (mView == child) {
1798 mAttachInfo.mRecomputeGlobalAttributes = true;
1799 if (!mWillDrawSoon) {
1800 scheduleTraversals();
1801 }
1802 }
1803 }
1804
1805 void dispatchDetachedFromWindow() {
Romain Guy90fc03b2011-01-16 13:07:15 -08001806 if (mView != null && mView.mAttachInfo != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001807 mView.dispatchDetachedFromWindow();
1808 }
1809
1810 mView = null;
1811 mAttachInfo.mRootView = null;
Mathias Agopian5583dc62009-07-09 16:28:11 -07001812 mAttachInfo.mSurface = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001813
Romain Guy29d89972010-09-22 16:10:57 -07001814 destroyHardwareRenderer();
Romain Guy4caa4ed2010-08-25 14:46:24 -07001815
Dianne Hackborn0586a1b2009-09-06 21:08:27 -07001816 mSurface.release();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001817
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001818 if (mInputChannel != null) {
1819 if (mInputQueueCallback != null) {
1820 mInputQueueCallback.onInputQueueDestroyed(mInputQueue);
1821 mInputQueueCallback = null;
1822 } else {
1823 InputQueue.unregisterInputChannel(mInputChannel);
Jeff Brown46b9ac02010-04-22 18:58:52 -07001824 }
1825 }
1826
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001827 try {
1828 sWindowSession.remove(mWindow);
1829 } catch (RemoteException e) {
1830 }
Jeff Brown349703e2010-06-22 01:27:15 -07001831
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001832 // Dispose the input channel after removing the window so the Window Manager
1833 // doesn't interpret the input channel being closed as an abnormal termination.
1834 if (mInputChannel != null) {
1835 mInputChannel.dispose();
1836 mInputChannel = null;
Jeff Brown349703e2010-06-22 01:27:15 -07001837 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001838 }
Romain Guy8506ab42009-06-11 17:35:47 -07001839
Dianne Hackborn694f79b2010-03-17 19:44:59 -07001840 void updateConfiguration(Configuration config, boolean force) {
1841 if (DEBUG_CONFIGURATION) Log.v(TAG,
1842 "Applying new config to window "
1843 + mWindowAttributes.getTitle()
1844 + ": " + config);
1845 synchronized (sConfigCallbacks) {
1846 for (int i=sConfigCallbacks.size()-1; i>=0; i--) {
1847 sConfigCallbacks.get(i).onConfigurationChanged(config);
1848 }
1849 }
1850 if (mView != null) {
1851 // At this point the resources have been updated to
1852 // have the most recent config, whatever that is. Use
1853 // the on in them which may be newer.
1854 if (mView != null) {
1855 config = mView.getResources().getConfiguration();
1856 }
1857 if (force || mLastConfiguration.diff(config) != 0) {
1858 mLastConfiguration.setTo(config);
1859 mView.dispatchConfigurationChanged(config);
1860 }
1861 }
1862 }
1863
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001864 /**
1865 * Return true if child is an ancestor of parent, (or equal to the parent).
1866 */
1867 private static boolean isViewDescendantOf(View child, View parent) {
1868 if (child == parent) {
1869 return true;
1870 }
1871
1872 final ViewParent theParent = child.getParent();
1873 return (theParent instanceof ViewGroup) && isViewDescendantOf((View) theParent, parent);
1874 }
1875
Romain Guycdb86672010-03-18 18:54:50 -07001876 private static void forceLayout(View view) {
1877 view.forceLayout();
1878 if (view instanceof ViewGroup) {
1879 ViewGroup group = (ViewGroup) view;
1880 final int count = group.getChildCount();
1881 for (int i = 0; i < count; i++) {
1882 forceLayout(group.getChildAt(i));
1883 }
1884 }
1885 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001886
1887 public final static int DO_TRAVERSAL = 1000;
1888 public final static int DIE = 1001;
1889 public final static int RESIZED = 1002;
1890 public final static int RESIZED_REPORT = 1003;
1891 public final static int WINDOW_FOCUS_CHANGED = 1004;
1892 public final static int DISPATCH_KEY = 1005;
1893 public final static int DISPATCH_POINTER = 1006;
1894 public final static int DISPATCH_TRACKBALL = 1007;
1895 public final static int DISPATCH_APP_VISIBILITY = 1008;
1896 public final static int DISPATCH_GET_NEW_SURFACE = 1009;
1897 public final static int FINISHED_EVENT = 1010;
1898 public final static int DISPATCH_KEY_FROM_IME = 1011;
1899 public final static int FINISH_INPUT_CONNECTION = 1012;
1900 public final static int CHECK_FOCUS = 1013;
Dianne Hackbornffa42482009-09-23 22:20:11 -07001901 public final static int CLOSE_SYSTEM_DIALOGS = 1014;
Christopher Tatea53146c2010-09-07 11:57:52 -07001902 public final static int DISPATCH_DRAG_EVENT = 1015;
Chris Tate91e9bb32010-10-12 12:58:43 -07001903 public final static int DISPATCH_DRAG_LOCATION_EVENT = 1016;
Joe Onorato664644d2011-01-23 17:53:23 -08001904 public final static int DISPATCH_SYSTEM_UI_VISIBILITY = 1017;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001905
1906 @Override
1907 public void handleMessage(Message msg) {
1908 switch (msg.what) {
1909 case View.AttachInfo.INVALIDATE_MSG:
1910 ((View) msg.obj).invalidate();
1911 break;
1912 case View.AttachInfo.INVALIDATE_RECT_MSG:
1913 final View.AttachInfo.InvalidateInfo info = (View.AttachInfo.InvalidateInfo) msg.obj;
1914 info.target.invalidate(info.left, info.top, info.right, info.bottom);
1915 info.release();
1916 break;
1917 case DO_TRAVERSAL:
1918 if (mProfile) {
1919 Debug.startMethodTracing("ViewRoot");
1920 }
1921
1922 performTraversals();
1923
1924 if (mProfile) {
1925 Debug.stopMethodTracing();
1926 mProfile = false;
1927 }
1928 break;
1929 case FINISHED_EVENT:
1930 handleFinishedEvent(msg.arg1, msg.arg2 != 0);
1931 break;
1932 case DISPATCH_KEY:
Jeff Brown92ff1dd2010-08-11 16:16:06 -07001933 deliverKeyEvent((KeyEvent)msg.obj, msg.arg1 != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001934 break;
Jeff Brown3915bb82010-11-05 15:02:16 -07001935 case DISPATCH_POINTER:
1936 deliverPointerEvent((MotionEvent) msg.obj, msg.arg1 != 0);
1937 break;
1938 case DISPATCH_TRACKBALL:
1939 deliverTrackballEvent((MotionEvent) msg.obj, msg.arg1 != 0);
1940 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001941 case DISPATCH_APP_VISIBILITY:
1942 handleAppVisibility(msg.arg1 != 0);
1943 break;
1944 case DISPATCH_GET_NEW_SURFACE:
1945 handleGetNewSurface();
1946 break;
1947 case RESIZED:
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001948 ResizedInfo ri = (ResizedInfo)msg.obj;
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001949
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001950 if (mWinFrame.width() == msg.arg1 && mWinFrame.height() == msg.arg2
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001951 && mPendingContentInsets.equals(ri.coveredInsets)
Dianne Hackbornd49258f2010-03-26 00:44:29 -07001952 && mPendingVisibleInsets.equals(ri.visibleInsets)
1953 && ((ResizedInfo)msg.obj).newConfig == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001954 break;
1955 }
1956 // fall through...
1957 case RESIZED_REPORT:
1958 if (mAdded) {
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001959 Configuration config = ((ResizedInfo)msg.obj).newConfig;
1960 if (config != null) {
Dianne Hackborn694f79b2010-03-17 19:44:59 -07001961 updateConfiguration(config, false);
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001962 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001963 mWinFrame.left = 0;
1964 mWinFrame.right = msg.arg1;
1965 mWinFrame.top = 0;
1966 mWinFrame.bottom = msg.arg2;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001967 mPendingContentInsets.set(((ResizedInfo)msg.obj).coveredInsets);
1968 mPendingVisibleInsets.set(((ResizedInfo)msg.obj).visibleInsets);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001969 if (msg.what == RESIZED_REPORT) {
1970 mReportNextDraw = true;
1971 }
Romain Guycdb86672010-03-18 18:54:50 -07001972
1973 if (mView != null) {
1974 forceLayout(mView);
1975 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001976 requestLayout();
1977 }
1978 break;
1979 case WINDOW_FOCUS_CHANGED: {
1980 if (mAdded) {
1981 boolean hasWindowFocus = msg.arg1 != 0;
1982 mAttachInfo.mHasWindowFocus = hasWindowFocus;
1983 if (hasWindowFocus) {
1984 boolean inTouchMode = msg.arg2 != 0;
Romain Guy2d4cff62010-04-09 15:39:00 -07001985 ensureTouchModeLocally(inTouchMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001986
Romain Guyc361da82010-10-25 15:29:10 -07001987 if (mAttachInfo.mHardwareRenderer != null &&
1988 mSurface != null && mSurface.isValid()) {
Romain Guyb051e892010-09-28 19:09:36 -07001989 mAttachInfo.mHardwareRenderer.initializeIfNeeded(mWidth, mHeight,
1990 mAttachInfo, mHolder);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001991 }
1992 }
Romain Guy8506ab42009-06-11 17:35:47 -07001993
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001994 mLastWasImTarget = WindowManager.LayoutParams
1995 .mayUseInputMethod(mWindowAttributes.flags);
Romain Guy8506ab42009-06-11 17:35:47 -07001996
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001997 InputMethodManager imm = InputMethodManager.peekInstance();
1998 if (mView != null) {
1999 if (hasWindowFocus && imm != null && mLastWasImTarget) {
2000 imm.startGettingWindowFocus(mView);
2001 }
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07002002 mAttachInfo.mKeyDispatchState.reset();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002003 mView.dispatchWindowFocusChanged(hasWindowFocus);
2004 }
svetoslavganov75986cf2009-05-14 22:28:01 -07002005
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002006 // Note: must be done after the focus change callbacks,
2007 // so all of the view state is set up correctly.
2008 if (hasWindowFocus) {
2009 if (imm != null && mLastWasImTarget) {
2010 imm.onWindowFocus(mView, mView.findFocus(),
2011 mWindowAttributes.softInputMode,
2012 !mHasHadWindowFocus, mWindowAttributes.flags);
2013 }
2014 // Clear the forward bit. We can just do this directly, since
2015 // the window manager doesn't care about it.
2016 mWindowAttributes.softInputMode &=
2017 ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
2018 ((WindowManager.LayoutParams)mView.getLayoutParams())
2019 .softInputMode &=
2020 ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
2021 mHasHadWindowFocus = true;
2022 }
svetoslavganov75986cf2009-05-14 22:28:01 -07002023
2024 if (hasWindowFocus && mView != null) {
2025 sendAccessibilityEvents();
2026 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002027 }
2028 } break;
2029 case DIE:
Dianne Hackborn94d69142009-09-28 22:14:42 -07002030 doDie();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002031 break;
The Android Open Source Project10592532009-03-18 17:39:46 -07002032 case DISPATCH_KEY_FROM_IME: {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002033 if (LOCAL_LOGV) Log.v(
Jeff Brownc5ed5912010-07-14 18:48:53 -07002034 TAG, "Dispatching key "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002035 + msg.obj + " from IME to " + mView);
The Android Open Source Project10592532009-03-18 17:39:46 -07002036 KeyEvent event = (KeyEvent)msg.obj;
2037 if ((event.getFlags()&KeyEvent.FLAG_FROM_SYSTEM) != 0) {
2038 // The IME is trying to say this event is from the
2039 // system! Bad bad bad!
Romain Guy812ccbe2010-06-01 14:07:24 -07002040 event = KeyEvent.changeFlags(event, event.getFlags() & ~KeyEvent.FLAG_FROM_SYSTEM);
The Android Open Source Project10592532009-03-18 17:39:46 -07002041 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002042 deliverKeyEventPostIme((KeyEvent)msg.obj, false);
The Android Open Source Project10592532009-03-18 17:39:46 -07002043 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002044 case FINISH_INPUT_CONNECTION: {
2045 InputMethodManager imm = InputMethodManager.peekInstance();
2046 if (imm != null) {
2047 imm.reportFinishInputConnection((InputConnection)msg.obj);
2048 }
2049 } break;
2050 case CHECK_FOCUS: {
2051 InputMethodManager imm = InputMethodManager.peekInstance();
2052 if (imm != null) {
2053 imm.checkFocus();
2054 }
2055 } break;
Dianne Hackbornffa42482009-09-23 22:20:11 -07002056 case CLOSE_SYSTEM_DIALOGS: {
2057 if (mView != null) {
2058 mView.onCloseSystemDialogs((String)msg.obj);
2059 }
2060 } break;
Chris Tate91e9bb32010-10-12 12:58:43 -07002061 case DISPATCH_DRAG_EVENT:
2062 case DISPATCH_DRAG_LOCATION_EVENT: {
Christopher Tate7fb8b562011-01-20 13:46:41 -08002063 DragEvent event = (DragEvent)msg.obj;
2064 event.mLocalState = mLocalDragState; // only present when this app called startDrag()
2065 handleDragEvent(event);
Christopher Tatea53146c2010-09-07 11:57:52 -07002066 } break;
Joe Onorato664644d2011-01-23 17:53:23 -08002067 case DISPATCH_SYSTEM_UI_VISIBILITY: {
2068 handleDispatchSystemUiVisibilityChanged(msg.arg1);
2069 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002070 }
2071 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002072
Jeff Brown3915bb82010-11-05 15:02:16 -07002073 private void startInputEvent(InputQueue.FinishedCallback finishedCallback) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07002074 if (mFinishedCallback != null) {
2075 Slog.w(TAG, "Received a new input event from the input queue but there is "
2076 + "already an unfinished input event in progress.");
2077 }
2078
2079 mFinishedCallback = finishedCallback;
2080 }
2081
Jeff Brown3915bb82010-11-05 15:02:16 -07002082 private void finishInputEvent(boolean handled) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07002083 if (LOCAL_LOGV) Log.v(TAG, "Telling window manager input event is finished");
Jeff Brown92ff1dd2010-08-11 16:16:06 -07002084
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002085 if (mFinishedCallback != null) {
Jeff Brown3915bb82010-11-05 15:02:16 -07002086 mFinishedCallback.finished(handled);
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002087 mFinishedCallback = null;
Jeff Brown92ff1dd2010-08-11 16:16:06 -07002088 } else {
Jeff Brown93ed4e32010-09-23 13:51:48 -07002089 Slog.w(TAG, "Attempted to tell the input queue that the current input event "
2090 + "is finished but there is no input event actually in progress.");
Jeff Brown46b9ac02010-04-22 18:58:52 -07002091 }
2092 }
2093
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002094 /**
2095 * Something in the current window tells us we need to change the touch mode. For
2096 * example, we are not in touch mode, and the user touches the screen.
2097 *
2098 * If the touch mode has changed, tell the window manager, and handle it locally.
2099 *
2100 * @param inTouchMode Whether we want to be in touch mode.
2101 * @return True if the touch mode changed and focus changed was changed as a result
2102 */
2103 boolean ensureTouchMode(boolean inTouchMode) {
2104 if (DBG) Log.d("touchmode", "ensureTouchMode(" + inTouchMode + "), current "
2105 + "touch mode is " + mAttachInfo.mInTouchMode);
2106 if (mAttachInfo.mInTouchMode == inTouchMode) return false;
2107
2108 // tell the window manager
2109 try {
2110 sWindowSession.setInTouchMode(inTouchMode);
2111 } catch (RemoteException e) {
2112 throw new RuntimeException(e);
2113 }
2114
2115 // handle the change
Romain Guy2d4cff62010-04-09 15:39:00 -07002116 return ensureTouchModeLocally(inTouchMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002117 }
2118
2119 /**
2120 * Ensure that the touch mode for this window is set, and if it is changing,
2121 * take the appropriate action.
2122 * @param inTouchMode Whether we want to be in touch mode.
2123 * @return True if the touch mode changed and focus changed was changed as a result
2124 */
Romain Guy2d4cff62010-04-09 15:39:00 -07002125 private boolean ensureTouchModeLocally(boolean inTouchMode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002126 if (DBG) Log.d("touchmode", "ensureTouchModeLocally(" + inTouchMode + "), current "
2127 + "touch mode is " + mAttachInfo.mInTouchMode);
2128
2129 if (mAttachInfo.mInTouchMode == inTouchMode) return false;
2130
2131 mAttachInfo.mInTouchMode = inTouchMode;
2132 mAttachInfo.mTreeObserver.dispatchOnTouchModeChanged(inTouchMode);
2133
Romain Guy2d4cff62010-04-09 15:39:00 -07002134 return (inTouchMode) ? enterTouchMode() : leaveTouchMode();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002135 }
2136
2137 private boolean enterTouchMode() {
2138 if (mView != null) {
2139 if (mView.hasFocus()) {
2140 // note: not relying on mFocusedView here because this could
2141 // be when the window is first being added, and mFocused isn't
2142 // set yet.
2143 final View focused = mView.findFocus();
2144 if (focused != null && !focused.isFocusableInTouchMode()) {
2145
2146 final ViewGroup ancestorToTakeFocus =
2147 findAncestorToTakeFocusInTouchMode(focused);
2148 if (ancestorToTakeFocus != null) {
2149 // there is an ancestor that wants focus after its descendants that
2150 // is focusable in touch mode.. give it focus
2151 return ancestorToTakeFocus.requestFocus();
2152 } else {
2153 // nothing appropriate to have focus in touch mode, clear it out
2154 mView.unFocus();
2155 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(focused, null);
2156 mFocusedView = null;
2157 return true;
2158 }
2159 }
2160 }
2161 }
2162 return false;
2163 }
2164
2165
2166 /**
2167 * Find an ancestor of focused that wants focus after its descendants and is
2168 * focusable in touch mode.
2169 * @param focused The currently focused view.
2170 * @return An appropriate view, or null if no such view exists.
2171 */
2172 private ViewGroup findAncestorToTakeFocusInTouchMode(View focused) {
2173 ViewParent parent = focused.getParent();
2174 while (parent instanceof ViewGroup) {
2175 final ViewGroup vgParent = (ViewGroup) parent;
2176 if (vgParent.getDescendantFocusability() == ViewGroup.FOCUS_AFTER_DESCENDANTS
2177 && vgParent.isFocusableInTouchMode()) {
2178 return vgParent;
2179 }
2180 if (vgParent.isRootNamespace()) {
2181 return null;
2182 } else {
2183 parent = vgParent.getParent();
2184 }
2185 }
2186 return null;
2187 }
2188
2189 private boolean leaveTouchMode() {
2190 if (mView != null) {
2191 if (mView.hasFocus()) {
2192 // i learned the hard way to not trust mFocusedView :)
2193 mFocusedView = mView.findFocus();
2194 if (!(mFocusedView instanceof ViewGroup)) {
2195 // some view has focus, let it keep it
2196 return false;
2197 } else if (((ViewGroup)mFocusedView).getDescendantFocusability() !=
2198 ViewGroup.FOCUS_AFTER_DESCENDANTS) {
2199 // some view group has focus, and doesn't prefer its children
2200 // over itself for focus, so let them keep it.
2201 return false;
2202 }
2203 }
2204
2205 // find the best view to give focus to in this brave new non-touch-mode
2206 // world
2207 final View focused = focusSearch(null, View.FOCUS_DOWN);
2208 if (focused != null) {
2209 return focused.requestFocus(View.FOCUS_DOWN);
2210 }
2211 }
2212 return false;
2213 }
2214
Jeff Brown3915bb82010-11-05 15:02:16 -07002215 private void deliverPointerEvent(MotionEvent event, boolean sendDone) {
2216 // If there is no view, then the event will not be handled.
2217 if (mView == null || !mAdded) {
2218 finishPointerEvent(event, sendDone, false);
2219 return;
2220 }
2221
2222 // Translate the pointer event for compatibility, if needed.
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002223 if (mTranslator != null) {
2224 mTranslator.translateEventInScreenToAppWindow(event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002225 }
2226
Jeff Brown3915bb82010-11-05 15:02:16 -07002227 // Enter touch mode on the down.
2228 boolean isDown = event.getAction() == MotionEvent.ACTION_DOWN;
2229 if (isDown) {
2230 ensureTouchMode(true);
2231 }
2232 if(Config.LOGV) {
2233 captureMotionLog("captureDispatchPointer", event);
2234 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002235
Jeff Brown3915bb82010-11-05 15:02:16 -07002236 // Offset the scroll position.
2237 if (mCurScrollY != 0) {
2238 event.offsetLocation(0, mCurScrollY);
2239 }
2240 if (MEASURE_LATENCY) {
2241 lt.sample("A Dispatching TouchEvents", System.nanoTime() - event.getEventTimeNano());
2242 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002243
Jeff Brown3915bb82010-11-05 15:02:16 -07002244 // Remember the touch position for possible drag-initiation.
2245 mLastTouchPoint.x = event.getRawX();
2246 mLastTouchPoint.y = event.getRawY();
2247
2248 // Dispatch touch to view hierarchy.
2249 boolean handled = mView.dispatchTouchEvent(event);
2250 if (MEASURE_LATENCY) {
2251 lt.sample("B Dispatched TouchEvents ", System.nanoTime() - event.getEventTimeNano());
2252 }
2253 if (handled) {
2254 finishPointerEvent(event, sendDone, true);
2255 return;
2256 }
2257
2258 // Apply edge slop and try again, if appropriate.
2259 final int edgeFlags = event.getEdgeFlags();
2260 if (edgeFlags != 0 && mView instanceof ViewGroup) {
2261 final int edgeSlop = mViewConfiguration.getScaledEdgeSlop();
2262 int direction = View.FOCUS_UP;
2263 int x = (int)event.getX();
2264 int y = (int)event.getY();
2265 final int[] deltas = new int[2];
2266
2267 if ((edgeFlags & MotionEvent.EDGE_TOP) != 0) {
2268 direction = View.FOCUS_DOWN;
2269 if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
2270 deltas[0] = edgeSlop;
2271 x += edgeSlop;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002272 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
Jeff Brown3915bb82010-11-05 15:02:16 -07002273 deltas[0] = -edgeSlop;
2274 x -= edgeSlop;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002275 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002276 } else if ((edgeFlags & MotionEvent.EDGE_BOTTOM) != 0) {
2277 direction = View.FOCUS_UP;
2278 if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
2279 deltas[0] = edgeSlop;
2280 x += edgeSlop;
2281 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
2282 deltas[0] = -edgeSlop;
2283 x -= edgeSlop;
2284 }
2285 } else if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
2286 direction = View.FOCUS_RIGHT;
2287 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
2288 direction = View.FOCUS_LEFT;
2289 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002290
Jeff Brown3915bb82010-11-05 15:02:16 -07002291 View nearest = FocusFinder.getInstance().findNearestTouchable(
2292 ((ViewGroup) mView), x, y, direction, deltas);
2293 if (nearest != null) {
2294 event.offsetLocation(deltas[0], deltas[1]);
2295 event.setEdgeFlags(0);
2296 if (mView.dispatchTouchEvent(event)) {
2297 finishPointerEvent(event, sendDone, true);
2298 return;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002299 }
2300 }
2301 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002302
2303 // Pointer event was unhandled.
2304 finishPointerEvent(event, sendDone, false);
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002305 }
2306
Jeff Brown3915bb82010-11-05 15:02:16 -07002307 private void finishPointerEvent(MotionEvent event, boolean sendDone, boolean handled) {
2308 event.recycle();
2309 if (sendDone) {
2310 finishInputEvent(handled);
2311 }
2312 if (LOCAL_LOGV || WATCH_POINTER) Log.i(TAG, "Done dispatching!");
2313 }
2314
2315 private void deliverTrackballEvent(MotionEvent event, boolean sendDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002316 if (DEBUG_TRACKBALL) Log.v(TAG, "Motion event:" + event);
2317
Jeff Brown3915bb82010-11-05 15:02:16 -07002318 // If there is no view, then the event will not be handled.
2319 if (mView == null || !mAdded) {
2320 finishTrackballEvent(event, sendDone, false);
2321 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002322 }
2323
Jeff Brown3915bb82010-11-05 15:02:16 -07002324 // Deliver the trackball event to the view.
2325 if (mView.dispatchTrackballEvent(event)) {
2326 // If we reach this, we delivered a trackball event to mView and
2327 // mView consumed it. Because we will not translate the trackball
2328 // event into a key event, touch mode will not exit, so we exit
2329 // touch mode here.
2330 ensureTouchMode(false);
2331
2332 finishTrackballEvent(event, sendDone, true);
2333 mLastTrackballTime = Integer.MIN_VALUE;
2334 return;
2335 }
2336
2337 // Translate the trackball event into DPAD keys and try to deliver those.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002338 final TrackballAxis x = mTrackballAxisX;
2339 final TrackballAxis y = mTrackballAxisY;
2340
2341 long curTime = SystemClock.uptimeMillis();
Jeff Brown3915bb82010-11-05 15:02:16 -07002342 if ((mLastTrackballTime + MAX_TRACKBALL_DELAY) < curTime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002343 // It has been too long since the last movement,
2344 // so restart at the beginning.
2345 x.reset(0);
2346 y.reset(0);
2347 mLastTrackballTime = curTime;
2348 }
2349
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002350 final int action = event.getAction();
Jeff Brown49ed71d2010-12-06 17:13:33 -08002351 final int metaState = event.getMetaState();
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002352 switch (action) {
2353 case MotionEvent.ACTION_DOWN:
2354 x.reset(2);
2355 y.reset(2);
2356 deliverKeyEvent(new KeyEvent(curTime, curTime,
Jeff Brown49ed71d2010-12-06 17:13:33 -08002357 KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_CENTER, 0, metaState,
2358 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
2359 InputDevice.SOURCE_KEYBOARD), false);
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002360 break;
2361 case MotionEvent.ACTION_UP:
2362 x.reset(2);
2363 y.reset(2);
2364 deliverKeyEvent(new KeyEvent(curTime, curTime,
Jeff Brown49ed71d2010-12-06 17:13:33 -08002365 KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_CENTER, 0, metaState,
2366 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
2367 InputDevice.SOURCE_KEYBOARD), false);
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002368 break;
2369 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002370
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002371 if (DEBUG_TRACKBALL) Log.v(TAG, "TB X=" + x.position + " step="
2372 + x.step + " dir=" + x.dir + " acc=" + x.acceleration
2373 + " move=" + event.getX()
2374 + " / Y=" + y.position + " step="
2375 + y.step + " dir=" + y.dir + " acc=" + y.acceleration
2376 + " move=" + event.getY());
2377 final float xOff = x.collect(event.getX(), event.getEventTime(), "X");
2378 final float yOff = y.collect(event.getY(), event.getEventTime(), "Y");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002379
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002380 // Generate DPAD events based on the trackball movement.
2381 // We pick the axis that has moved the most as the direction of
2382 // the DPAD. When we generate DPAD events for one axis, then the
2383 // other axis is reset -- we don't want to perform DPAD jumps due
2384 // to slight movements in the trackball when making major movements
2385 // along the other axis.
2386 int keycode = 0;
2387 int movement = 0;
2388 float accel = 1;
2389 if (xOff > yOff) {
2390 movement = x.generate((2/event.getXPrecision()));
2391 if (movement != 0) {
2392 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_RIGHT
2393 : KeyEvent.KEYCODE_DPAD_LEFT;
2394 accel = x.acceleration;
2395 y.reset(2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002396 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002397 } else if (yOff > 0) {
2398 movement = y.generate((2/event.getYPrecision()));
2399 if (movement != 0) {
2400 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_DOWN
2401 : KeyEvent.KEYCODE_DPAD_UP;
2402 accel = y.acceleration;
2403 x.reset(2);
2404 }
2405 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002406
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002407 if (keycode != 0) {
2408 if (movement < 0) movement = -movement;
2409 int accelMovement = (int)(movement * accel);
2410 if (DEBUG_TRACKBALL) Log.v(TAG, "Move: movement=" + movement
2411 + " accelMovement=" + accelMovement
2412 + " accel=" + accel);
2413 if (accelMovement > movement) {
2414 if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: "
2415 + keycode);
2416 movement--;
Jeff Brown49ed71d2010-12-06 17:13:33 -08002417 int repeatCount = accelMovement - movement;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002418 deliverKeyEvent(new KeyEvent(curTime, curTime,
Jeff Brown49ed71d2010-12-06 17:13:33 -08002419 KeyEvent.ACTION_MULTIPLE, keycode, repeatCount, metaState,
2420 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
2421 InputDevice.SOURCE_KEYBOARD), false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002422 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002423 while (movement > 0) {
2424 if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: "
2425 + keycode);
2426 movement--;
2427 curTime = SystemClock.uptimeMillis();
2428 deliverKeyEvent(new KeyEvent(curTime, curTime,
Jeff Brown49ed71d2010-12-06 17:13:33 -08002429 KeyEvent.ACTION_DOWN, keycode, 0, metaState,
2430 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
2431 InputDevice.SOURCE_KEYBOARD), false);
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002432 deliverKeyEvent(new KeyEvent(curTime, curTime,
Jeff Brown49ed71d2010-12-06 17:13:33 -08002433 KeyEvent.ACTION_UP, keycode, 0, metaState,
2434 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
2435 InputDevice.SOURCE_KEYBOARD), false);
2436 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002437 mLastTrackballTime = curTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002438 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002439
2440 // Unfortunately we can't tell whether the application consumed the keys, so
2441 // we always consider the trackball event handled.
2442 finishTrackballEvent(event, sendDone, true);
2443 }
2444
2445 private void finishTrackballEvent(MotionEvent event, boolean sendDone, boolean handled) {
2446 event.recycle();
2447 if (sendDone) {
2448 finishInputEvent(handled);
2449 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002450 }
2451
2452 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08002453 * Returns true if the key is used for keyboard navigation.
2454 * @param keyEvent The key event.
2455 * @return True if the key is used for keyboard navigation.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002456 */
Jeff Brown4e6319b2010-12-13 10:36:51 -08002457 private static boolean isNavigationKey(KeyEvent keyEvent) {
2458 switch (keyEvent.getKeyCode()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002459 case KeyEvent.KEYCODE_DPAD_LEFT:
2460 case KeyEvent.KEYCODE_DPAD_RIGHT:
2461 case KeyEvent.KEYCODE_DPAD_UP:
2462 case KeyEvent.KEYCODE_DPAD_DOWN:
Jeff Brown4e6319b2010-12-13 10:36:51 -08002463 case KeyEvent.KEYCODE_DPAD_CENTER:
2464 case KeyEvent.KEYCODE_PAGE_UP:
2465 case KeyEvent.KEYCODE_PAGE_DOWN:
2466 case KeyEvent.KEYCODE_MOVE_HOME:
2467 case KeyEvent.KEYCODE_MOVE_END:
2468 case KeyEvent.KEYCODE_TAB:
2469 case KeyEvent.KEYCODE_SPACE:
2470 case KeyEvent.KEYCODE_ENTER:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002471 return true;
2472 }
2473 return false;
2474 }
2475
2476 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08002477 * Returns true if the key is used for typing.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002478 * @param keyEvent The key event.
Jeff Brown4e6319b2010-12-13 10:36:51 -08002479 * @return True if the key is used for typing.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002480 */
Jeff Brown4e6319b2010-12-13 10:36:51 -08002481 private static boolean isTypingKey(KeyEvent keyEvent) {
2482 return keyEvent.getUnicodeChar() > 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002483 }
2484
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002485 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08002486 * See if the key event means we should leave touch mode (and leave touch mode if so).
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002487 * @param event The key event.
2488 * @return Whether this key event should be consumed (meaning the act of
2489 * leaving touch mode alone is considered the event).
2490 */
2491 private boolean checkForLeavingTouchModeAndConsume(KeyEvent event) {
Jeff Brown4e6319b2010-12-13 10:36:51 -08002492 // Only relevant in touch mode.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002493 if (!mAttachInfo.mInTouchMode) {
2494 return false;
2495 }
2496
Jeff Brown4e6319b2010-12-13 10:36:51 -08002497 // Only consider leaving touch mode on DOWN or MULTIPLE actions, never on UP.
2498 final int action = event.getAction();
2499 if (action != KeyEvent.ACTION_DOWN && action != KeyEvent.ACTION_MULTIPLE) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002500 return false;
2501 }
2502
Jeff Brown4e6319b2010-12-13 10:36:51 -08002503 // Don't leave touch mode if the IME told us not to.
2504 if ((event.getFlags() & KeyEvent.FLAG_KEEP_TOUCH_MODE) != 0) {
2505 return false;
2506 }
2507
2508 // If the key can be used for keyboard navigation then leave touch mode
2509 // and select a focused view if needed (in ensureTouchMode).
2510 // When a new focused view is selected, we consume the navigation key because
2511 // navigation doesn't make much sense unless a view already has focus so
2512 // the key's purpose is to set focus.
2513 if (isNavigationKey(event)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002514 return ensureTouchMode(false);
2515 }
Jeff Brown4e6319b2010-12-13 10:36:51 -08002516
2517 // If the key can be used for typing then leave touch mode
2518 // and select a focused view if needed (in ensureTouchMode).
2519 // Always allow the view to process the typing key.
2520 if (isTypingKey(event)) {
2521 ensureTouchMode(false);
2522 return false;
2523 }
2524
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002525 return false;
2526 }
2527
2528 /**
Romain Guy8506ab42009-06-11 17:35:47 -07002529 * log motion events
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002530 */
2531 private static void captureMotionLog(String subTag, MotionEvent ev) {
Romain Guy8506ab42009-06-11 17:35:47 -07002532 //check dynamic switch
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002533 if (ev == null ||
2534 SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_EVENT, 0) == 0) {
2535 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002536 }
Romain Guy8506ab42009-06-11 17:35:47 -07002537
2538 StringBuilder sb = new StringBuilder(subTag + ": ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002539 sb.append(ev.getDownTime()).append(',');
2540 sb.append(ev.getEventTime()).append(',');
2541 sb.append(ev.getAction()).append(',');
Romain Guy8506ab42009-06-11 17:35:47 -07002542 sb.append(ev.getX()).append(',');
2543 sb.append(ev.getY()).append(',');
2544 sb.append(ev.getPressure()).append(',');
2545 sb.append(ev.getSize()).append(',');
2546 sb.append(ev.getMetaState()).append(',');
2547 sb.append(ev.getXPrecision()).append(',');
2548 sb.append(ev.getYPrecision()).append(',');
2549 sb.append(ev.getDeviceId()).append(',');
2550 sb.append(ev.getEdgeFlags());
2551 Log.d(TAG, sb.toString());
2552 }
2553 /**
2554 * log motion events
2555 */
2556 private static void captureKeyLog(String subTag, KeyEvent ev) {
2557 //check dynamic switch
2558 if (ev == null ||
2559 SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_EVENT, 0) == 0) {
2560 return;
2561 }
2562 StringBuilder sb = new StringBuilder(subTag + ": ");
2563 sb.append(ev.getDownTime()).append(',');
2564 sb.append(ev.getEventTime()).append(',');
2565 sb.append(ev.getAction()).append(',');
2566 sb.append(ev.getKeyCode()).append(',');
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002567 sb.append(ev.getRepeatCount()).append(',');
2568 sb.append(ev.getMetaState()).append(',');
2569 sb.append(ev.getDeviceId()).append(',');
2570 sb.append(ev.getScanCode());
Romain Guy8506ab42009-06-11 17:35:47 -07002571 Log.d(TAG, sb.toString());
2572 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002573
2574 int enqueuePendingEvent(Object event, boolean sendDone) {
2575 int seq = mPendingEventSeq+1;
2576 if (seq < 0) seq = 0;
2577 mPendingEventSeq = seq;
2578 mPendingEvents.put(seq, event);
2579 return sendDone ? seq : -seq;
2580 }
2581
2582 Object retrievePendingEvent(int seq) {
2583 if (seq < 0) seq = -seq;
2584 Object event = mPendingEvents.get(seq);
2585 if (event != null) {
2586 mPendingEvents.remove(seq);
2587 }
2588 return event;
2589 }
Romain Guy8506ab42009-06-11 17:35:47 -07002590
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002591 private void deliverKeyEvent(KeyEvent event, boolean sendDone) {
Jeff Brown3915bb82010-11-05 15:02:16 -07002592 // If there is no view, then the event will not be handled.
2593 if (mView == null || !mAdded) {
2594 finishKeyEvent(event, sendDone, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002595 return;
2596 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002597
2598 if (LOCAL_LOGV) Log.v(TAG, "Dispatching key " + event + " to " + mView);
2599
2600 // Perform predispatching before the IME.
2601 if (mView.dispatchKeyEventPreIme(event)) {
2602 finishKeyEvent(event, sendDone, true);
2603 return;
2604 }
2605
2606 // Dispatch to the IME before propagating down the view hierarchy.
2607 // The IME will eventually call back into handleFinishedEvent.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002608 if (mLastWasImTarget) {
2609 InputMethodManager imm = InputMethodManager.peekInstance();
Jeff Brown3915bb82010-11-05 15:02:16 -07002610 if (imm != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002611 int seq = enqueuePendingEvent(event, sendDone);
2612 if (DEBUG_IMF) Log.v(TAG, "Sending key event to IME: seq="
2613 + seq + " event=" + event);
Jeff Brown3915bb82010-11-05 15:02:16 -07002614 imm.dispatchKeyEvent(mView.getContext(), seq, event, mInputMethodCallback);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002615 return;
2616 }
2617 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002618
2619 // Not dispatching to IME, continue with post IME actions.
2620 deliverKeyEventPostIme(event, sendDone);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002621 }
2622
Jeff Brown3915bb82010-11-05 15:02:16 -07002623 private void handleFinishedEvent(int seq, boolean handled) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002624 final KeyEvent event = (KeyEvent)retrievePendingEvent(seq);
2625 if (DEBUG_IMF) Log.v(TAG, "IME finished event: seq=" + seq
2626 + " handled=" + handled + " event=" + event);
2627 if (event != null) {
2628 final boolean sendDone = seq >= 0;
Jeff Brown3915bb82010-11-05 15:02:16 -07002629 if (handled) {
2630 finishKeyEvent(event, sendDone, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002631 } else {
Jeff Brown3915bb82010-11-05 15:02:16 -07002632 deliverKeyEventPostIme(event, sendDone);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002633 }
2634 }
2635 }
Romain Guy8506ab42009-06-11 17:35:47 -07002636
Jeff Brown3915bb82010-11-05 15:02:16 -07002637 private void deliverKeyEventPostIme(KeyEvent event, boolean sendDone) {
2638 // If the view went away, then the event will not be handled.
2639 if (mView == null || !mAdded) {
2640 finishKeyEvent(event, sendDone, false);
2641 return;
2642 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002643
Jeff Brown3915bb82010-11-05 15:02:16 -07002644 // If the key's purpose is to exit touch mode then we consume it and consider it handled.
2645 if (checkForLeavingTouchModeAndConsume(event)) {
2646 finishKeyEvent(event, sendDone, true);
2647 return;
2648 }
Romain Guy8506ab42009-06-11 17:35:47 -07002649
Jeff Brown3915bb82010-11-05 15:02:16 -07002650 if (Config.LOGV) {
2651 captureKeyLog("captureDispatchKeyEvent", event);
2652 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002653
Jeff Brown90655042010-12-02 13:50:46 -08002654 // Make sure the fallback event policy sees all keys that will be delivered to the
2655 // view hierarchy.
2656 mFallbackEventHandler.preDispatchKeyEvent(event);
2657
Jeff Brown3915bb82010-11-05 15:02:16 -07002658 // Deliver the key to the view hierarchy.
2659 if (mView.dispatchKeyEvent(event)) {
2660 finishKeyEvent(event, sendDone, true);
2661 return;
2662 }
Joe Onorato86f67862010-11-05 18:57:34 -07002663
Jeff Brownc1df9072010-12-21 16:38:50 -08002664 // If the Control modifier is held, try to interpret the key as a shortcut.
2665 if (event.getAction() == KeyEvent.ACTION_UP
2666 && event.isCtrlPressed()
2667 && !KeyEvent.isModifierKey(event.getKeyCode())) {
2668 if (mView.dispatchKeyShortcutEvent(event)) {
2669 finishKeyEvent(event, sendDone, true);
2670 return;
2671 }
2672 }
2673
Jeff Brown3915bb82010-11-05 15:02:16 -07002674 // Apply the fallback event policy.
2675 if (mFallbackEventHandler.dispatchKeyEvent(event)) {
2676 finishKeyEvent(event, sendDone, true);
2677 return;
2678 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002679
Jeff Brown3915bb82010-11-05 15:02:16 -07002680 // Handle automatic focus changes.
2681 if (event.getAction() == KeyEvent.ACTION_DOWN) {
2682 int direction = 0;
2683 switch (event.getKeyCode()) {
2684 case KeyEvent.KEYCODE_DPAD_LEFT:
Jeff Brown4e6319b2010-12-13 10:36:51 -08002685 if (event.hasNoModifiers()) {
2686 direction = View.FOCUS_LEFT;
2687 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002688 break;
2689 case KeyEvent.KEYCODE_DPAD_RIGHT:
Jeff Brown4e6319b2010-12-13 10:36:51 -08002690 if (event.hasNoModifiers()) {
2691 direction = View.FOCUS_RIGHT;
2692 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002693 break;
2694 case KeyEvent.KEYCODE_DPAD_UP:
Jeff Brown4e6319b2010-12-13 10:36:51 -08002695 if (event.hasNoModifiers()) {
2696 direction = View.FOCUS_UP;
2697 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002698 break;
2699 case KeyEvent.KEYCODE_DPAD_DOWN:
Jeff Brown4e6319b2010-12-13 10:36:51 -08002700 if (event.hasNoModifiers()) {
2701 direction = View.FOCUS_DOWN;
2702 }
2703 break;
2704 case KeyEvent.KEYCODE_TAB:
2705 if (event.hasNoModifiers()) {
2706 direction = View.FOCUS_FORWARD;
2707 } else if (event.hasModifiers(KeyEvent.META_SHIFT_ON)) {
2708 direction = View.FOCUS_BACKWARD;
2709 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002710 break;
2711 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002712
Jeff Brown3915bb82010-11-05 15:02:16 -07002713 if (direction != 0) {
2714 View focused = mView != null ? mView.findFocus() : null;
2715 if (focused != null) {
2716 View v = focused.focusSearch(direction);
2717 if (v != null && v != focused) {
2718 // do the math the get the interesting rect
2719 // of previous focused into the coord system of
2720 // newly focused view
2721 focused.getFocusedRect(mTempRect);
2722 if (mView instanceof ViewGroup) {
2723 ((ViewGroup) mView).offsetDescendantRectToMyCoords(
2724 focused, mTempRect);
2725 ((ViewGroup) mView).offsetRectIntoDescendantCoords(
2726 v, mTempRect);
2727 }
2728 if (v.requestFocus(direction, mTempRect)) {
2729 playSoundEffect(
2730 SoundEffectConstants.getContantForFocusDirection(direction));
2731 finishKeyEvent(event, sendDone, true);
2732 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002733 }
2734 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002735
2736 // Give the focused view a last chance to handle the dpad key.
2737 if (mView.dispatchUnhandledMove(focused, direction)) {
2738 finishKeyEvent(event, sendDone, true);
2739 return;
2740 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002741 }
2742 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002743 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002744
Jeff Brown3915bb82010-11-05 15:02:16 -07002745 // Key was unhandled.
2746 finishKeyEvent(event, sendDone, false);
2747 }
2748
2749 private void finishKeyEvent(KeyEvent event, boolean sendDone, boolean handled) {
2750 if (sendDone) {
2751 finishInputEvent(handled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002752 }
2753 }
2754
Christopher Tatea53146c2010-09-07 11:57:52 -07002755 /* drag/drop */
Christopher Tate407b4e92010-11-30 17:14:08 -08002756 void setLocalDragState(Object obj) {
2757 mLocalDragState = obj;
2758 }
2759
Christopher Tatea53146c2010-09-07 11:57:52 -07002760 private void handleDragEvent(DragEvent event) {
2761 // From the root, only drag start/end/location are dispatched. entered/exited
2762 // are determined and dispatched by the viewgroup hierarchy, who then report
2763 // that back here for ultimate reporting back to the framework.
2764 if (mView != null && mAdded) {
2765 final int what = event.mAction;
2766
2767 if (what == DragEvent.ACTION_DRAG_EXITED) {
2768 // A direct EXITED event means that the window manager knows we've just crossed
2769 // a window boundary, so the current drag target within this one must have
2770 // just been exited. Send it the usual notifications and then we're done
2771 // for now.
Chris Tate9d1ab882010-11-02 15:55:39 -07002772 mView.dispatchDragEvent(event);
Christopher Tatea53146c2010-09-07 11:57:52 -07002773 } else {
2774 // Cache the drag description when the operation starts, then fill it in
2775 // on subsequent calls as a convenience
2776 if (what == DragEvent.ACTION_DRAG_STARTED) {
Chris Tate9d1ab882010-11-02 15:55:39 -07002777 mCurrentDragView = null; // Start the current-recipient tracking
Christopher Tatea53146c2010-09-07 11:57:52 -07002778 mDragDescription = event.mClipDescription;
2779 } else {
2780 event.mClipDescription = mDragDescription;
2781 }
2782
2783 // For events with a [screen] location, translate into window coordinates
2784 if ((what == DragEvent.ACTION_DRAG_LOCATION) || (what == DragEvent.ACTION_DROP)) {
2785 mDragPoint.set(event.mX, event.mY);
2786 if (mTranslator != null) {
2787 mTranslator.translatePointInScreenToAppWindow(mDragPoint);
2788 }
2789
2790 if (mCurScrollY != 0) {
2791 mDragPoint.offset(0, mCurScrollY);
2792 }
2793
2794 event.mX = mDragPoint.x;
2795 event.mY = mDragPoint.y;
2796 }
2797
2798 // Remember who the current drag target is pre-dispatch
2799 final View prevDragView = mCurrentDragView;
2800
2801 // Now dispatch the drag/drop event
Chris Tated4533f12010-10-19 15:15:08 -07002802 boolean result = mView.dispatchDragEvent(event);
Christopher Tatea53146c2010-09-07 11:57:52 -07002803
2804 // If we changed apparent drag target, tell the OS about it
2805 if (prevDragView != mCurrentDragView) {
2806 try {
2807 if (prevDragView != null) {
2808 sWindowSession.dragRecipientExited(mWindow);
2809 }
2810 if (mCurrentDragView != null) {
2811 sWindowSession.dragRecipientEntered(mWindow);
2812 }
2813 } catch (RemoteException e) {
2814 Slog.e(TAG, "Unable to note drag target change");
2815 }
Christopher Tatea53146c2010-09-07 11:57:52 -07002816 }
Chris Tated4533f12010-10-19 15:15:08 -07002817
Christopher Tate407b4e92010-11-30 17:14:08 -08002818 // Report the drop result when we're done
Chris Tated4533f12010-10-19 15:15:08 -07002819 if (what == DragEvent.ACTION_DROP) {
Christopher Tate1fc014f2011-01-19 12:56:26 -08002820 mDragDescription = null;
Chris Tated4533f12010-10-19 15:15:08 -07002821 try {
2822 Log.i(TAG, "Reporting drop result: " + result);
2823 sWindowSession.reportDropResult(mWindow, result);
2824 } catch (RemoteException e) {
2825 Log.e(TAG, "Unable to report drop result");
2826 }
2827 }
Christopher Tate407b4e92010-11-30 17:14:08 -08002828
2829 // When the drag operation ends, release any local state object
2830 // that may have been in use
2831 if (what == DragEvent.ACTION_DRAG_ENDED) {
2832 setLocalDragState(null);
2833 }
Christopher Tatea53146c2010-09-07 11:57:52 -07002834 }
2835 }
2836 event.recycle();
2837 }
2838
Joe Onorato664644d2011-01-23 17:53:23 -08002839 public void handleDispatchSystemUiVisibilityChanged(int visibility) {
2840 if (mView == null) return;
2841 mView.dispatchSystemUiVisibilityChanged(visibility);
2842 }
2843
Christopher Tate2c095f32010-10-04 14:13:40 -07002844 public void getLastTouchPoint(Point outLocation) {
2845 outLocation.x = (int) mLastTouchPoint.x;
2846 outLocation.y = (int) mLastTouchPoint.y;
2847 }
2848
Chris Tate9d1ab882010-11-02 15:55:39 -07002849 public void setDragFocus(View newDragTarget) {
Christopher Tatea53146c2010-09-07 11:57:52 -07002850 if (mCurrentDragView != newDragTarget) {
Chris Tate048691c2010-10-12 17:39:18 -07002851 mCurrentDragView = newDragTarget;
Christopher Tatea53146c2010-09-07 11:57:52 -07002852 }
Christopher Tatea53146c2010-09-07 11:57:52 -07002853 }
2854
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002855 private AudioManager getAudioManager() {
2856 if (mView == null) {
2857 throw new IllegalStateException("getAudioManager called when there is no mView");
2858 }
2859 if (mAudioManager == null) {
2860 mAudioManager = (AudioManager) mView.getContext().getSystemService(Context.AUDIO_SERVICE);
2861 }
2862 return mAudioManager;
2863 }
2864
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002865 private int relayoutWindow(WindowManager.LayoutParams params, int viewVisibility,
2866 boolean insetsPending) throws RemoteException {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002867
2868 float appScale = mAttachInfo.mApplicationScale;
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002869 boolean restore = false;
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002870 if (params != null && mTranslator != null) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07002871 restore = true;
2872 params.backup();
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002873 mTranslator.translateWindowLayout(params);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002874 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002875 if (params != null) {
2876 if (DBG) Log.d(TAG, "WindowLayout in layoutWindow:" + params);
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002877 }
Dianne Hackborn694f79b2010-03-17 19:44:59 -07002878 mPendingConfiguration.seq = 0;
Dianne Hackbornf123e492010-09-24 11:16:23 -07002879 //Log.d(TAG, ">>>>>> CALLING relayout");
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002880 int relayoutResult = sWindowSession.relayout(
2881 mWindow, params,
Dianne Hackborn189ee182010-12-02 21:48:53 -08002882 (int) (mView.getMeasuredWidth() * appScale + 0.5f),
2883 (int) (mView.getMeasuredHeight() * appScale + 0.5f),
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002884 viewVisibility, insetsPending, mWinFrame,
Dianne Hackborn694f79b2010-03-17 19:44:59 -07002885 mPendingContentInsets, mPendingVisibleInsets,
2886 mPendingConfiguration, mSurface);
Dianne Hackbornf123e492010-09-24 11:16:23 -07002887 //Log.d(TAG, "<<<<<< BACK FROM relayout");
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002888 if (restore) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07002889 params.restore();
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002890 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002891
2892 if (mTranslator != null) {
2893 mTranslator.translateRectInScreenToAppWinFrame(mWinFrame);
2894 mTranslator.translateRectInScreenToAppWindow(mPendingContentInsets);
2895 mTranslator.translateRectInScreenToAppWindow(mPendingVisibleInsets);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002896 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002897 return relayoutResult;
2898 }
Romain Guy8506ab42009-06-11 17:35:47 -07002899
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002900 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002901 * {@inheritDoc}
2902 */
2903 public void playSoundEffect(int effectId) {
2904 checkThread();
2905
Jean-Michel Trivi13b18fd2010-05-05 09:18:15 -07002906 try {
2907 final AudioManager audioManager = getAudioManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002908
Jean-Michel Trivi13b18fd2010-05-05 09:18:15 -07002909 switch (effectId) {
2910 case SoundEffectConstants.CLICK:
2911 audioManager.playSoundEffect(AudioManager.FX_KEY_CLICK);
2912 return;
2913 case SoundEffectConstants.NAVIGATION_DOWN:
2914 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_DOWN);
2915 return;
2916 case SoundEffectConstants.NAVIGATION_LEFT:
2917 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_LEFT);
2918 return;
2919 case SoundEffectConstants.NAVIGATION_RIGHT:
2920 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_RIGHT);
2921 return;
2922 case SoundEffectConstants.NAVIGATION_UP:
2923 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_UP);
2924 return;
2925 default:
2926 throw new IllegalArgumentException("unknown effect id " + effectId +
2927 " not defined in " + SoundEffectConstants.class.getCanonicalName());
2928 }
2929 } catch (IllegalStateException e) {
2930 // Exception thrown by getAudioManager() when mView is null
2931 Log.e(TAG, "FATAL EXCEPTION when attempting to play sound effect: " + e);
2932 e.printStackTrace();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002933 }
2934 }
2935
2936 /**
2937 * {@inheritDoc}
2938 */
2939 public boolean performHapticFeedback(int effectId, boolean always) {
2940 try {
2941 return sWindowSession.performHapticFeedback(mWindow, effectId, always);
2942 } catch (RemoteException e) {
2943 return false;
2944 }
2945 }
2946
2947 /**
2948 * {@inheritDoc}
2949 */
2950 public View focusSearch(View focused, int direction) {
2951 checkThread();
2952 if (!(mView instanceof ViewGroup)) {
2953 return null;
2954 }
2955 return FocusFinder.getInstance().findNextFocus((ViewGroup) mView, focused, direction);
2956 }
2957
2958 public void debug() {
2959 mView.debug();
2960 }
2961
2962 public void die(boolean immediate) {
Dianne Hackborn94d69142009-09-28 22:14:42 -07002963 if (immediate) {
2964 doDie();
2965 } else {
2966 sendEmptyMessage(DIE);
2967 }
2968 }
2969
2970 void doDie() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002971 checkThread();
Jeff Brownb75fa302010-07-15 23:47:29 -07002972 if (LOCAL_LOGV) Log.v(TAG, "DIE in " + this + " of " + mSurface);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002973 synchronized (this) {
2974 if (mAdded && !mFirst) {
Romain Guy29d89972010-09-22 16:10:57 -07002975 destroyHardwareRenderer();
2976
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002977 int viewVisibility = mView.getVisibility();
2978 boolean viewVisibilityChanged = mViewVisibility != viewVisibility;
2979 if (mWindowAttributesChanged || viewVisibilityChanged) {
2980 // If layout params have been changed, first give them
2981 // to the window manager to make sure it has the correct
2982 // animation info.
2983 try {
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002984 if ((relayoutWindow(mWindowAttributes, viewVisibility, false)
2985 & WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002986 sWindowSession.finishDrawing(mWindow);
2987 }
2988 } catch (RemoteException e) {
2989 }
2990 }
2991
Dianne Hackborn0586a1b2009-09-06 21:08:27 -07002992 mSurface.release();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002993 }
2994 if (mAdded) {
2995 mAdded = false;
Dianne Hackborn94d69142009-09-28 22:14:42 -07002996 dispatchDetachedFromWindow();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002997 }
2998 }
2999 }
3000
Romain Guy29d89972010-09-22 16:10:57 -07003001 private void destroyHardwareRenderer() {
Romain Guyb051e892010-09-28 19:09:36 -07003002 if (mAttachInfo.mHardwareRenderer != null) {
3003 mAttachInfo.mHardwareRenderer.destroy(true);
3004 mAttachInfo.mHardwareRenderer = null;
Romain Guy29d89972010-09-22 16:10:57 -07003005 mAttachInfo.mHardwareAccelerated = false;
3006 }
3007 }
3008
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003009 public void dispatchFinishedEvent(int seq, boolean handled) {
3010 Message msg = obtainMessage(FINISHED_EVENT);
3011 msg.arg1 = seq;
3012 msg.arg2 = handled ? 1 : 0;
3013 sendMessage(msg);
3014 }
Mitsuru Oshima3d914922009-05-13 22:29:15 -07003015
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003016 public void dispatchResized(int w, int h, Rect coveredInsets,
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003017 Rect visibleInsets, boolean reportDraw, Configuration newConfig) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003018 if (DEBUG_LAYOUT) Log.v(TAG, "Resizing " + this + ": w=" + w
3019 + " h=" + h + " coveredInsets=" + coveredInsets.toShortString()
3020 + " visibleInsets=" + visibleInsets.toShortString()
3021 + " reportDraw=" + reportDraw);
3022 Message msg = obtainMessage(reportDraw ? RESIZED_REPORT :RESIZED);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07003023 if (mTranslator != null) {
3024 mTranslator.translateRectInScreenToAppWindow(coveredInsets);
3025 mTranslator.translateRectInScreenToAppWindow(visibleInsets);
3026 w *= mTranslator.applicationInvertedScale;
3027 h *= mTranslator.applicationInvertedScale;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07003028 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07003029 msg.arg1 = w;
3030 msg.arg2 = h;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003031 ResizedInfo ri = new ResizedInfo();
3032 ri.coveredInsets = new Rect(coveredInsets);
3033 ri.visibleInsets = new Rect(visibleInsets);
3034 ri.newConfig = newConfig;
3035 msg.obj = ri;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003036 sendMessage(msg);
3037 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07003038
Jeff Brown3915bb82010-11-05 15:02:16 -07003039 private InputQueue.FinishedCallback mFinishedCallback;
Jeff Brown46b9ac02010-04-22 18:58:52 -07003040
3041 private final InputHandler mInputHandler = new InputHandler() {
Jeff Brown3915bb82010-11-05 15:02:16 -07003042 public void handleKey(KeyEvent event, InputQueue.FinishedCallback finishedCallback) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07003043 startInputEvent(finishedCallback);
Jeff Brown92ff1dd2010-08-11 16:16:06 -07003044 dispatchKey(event, true);
Jeff Brown46b9ac02010-04-22 18:58:52 -07003045 }
3046
Jeff Brown3915bb82010-11-05 15:02:16 -07003047 public void handleMotion(MotionEvent event, InputQueue.FinishedCallback finishedCallback) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07003048 startInputEvent(finishedCallback);
3049 dispatchMotion(event, true);
Jeff Brown46b9ac02010-04-22 18:58:52 -07003050 }
3051 };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003052
3053 public void dispatchKey(KeyEvent event) {
Jeff Brown92ff1dd2010-08-11 16:16:06 -07003054 dispatchKey(event, false);
3055 }
3056
3057 private void dispatchKey(KeyEvent event, boolean sendDone) {
3058 //noinspection ConstantConditions
3059 if (false && event.getAction() == KeyEvent.ACTION_DOWN) {
3060 if (event.getKeyCode() == KeyEvent.KEYCODE_CAMERA) {
Romain Guy812ccbe2010-06-01 14:07:24 -07003061 if (DBG) Log.d("keydisp", "===================================================");
3062 if (DBG) Log.d("keydisp", "Focused view Hierarchy is:");
3063
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003064 debug();
3065
Romain Guy812ccbe2010-06-01 14:07:24 -07003066 if (DBG) Log.d("keydisp", "===================================================");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003067 }
3068 }
3069
3070 Message msg = obtainMessage(DISPATCH_KEY);
3071 msg.obj = event;
Jeff Brown92ff1dd2010-08-11 16:16:06 -07003072 msg.arg1 = sendDone ? 1 : 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003073
3074 if (LOCAL_LOGV) Log.v(
Jeff Brownc5ed5912010-07-14 18:48:53 -07003075 TAG, "sending key " + event + " to " + mView);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003076
3077 sendMessageAtTime(msg, event.getEventTime());
3078 }
Jeff Brownc5ed5912010-07-14 18:48:53 -07003079
3080 public void dispatchMotion(MotionEvent event) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07003081 dispatchMotion(event, false);
3082 }
3083
3084 private void dispatchMotion(MotionEvent event, boolean sendDone) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07003085 int source = event.getSource();
3086 if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07003087 dispatchPointer(event, sendDone);
Jeff Brownc5ed5912010-07-14 18:48:53 -07003088 } else if ((source & InputDevice.SOURCE_CLASS_TRACKBALL) != 0) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07003089 dispatchTrackball(event, sendDone);
Jeff Brownc5ed5912010-07-14 18:48:53 -07003090 } else {
3091 // TODO
3092 Log.v(TAG, "Dropping unsupported motion event (unimplemented): " + event);
Jeff Brown93ed4e32010-09-23 13:51:48 -07003093 if (sendDone) {
Jeff Brown3915bb82010-11-05 15:02:16 -07003094 finishInputEvent(false);
Jeff Brown93ed4e32010-09-23 13:51:48 -07003095 }
Jeff Brownc5ed5912010-07-14 18:48:53 -07003096 }
3097 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003098
Jeff Brown00fa7bd2010-07-02 15:37:36 -07003099 public void dispatchPointer(MotionEvent event) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07003100 dispatchPointer(event, false);
3101 }
3102
3103 private void dispatchPointer(MotionEvent event, boolean sendDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003104 Message msg = obtainMessage(DISPATCH_POINTER);
3105 msg.obj = event;
Jeff Brown93ed4e32010-09-23 13:51:48 -07003106 msg.arg1 = sendDone ? 1 : 0;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07003107 sendMessageAtTime(msg, event.getEventTime());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003108 }
3109
Jeff Brown00fa7bd2010-07-02 15:37:36 -07003110 public void dispatchTrackball(MotionEvent event) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07003111 dispatchTrackball(event, false);
3112 }
3113
3114 private void dispatchTrackball(MotionEvent event, boolean sendDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003115 Message msg = obtainMessage(DISPATCH_TRACKBALL);
3116 msg.obj = event;
Jeff Brown93ed4e32010-09-23 13:51:48 -07003117 msg.arg1 = sendDone ? 1 : 0;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07003118 sendMessageAtTime(msg, event.getEventTime());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003119 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07003120
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003121 public void dispatchAppVisibility(boolean visible) {
3122 Message msg = obtainMessage(DISPATCH_APP_VISIBILITY);
3123 msg.arg1 = visible ? 1 : 0;
3124 sendMessage(msg);
3125 }
3126
3127 public void dispatchGetNewSurface() {
3128 Message msg = obtainMessage(DISPATCH_GET_NEW_SURFACE);
3129 sendMessage(msg);
3130 }
3131
3132 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
3133 Message msg = Message.obtain();
3134 msg.what = WINDOW_FOCUS_CHANGED;
3135 msg.arg1 = hasFocus ? 1 : 0;
3136 msg.arg2 = inTouchMode ? 1 : 0;
3137 sendMessage(msg);
3138 }
3139
Dianne Hackbornffa42482009-09-23 22:20:11 -07003140 public void dispatchCloseSystemDialogs(String reason) {
3141 Message msg = Message.obtain();
3142 msg.what = CLOSE_SYSTEM_DIALOGS;
3143 msg.obj = reason;
3144 sendMessage(msg);
3145 }
Christopher Tatea53146c2010-09-07 11:57:52 -07003146
3147 public void dispatchDragEvent(DragEvent event) {
Chris Tate91e9bb32010-10-12 12:58:43 -07003148 final int what;
3149 if (event.getAction() == DragEvent.ACTION_DRAG_LOCATION) {
3150 what = DISPATCH_DRAG_LOCATION_EVENT;
3151 removeMessages(what);
3152 } else {
3153 what = DISPATCH_DRAG_EVENT;
3154 }
3155 Message msg = obtainMessage(what, event);
Christopher Tatea53146c2010-09-07 11:57:52 -07003156 sendMessage(msg);
3157 }
3158
Joe Onorato664644d2011-01-23 17:53:23 -08003159 public void dispatchSystemUiVisibilityChanged(int visibility) {
3160 sendMessage(obtainMessage(DISPATCH_SYSTEM_UI_VISIBILITY, visibility, 0));
3161 }
3162
svetoslavganov75986cf2009-05-14 22:28:01 -07003163 /**
3164 * The window is getting focus so if there is anything focused/selected
3165 * send an {@link AccessibilityEvent} to announce that.
3166 */
3167 private void sendAccessibilityEvents() {
3168 if (!AccessibilityManager.getInstance(mView.getContext()).isEnabled()) {
3169 return;
3170 }
3171 mView.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
3172 View focusedView = mView.findFocus();
3173 if (focusedView != null && focusedView != mView) {
3174 focusedView.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
3175 }
3176 }
3177
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003178 public boolean showContextMenuForChild(View originalView) {
3179 return false;
3180 }
3181
Adam Powell6e346362010-07-23 10:18:23 -07003182 public ActionMode startActionModeForChild(View originalView, ActionMode.Callback callback) {
3183 return null;
3184 }
3185
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003186 public void createContextMenu(ContextMenu menu) {
3187 }
3188
3189 public void childDrawableStateChanged(View child) {
3190 }
3191
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003192 void checkThread() {
3193 if (mThread != Thread.currentThread()) {
3194 throw new CalledFromWrongThreadException(
3195 "Only the original thread that created a view hierarchy can touch its views.");
3196 }
3197 }
3198
3199 public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
3200 // ViewRoot never intercepts touch event, so this can be a no-op
3201 }
3202
3203 public boolean requestChildRectangleOnScreen(View child, Rect rectangle,
3204 boolean immediate) {
3205 return scrollToRectOrFocus(rectangle, immediate);
3206 }
Romain Guy8506ab42009-06-11 17:35:47 -07003207
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07003208 class TakenSurfaceHolder extends BaseSurfaceHolder {
3209 @Override
3210 public boolean onAllowLockCanvas() {
3211 return mDrawingAllowed;
3212 }
3213
3214 @Override
3215 public void onRelayoutContainer() {
3216 // Not currently interesting -- from changing between fixed and layout size.
3217 }
3218
3219 public void setFormat(int format) {
3220 ((RootViewSurfaceTaker)mView).setSurfaceFormat(format);
3221 }
3222
3223 public void setType(int type) {
3224 ((RootViewSurfaceTaker)mView).setSurfaceType(type);
3225 }
3226
3227 @Override
3228 public void onUpdateSurface() {
3229 // We take care of format and type changes on our own.
3230 throw new IllegalStateException("Shouldn't be here");
3231 }
3232
3233 public boolean isCreating() {
3234 return mIsCreating;
3235 }
3236
3237 @Override
3238 public void setFixedSize(int width, int height) {
3239 throw new UnsupportedOperationException(
3240 "Currently only support sizing from layout");
3241 }
3242
3243 public void setKeepScreenOn(boolean screenOn) {
3244 ((RootViewSurfaceTaker)mView).setSurfaceKeepScreenOn(screenOn);
3245 }
3246 }
3247
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003248 static class InputMethodCallback extends IInputMethodCallback.Stub {
3249 private WeakReference<ViewRoot> mViewRoot;
3250
3251 public InputMethodCallback(ViewRoot viewRoot) {
3252 mViewRoot = new WeakReference<ViewRoot>(viewRoot);
3253 }
Romain Guy8506ab42009-06-11 17:35:47 -07003254
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003255 public void finishedEvent(int seq, boolean handled) {
3256 final ViewRoot viewRoot = mViewRoot.get();
3257 if (viewRoot != null) {
3258 viewRoot.dispatchFinishedEvent(seq, handled);
3259 }
3260 }
3261
3262 public void sessionCreated(IInputMethodSession session) throws RemoteException {
3263 // Stub -- not for use in the client.
3264 }
3265 }
Romain Guy8506ab42009-06-11 17:35:47 -07003266
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003267 static class W extends IWindow.Stub {
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07003268 private final WeakReference<ViewRoot> mViewRoot;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003269
Romain Guyfb8b7632010-08-23 21:05:08 -07003270 W(ViewRoot viewRoot) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003271 mViewRoot = new WeakReference<ViewRoot>(viewRoot);
3272 }
3273
Romain Guyfb8b7632010-08-23 21:05:08 -07003274 public void resized(int w, int h, Rect coveredInsets, Rect visibleInsets,
3275 boolean reportDraw, Configuration newConfig) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003276 final ViewRoot viewRoot = mViewRoot.get();
3277 if (viewRoot != null) {
Romain Guyfb8b7632010-08-23 21:05:08 -07003278 viewRoot.dispatchResized(w, h, coveredInsets, visibleInsets, reportDraw, newConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003279 }
3280 }
3281
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003282 public void dispatchAppVisibility(boolean visible) {
3283 final ViewRoot viewRoot = mViewRoot.get();
3284 if (viewRoot != null) {
3285 viewRoot.dispatchAppVisibility(visible);
3286 }
3287 }
3288
3289 public void dispatchGetNewSurface() {
3290 final ViewRoot viewRoot = mViewRoot.get();
3291 if (viewRoot != null) {
3292 viewRoot.dispatchGetNewSurface();
3293 }
3294 }
3295
3296 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
3297 final ViewRoot viewRoot = mViewRoot.get();
3298 if (viewRoot != null) {
3299 viewRoot.windowFocusChanged(hasFocus, inTouchMode);
3300 }
3301 }
3302
3303 private static int checkCallingPermission(String permission) {
3304 if (!Process.supportsProcesses()) {
3305 return PackageManager.PERMISSION_GRANTED;
3306 }
3307
3308 try {
3309 return ActivityManagerNative.getDefault().checkPermission(
3310 permission, Binder.getCallingPid(), Binder.getCallingUid());
3311 } catch (RemoteException e) {
3312 return PackageManager.PERMISSION_DENIED;
3313 }
3314 }
3315
3316 public void executeCommand(String command, String parameters, ParcelFileDescriptor out) {
3317 final ViewRoot viewRoot = mViewRoot.get();
3318 if (viewRoot != null) {
3319 final View view = viewRoot.mView;
3320 if (view != null) {
3321 if (checkCallingPermission(Manifest.permission.DUMP) !=
3322 PackageManager.PERMISSION_GRANTED) {
3323 throw new SecurityException("Insufficient permissions to invoke"
3324 + " executeCommand() from pid=" + Binder.getCallingPid()
3325 + ", uid=" + Binder.getCallingUid());
3326 }
3327
3328 OutputStream clientStream = null;
3329 try {
3330 clientStream = new ParcelFileDescriptor.AutoCloseOutputStream(out);
3331 ViewDebug.dispatchCommand(view, command, parameters, clientStream);
3332 } catch (IOException e) {
3333 e.printStackTrace();
3334 } finally {
3335 if (clientStream != null) {
3336 try {
3337 clientStream.close();
3338 } catch (IOException e) {
3339 e.printStackTrace();
3340 }
3341 }
3342 }
3343 }
3344 }
3345 }
Dianne Hackborn72c82ab2009-08-11 21:13:54 -07003346
Dianne Hackbornffa42482009-09-23 22:20:11 -07003347 public void closeSystemDialogs(String reason) {
3348 final ViewRoot viewRoot = mViewRoot.get();
3349 if (viewRoot != null) {
3350 viewRoot.dispatchCloseSystemDialogs(reason);
3351 }
3352 }
3353
Marco Nelissenbf6956b2009-11-09 15:21:13 -08003354 public void dispatchWallpaperOffsets(float x, float y, float xStep, float yStep,
3355 boolean sync) {
Dianne Hackborn19382ac2009-09-11 21:13:37 -07003356 if (sync) {
3357 try {
3358 sWindowSession.wallpaperOffsetsComplete(asBinder());
3359 } catch (RemoteException e) {
3360 }
3361 }
Dianne Hackborn72c82ab2009-08-11 21:13:54 -07003362 }
Dianne Hackborn75804932009-10-20 20:15:20 -07003363
3364 public void dispatchWallpaperCommand(String action, int x, int y,
3365 int z, Bundle extras, boolean sync) {
3366 if (sync) {
3367 try {
3368 sWindowSession.wallpaperCommandComplete(asBinder(), null);
3369 } catch (RemoteException e) {
3370 }
3371 }
3372 }
Christopher Tatea53146c2010-09-07 11:57:52 -07003373
3374 /* Drag/drop */
3375 public void dispatchDragEvent(DragEvent event) {
3376 final ViewRoot viewRoot = mViewRoot.get();
3377 if (viewRoot != null) {
3378 viewRoot.dispatchDragEvent(event);
3379 }
3380 }
Joe Onorato664644d2011-01-23 17:53:23 -08003381
3382 @Override
3383 public void dispatchSystemUiVisibilityChanged(int visibility) {
3384 final ViewRoot viewRoot = mViewRoot.get();
3385 if (viewRoot != null) {
3386 viewRoot.dispatchSystemUiVisibilityChanged(visibility);
3387 }
3388 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003389 }
3390
3391 /**
3392 * Maintains state information for a single trackball axis, generating
3393 * discrete (DPAD) movements based on raw trackball motion.
3394 */
3395 static final class TrackballAxis {
3396 /**
3397 * The maximum amount of acceleration we will apply.
3398 */
3399 static final float MAX_ACCELERATION = 20;
Romain Guy8506ab42009-06-11 17:35:47 -07003400
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003401 /**
3402 * The maximum amount of time (in milliseconds) between events in order
3403 * for us to consider the user to be doing fast trackball movements,
3404 * and thus apply an acceleration.
3405 */
3406 static final long FAST_MOVE_TIME = 150;
Romain Guy8506ab42009-06-11 17:35:47 -07003407
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003408 /**
3409 * Scaling factor to the time (in milliseconds) between events to how
3410 * much to multiple/divide the current acceleration. When movement
3411 * is < FAST_MOVE_TIME this multiplies the acceleration; when >
3412 * FAST_MOVE_TIME it divides it.
3413 */
3414 static final float ACCEL_MOVE_SCALING_FACTOR = (1.0f/40);
Romain Guy8506ab42009-06-11 17:35:47 -07003415
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003416 float position;
3417 float absPosition;
3418 float acceleration = 1;
3419 long lastMoveTime = 0;
3420 int step;
3421 int dir;
3422 int nonAccelMovement;
3423
3424 void reset(int _step) {
3425 position = 0;
3426 acceleration = 1;
3427 lastMoveTime = 0;
3428 step = _step;
3429 dir = 0;
3430 }
3431
3432 /**
3433 * Add trackball movement into the state. If the direction of movement
3434 * has been reversed, the state is reset before adding the
3435 * movement (so that you don't have to compensate for any previously
3436 * collected movement before see the result of the movement in the
3437 * new direction).
3438 *
3439 * @return Returns the absolute value of the amount of movement
3440 * collected so far.
3441 */
3442 float collect(float off, long time, String axis) {
3443 long normTime;
3444 if (off > 0) {
3445 normTime = (long)(off * FAST_MOVE_TIME);
3446 if (dir < 0) {
3447 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to positive!");
3448 position = 0;
3449 step = 0;
3450 acceleration = 1;
3451 lastMoveTime = 0;
3452 }
3453 dir = 1;
3454 } else if (off < 0) {
3455 normTime = (long)((-off) * FAST_MOVE_TIME);
3456 if (dir > 0) {
3457 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to negative!");
3458 position = 0;
3459 step = 0;
3460 acceleration = 1;
3461 lastMoveTime = 0;
3462 }
3463 dir = -1;
3464 } else {
3465 normTime = 0;
3466 }
Romain Guy8506ab42009-06-11 17:35:47 -07003467
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003468 // The number of milliseconds between each movement that is
3469 // considered "normal" and will not result in any acceleration
3470 // or deceleration, scaled by the offset we have here.
3471 if (normTime > 0) {
3472 long delta = time - lastMoveTime;
3473 lastMoveTime = time;
3474 float acc = acceleration;
3475 if (delta < normTime) {
3476 // The user is scrolling rapidly, so increase acceleration.
3477 float scale = (normTime-delta) * ACCEL_MOVE_SCALING_FACTOR;
3478 if (scale > 1) acc *= scale;
3479 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " accelerate: off="
3480 + off + " normTime=" + normTime + " delta=" + delta
3481 + " scale=" + scale + " acc=" + acc);
3482 acceleration = acc < MAX_ACCELERATION ? acc : MAX_ACCELERATION;
3483 } else {
3484 // The user is scrolling slowly, so decrease acceleration.
3485 float scale = (delta-normTime) * ACCEL_MOVE_SCALING_FACTOR;
3486 if (scale > 1) acc /= scale;
3487 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " deccelerate: off="
3488 + off + " normTime=" + normTime + " delta=" + delta
3489 + " scale=" + scale + " acc=" + acc);
3490 acceleration = acc > 1 ? acc : 1;
3491 }
3492 }
3493 position += off;
3494 return (absPosition = Math.abs(position));
3495 }
3496
3497 /**
3498 * Generate the number of discrete movement events appropriate for
3499 * the currently collected trackball movement.
3500 *
3501 * @param precision The minimum movement required to generate the
3502 * first discrete movement.
3503 *
3504 * @return Returns the number of discrete movements, either positive
3505 * or negative, or 0 if there is not enough trackball movement yet
3506 * for a discrete movement.
3507 */
3508 int generate(float precision) {
3509 int movement = 0;
3510 nonAccelMovement = 0;
3511 do {
3512 final int dir = position >= 0 ? 1 : -1;
3513 switch (step) {
3514 // If we are going to execute the first step, then we want
3515 // to do this as soon as possible instead of waiting for
3516 // a full movement, in order to make things look responsive.
3517 case 0:
3518 if (absPosition < precision) {
3519 return movement;
3520 }
3521 movement += dir;
3522 nonAccelMovement += dir;
3523 step = 1;
3524 break;
3525 // If we have generated the first movement, then we need
3526 // to wait for the second complete trackball motion before
3527 // generating the second discrete movement.
3528 case 1:
3529 if (absPosition < 2) {
3530 return movement;
3531 }
3532 movement += dir;
3533 nonAccelMovement += dir;
3534 position += dir > 0 ? -2 : 2;
3535 absPosition = Math.abs(position);
3536 step = 2;
3537 break;
3538 // After the first two, we generate discrete movements
3539 // consistently with the trackball, applying an acceleration
3540 // if the trackball is moving quickly. This is a simple
3541 // acceleration on top of what we already compute based
3542 // on how quickly the wheel is being turned, to apply
3543 // a longer increasing acceleration to continuous movement
3544 // in one direction.
3545 default:
3546 if (absPosition < 1) {
3547 return movement;
3548 }
3549 movement += dir;
3550 position += dir >= 0 ? -1 : 1;
3551 absPosition = Math.abs(position);
3552 float acc = acceleration;
3553 acc *= 1.1f;
3554 acceleration = acc < MAX_ACCELERATION ? acc : acceleration;
3555 break;
3556 }
3557 } while (true);
3558 }
3559 }
3560
3561 public static final class CalledFromWrongThreadException extends AndroidRuntimeException {
3562 public CalledFromWrongThreadException(String msg) {
3563 super(msg);
3564 }
3565 }
3566
3567 private SurfaceHolder mHolder = new SurfaceHolder() {
3568 // we only need a SurfaceHolder for opengl. it would be nice
3569 // to implement everything else though, especially the callback
3570 // support (opengl doesn't make use of it right now, but eventually
3571 // will).
3572 public Surface getSurface() {
3573 return mSurface;
3574 }
3575
3576 public boolean isCreating() {
3577 return false;
3578 }
3579
3580 public void addCallback(Callback callback) {
3581 }
3582
3583 public void removeCallback(Callback callback) {
3584 }
3585
3586 public void setFixedSize(int width, int height) {
3587 }
3588
3589 public void setSizeFromLayout() {
3590 }
3591
3592 public void setFormat(int format) {
3593 }
3594
3595 public void setType(int type) {
3596 }
3597
3598 public void setKeepScreenOn(boolean screenOn) {
3599 }
3600
3601 public Canvas lockCanvas() {
3602 return null;
3603 }
3604
3605 public Canvas lockCanvas(Rect dirty) {
3606 return null;
3607 }
3608
3609 public void unlockCanvasAndPost(Canvas canvas) {
3610 }
3611 public Rect getSurfaceFrame() {
3612 return null;
3613 }
3614 };
3615
3616 static RunQueue getRunQueue() {
3617 RunQueue rq = sRunQueues.get();
3618 if (rq != null) {
3619 return rq;
3620 }
3621 rq = new RunQueue();
3622 sRunQueues.set(rq);
3623 return rq;
3624 }
Romain Guy8506ab42009-06-11 17:35:47 -07003625
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003626 /**
3627 * @hide
3628 */
3629 static final class RunQueue {
3630 private final ArrayList<HandlerAction> mActions = new ArrayList<HandlerAction>();
3631
3632 void post(Runnable action) {
3633 postDelayed(action, 0);
3634 }
3635
3636 void postDelayed(Runnable action, long delayMillis) {
3637 HandlerAction handlerAction = new HandlerAction();
3638 handlerAction.action = action;
3639 handlerAction.delay = delayMillis;
3640
3641 synchronized (mActions) {
3642 mActions.add(handlerAction);
3643 }
3644 }
3645
3646 void removeCallbacks(Runnable action) {
3647 final HandlerAction handlerAction = new HandlerAction();
3648 handlerAction.action = action;
3649
3650 synchronized (mActions) {
3651 final ArrayList<HandlerAction> actions = mActions;
3652
3653 while (actions.remove(handlerAction)) {
3654 // Keep going
3655 }
3656 }
3657 }
3658
3659 void executeActions(Handler handler) {
3660 synchronized (mActions) {
3661 final ArrayList<HandlerAction> actions = mActions;
3662 final int count = actions.size();
3663
3664 for (int i = 0; i < count; i++) {
3665 final HandlerAction handlerAction = actions.get(i);
3666 handler.postDelayed(handlerAction.action, handlerAction.delay);
3667 }
3668
Romain Guy15df6702009-08-17 20:17:30 -07003669 actions.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003670 }
3671 }
3672
3673 private static class HandlerAction {
3674 Runnable action;
3675 long delay;
3676
3677 @Override
3678 public boolean equals(Object o) {
3679 if (this == o) return true;
3680 if (o == null || getClass() != o.getClass()) return false;
3681
3682 HandlerAction that = (HandlerAction) o;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003683 return !(action != null ? !action.equals(that.action) : that.action != null);
3684
3685 }
3686
3687 @Override
3688 public int hashCode() {
3689 int result = action != null ? action.hashCode() : 0;
3690 result = 31 * result + (int) (delay ^ (delay >>> 32));
3691 return result;
3692 }
3693 }
3694 }
3695
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003696 private static native void nativeShowFPS(Canvas canvas, int durationMillis);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003697}