blob: a34fe8797b62b3078637319299b9c19600be2d66 [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 Tate407b4e92010-11-30 17:14:08 -0800231 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
Romain Guy529b60a2010-08-03 18:05:47 -0700348 enableHardwareAcceleration(attrs);
Romain Guye4d01122010-06-16 18:44:05 -0700349
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700350 if (view instanceof RootViewSurfaceTaker) {
351 mSurfaceHolderCallback =
352 ((RootViewSurfaceTaker)view).willYouTakeTheSurface();
353 if (mSurfaceHolderCallback != null) {
354 mSurfaceHolder = new TakenSurfaceHolder();
Dianne Hackborn289b9b62010-07-09 11:44:11 -0700355 mSurfaceHolder.setFormat(PixelFormat.UNKNOWN);
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700356 }
357 }
Mitsuru Oshima38ed7d772009-07-21 14:39:34 -0700358 Resources resources = mView.getContext().getResources();
359 CompatibilityInfo compatibilityInfo = resources.getCompatibilityInfo();
Mitsuru Oshima589cebe2009-07-22 20:38:58 -0700360 mTranslator = compatibilityInfo.getTranslator();
Mitsuru Oshima38ed7d772009-07-21 14:39:34 -0700361
362 if (mTranslator != null || !compatibilityInfo.supportsScreen()) {
Mitsuru Oshima240f8a72009-07-22 20:39:14 -0700363 mSurface.setCompatibleDisplayMetrics(resources.getDisplayMetrics(),
364 mTranslator);
Mitsuru Oshima38ed7d772009-07-21 14:39:34 -0700365 }
366
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -0700367 boolean restore = false;
Romain Guy35b38ce2009-10-07 13:38:55 -0700368 if (mTranslator != null) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -0700369 restore = true;
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700370 attrs.backup();
371 mTranslator.translateWindowLayout(attrs);
Mitsuru Oshima3d914922009-05-13 22:29:15 -0700372 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700373 if (DEBUG_LAYOUT) Log.d(TAG, "WindowLayout in setView:" + attrs);
374
Mitsuru Oshima1ecf5d22009-07-06 17:20:38 -0700375 if (!compatibilityInfo.supportsScreen()) {
376 attrs.flags |= WindowManager.LayoutParams.FLAG_COMPATIBLE_WINDOW;
377 }
378
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800379 mSoftInputMode = attrs.softInputMode;
380 mWindowAttributesChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800381 mAttachInfo.mRootView = view;
Romain Guy35b38ce2009-10-07 13:38:55 -0700382 mAttachInfo.mScalingRequired = mTranslator != null;
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700383 mAttachInfo.mApplicationScale =
384 mTranslator == null ? 1.0f : mTranslator.applicationScale;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800385 if (panelParentView != null) {
386 mAttachInfo.mPanelParentWindowToken
387 = panelParentView.getApplicationWindowToken();
388 }
389 mAdded = true;
390 int res; /* = WindowManagerImpl.ADD_OKAY; */
Romain Guy8506ab42009-06-11 17:35:47 -0700391
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800392 // Schedule the first layout -before- adding to the window
393 // manager, to make sure we do the relayout before receiving
394 // any other events from the system.
395 requestLayout();
Jeff Brown46b9ac02010-04-22 18:58:52 -0700396 mInputChannel = new InputChannel();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800397 try {
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700398 res = sWindowSession.add(mWindow, mWindowAttributes,
Jeff Brown46b9ac02010-04-22 18:58:52 -0700399 getHostVisibility(), mAttachInfo.mContentInsets,
400 mInputChannel);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800401 } catch (RemoteException e) {
402 mAdded = false;
403 mView = null;
404 mAttachInfo.mRootView = null;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700405 mInputChannel = null;
Joe Onorato86f67862010-11-05 18:57:34 -0700406 mFallbackEventHandler.setView(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800407 unscheduleTraversals();
408 throw new RuntimeException("Adding window failed", e);
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700409 } finally {
410 if (restore) {
411 attrs.restore();
412 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800413 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700414
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700415 if (mTranslator != null) {
416 mTranslator.translateRectInScreenToAppWindow(mAttachInfo.mContentInsets);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700417 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800418 mPendingContentInsets.set(mAttachInfo.mContentInsets);
419 mPendingVisibleInsets.set(0, 0, 0, 0);
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800420 if (DEBUG_LAYOUT) Log.v(TAG, "Added window " + mWindow);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800421 if (res < WindowManagerImpl.ADD_OKAY) {
422 mView = null;
423 mAttachInfo.mRootView = null;
424 mAdded = false;
Joe Onorato86f67862010-11-05 18:57:34 -0700425 mFallbackEventHandler.setView(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800426 unscheduleTraversals();
427 switch (res) {
428 case WindowManagerImpl.ADD_BAD_APP_TOKEN:
429 case WindowManagerImpl.ADD_BAD_SUBWINDOW_TOKEN:
430 throw new WindowManagerImpl.BadTokenException(
431 "Unable to add window -- token " + attrs.token
432 + " is not valid; is your activity running?");
433 case WindowManagerImpl.ADD_NOT_APP_TOKEN:
434 throw new WindowManagerImpl.BadTokenException(
435 "Unable to add window -- token " + attrs.token
436 + " is not for an application");
437 case WindowManagerImpl.ADD_APP_EXITING:
438 throw new WindowManagerImpl.BadTokenException(
439 "Unable to add window -- app for token " + attrs.token
440 + " is exiting");
441 case WindowManagerImpl.ADD_DUPLICATE_ADD:
442 throw new WindowManagerImpl.BadTokenException(
443 "Unable to add window -- window " + mWindow
444 + " has already been added");
445 case WindowManagerImpl.ADD_STARTING_NOT_NEEDED:
446 // Silently ignore -- we would have just removed it
447 // right away, anyway.
448 return;
449 case WindowManagerImpl.ADD_MULTIPLE_SINGLETON:
450 throw new WindowManagerImpl.BadTokenException(
451 "Unable to add window " + mWindow +
452 " -- another window of this type already exists");
453 case WindowManagerImpl.ADD_PERMISSION_DENIED:
454 throw new WindowManagerImpl.BadTokenException(
455 "Unable to add window " + mWindow +
456 " -- permission denied for this window type");
457 }
458 throw new RuntimeException(
459 "Unable to add window -- unknown error code " + res);
460 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700461
Jeff Brown00fa7bd2010-07-02 15:37:36 -0700462 if (view instanceof RootViewSurfaceTaker) {
463 mInputQueueCallback =
464 ((RootViewSurfaceTaker)view).willYouTakeTheInputQueue();
465 }
466 if (mInputQueueCallback != null) {
467 mInputQueue = new InputQueue(mInputChannel);
468 mInputQueueCallback.onInputQueueCreated(mInputQueue);
469 } else {
470 InputQueue.registerInputChannel(mInputChannel, mInputHandler,
471 Looper.myQueue());
Jeff Brown46b9ac02010-04-22 18:58:52 -0700472 }
473
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800474 view.assignParent(this);
475 mAddedTouchMode = (res&WindowManagerImpl.ADD_FLAG_IN_TOUCH_MODE) != 0;
476 mAppVisible = (res&WindowManagerImpl.ADD_FLAG_APP_VISIBLE) != 0;
477 }
478 }
479 }
480
Romain Guy529b60a2010-08-03 18:05:47 -0700481 private void enableHardwareAcceleration(WindowManager.LayoutParams attrs) {
Dianne Hackborn7eec10e2010-11-12 18:03:47 -0800482 mAttachInfo.mHardwareAccelerated = false;
483 mAttachInfo.mHardwareAccelerationRequested = false;
484
485 // Try to enable hardware acceleration if requested
486 if (attrs != null &&
487 (attrs.flags & WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED) != 0) {
488 // Only enable hardware acceleration if we are not in the system process
489 // The window manager creates ViewRoots to display animated preview windows
490 // of launching apps and we don't want those to be hardware accelerated
491 if (!HardwareRenderer.sRendererDisabled) {
Romain Guye4d01122010-06-16 18:44:05 -0700492 final boolean translucent = attrs.format != PixelFormat.OPAQUE;
Romain Guyb051e892010-09-28 19:09:36 -0700493 if (mAttachInfo.mHardwareRenderer != null) {
494 mAttachInfo.mHardwareRenderer.destroy(true);
Romain Guy4caa4ed2010-08-25 14:46:24 -0700495 }
Romain Guyb051e892010-09-28 19:09:36 -0700496 mAttachInfo.mHardwareRenderer = HardwareRenderer.createGlRenderer(2, translucent);
Dianne Hackborn7eec10e2010-11-12 18:03:47 -0800497 mAttachInfo.mHardwareAccelerated = mAttachInfo.mHardwareAccelerationRequested
498 = mAttachInfo.mHardwareRenderer != null;
499 } else if (HardwareRenderer.isAvailable()) {
500 mAttachInfo.mHardwareAccelerationRequested = true;
Romain Guye4d01122010-06-16 18:44:05 -0700501 }
502 }
503 }
504
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800505 public View getView() {
506 return mView;
507 }
508
509 final WindowLeaked getLocation() {
510 return mLocation;
511 }
512
513 void setLayoutParams(WindowManager.LayoutParams attrs, boolean newView) {
514 synchronized (this) {
The Android Open Source Project10592532009-03-18 17:39:46 -0700515 int oldSoftInputMode = mWindowAttributes.softInputMode;
Mitsuru Oshima5a2b91d2009-07-16 16:30:02 -0700516 // preserve compatible window flag if exists.
517 int compatibleWindowFlag =
518 mWindowAttributes.flags & WindowManager.LayoutParams.FLAG_COMPATIBLE_WINDOW;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800519 mWindowAttributes.copyFrom(attrs);
Mitsuru Oshima5a2b91d2009-07-16 16:30:02 -0700520 mWindowAttributes.flags |= compatibleWindowFlag;
521
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800522 if (newView) {
523 mSoftInputMode = attrs.softInputMode;
524 requestLayout();
525 }
The Android Open Source Project10592532009-03-18 17:39:46 -0700526 // Don't lose the mode we last auto-computed.
527 if ((attrs.softInputMode&WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST)
528 == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED) {
529 mWindowAttributes.softInputMode = (mWindowAttributes.softInputMode
530 & ~WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST)
531 | (oldSoftInputMode
532 & WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST);
533 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800534 mWindowAttributesChanged = true;
535 scheduleTraversals();
536 }
537 }
538
539 void handleAppVisibility(boolean visible) {
540 if (mAppVisible != visible) {
541 mAppVisible = visible;
542 scheduleTraversals();
543 }
544 }
545
546 void handleGetNewSurface() {
547 mNewSurfaceNeeded = true;
548 mFullRedrawNeeded = true;
549 scheduleTraversals();
550 }
551
552 /**
553 * {@inheritDoc}
554 */
555 public void requestLayout() {
556 checkThread();
557 mLayoutRequested = true;
558 scheduleTraversals();
559 }
560
561 /**
562 * {@inheritDoc}
563 */
564 public boolean isLayoutRequested() {
565 return mLayoutRequested;
566 }
567
568 public void invalidateChild(View child, Rect dirty) {
569 checkThread();
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700570 if (DEBUG_DRAW) Log.v(TAG, "Invalidate child: " + dirty);
Chet Haase70d4ba12010-10-06 09:46:45 -0700571 if (dirty == null) {
572 // Fast invalidation for GL-enabled applications; GL must redraw everything
573 invalidate();
574 return;
575 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700576 if (mCurScrollY != 0 || mTranslator != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800577 mTempRect.set(dirty);
Romain Guy1e095972009-07-07 11:22:45 -0700578 dirty = mTempRect;
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700579 if (mCurScrollY != 0) {
Romain Guy1e095972009-07-07 11:22:45 -0700580 dirty.offset(0, -mCurScrollY);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700581 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700582 if (mTranslator != null) {
Romain Guy1e095972009-07-07 11:22:45 -0700583 mTranslator.translateRectInAppWindowToScreen(dirty);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700584 }
Romain Guy1e095972009-07-07 11:22:45 -0700585 if (mAttachInfo.mScalingRequired) {
586 dirty.inset(-1, -1);
587 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800588 }
Romain Guy7d695942010-12-01 17:22:29 -0800589 if (!mDirty.isEmpty()) {
590 mAttachInfo.mIgnoreDirtyState = true;
591 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800592 mDirty.union(dirty);
593 if (!mWillDrawSoon) {
594 scheduleTraversals();
595 }
596 }
Romain Guy0d9275e2010-10-26 14:22:30 -0700597
598 void invalidate() {
599 mDirty.set(0, 0, mWidth, mHeight);
600 scheduleTraversals();
601 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800602
603 public ViewParent getParent() {
604 return null;
605 }
606
607 public ViewParent invalidateChildInParent(final int[] location, final Rect dirty) {
608 invalidateChild(null, dirty);
609 return null;
610 }
611
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700612 public boolean getChildVisibleRect(View child, Rect r, android.graphics.Point offset) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800613 if (child != mView) {
614 throw new RuntimeException("child is not mine, honest!");
615 }
616 // Note: don't apply scroll offset, because we want to know its
617 // visibility in the virtual canvas being given to the view hierarchy.
618 return r.intersect(0, 0, mWidth, mHeight);
619 }
620
621 public void bringChildToFront(View child) {
622 }
623
624 public void scheduleTraversals() {
625 if (!mTraversalScheduled) {
626 mTraversalScheduled = true;
627 sendEmptyMessage(DO_TRAVERSAL);
628 }
629 }
630
631 public void unscheduleTraversals() {
632 if (mTraversalScheduled) {
633 mTraversalScheduled = false;
634 removeMessages(DO_TRAVERSAL);
635 }
636 }
637
638 int getHostVisibility() {
639 return mAppVisible ? mView.getVisibility() : View.GONE;
640 }
Romain Guy8506ab42009-06-11 17:35:47 -0700641
Dianne Hackborn0f761d62010-11-30 22:06:10 -0800642 void disposeResizeBitmap() {
643 if (mResizeBitmap != null) {
644 mResizeBitmap.recycle();
645 mResizeBitmap = null;
646 }
647 }
648
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800649 private void performTraversals() {
650 // cache mView since it is used so much below...
651 final View host = mView;
652
653 if (DBG) {
654 System.out.println("======================================");
655 System.out.println("performTraversals");
656 host.debug();
657 }
658
659 if (host == null || !mAdded)
660 return;
661
662 mTraversalScheduled = false;
663 mWillDrawSoon = true;
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800664 boolean windowSizeMayChange = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800665 boolean fullRedrawNeeded = mFullRedrawNeeded;
666 boolean newSurface = false;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700667 boolean surfaceChanged = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800668 WindowManager.LayoutParams lp = mWindowAttributes;
669
670 int desiredWindowWidth;
671 int desiredWindowHeight;
672 int childWidthMeasureSpec;
673 int childHeightMeasureSpec;
674
675 final View.AttachInfo attachInfo = mAttachInfo;
676
677 final int viewVisibility = getHostVisibility();
678 boolean viewVisibilityChanged = mViewVisibility != viewVisibility
679 || mNewSurfaceNeeded;
680
681 WindowManager.LayoutParams params = null;
682 if (mWindowAttributesChanged) {
683 mWindowAttributesChanged = false;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700684 surfaceChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800685 params = lp;
686 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700687 Rect frame = mWinFrame;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800688 if (mFirst) {
689 fullRedrawNeeded = true;
690 mLayoutRequested = true;
691
Romain Guy8506ab42009-06-11 17:35:47 -0700692 DisplayMetrics packageMetrics =
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700693 mView.getContext().getResources().getDisplayMetrics();
694 desiredWindowWidth = packageMetrics.widthPixels;
695 desiredWindowHeight = packageMetrics.heightPixels;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800696
697 // For the very first time, tell the view hierarchy that it
698 // is attached to the window. Note that at this point the surface
699 // object is not initialized to its backing store, but soon it
700 // will be (assuming the window is visible).
701 attachInfo.mSurface = mSurface;
Adam Powell26153a32010-11-08 15:22:27 -0800702 attachInfo.mUse32BitDrawingCache = PixelFormat.formatHasAlpha(lp.format) ||
703 lp.format == PixelFormat.RGBX_8888;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800704 attachInfo.mHasWindowFocus = false;
705 attachInfo.mWindowVisibility = viewVisibility;
706 attachInfo.mRecomputeGlobalAttributes = false;
707 attachInfo.mKeepScreenOn = false;
708 viewVisibilityChanged = false;
Dianne Hackborn694f79b2010-03-17 19:44:59 -0700709 mLastConfiguration.setTo(host.getResources().getConfiguration());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800710 host.dispatchAttachedToWindow(attachInfo, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800711 //Log.i(TAG, "Screen on initialized: " + attachInfo.mKeepScreenOn);
svetoslavganov75986cf2009-05-14 22:28:01 -0700712
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800713 } else {
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700714 desiredWindowWidth = frame.width();
715 desiredWindowHeight = frame.height();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800716 if (desiredWindowWidth != mWidth || desiredWindowHeight != mHeight) {
Jeff Brownc5ed5912010-07-14 18:48:53 -0700717 if (DEBUG_ORIENTATION) Log.v(TAG,
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700718 "View " + host + " resized to: " + frame);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800719 fullRedrawNeeded = true;
720 mLayoutRequested = true;
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800721 windowSizeMayChange = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800722 }
723 }
724
725 if (viewVisibilityChanged) {
726 attachInfo.mWindowVisibility = viewVisibility;
727 host.dispatchWindowVisibilityChanged(viewVisibility);
728 if (viewVisibility != View.VISIBLE || mNewSurfaceNeeded) {
Romain Guyb051e892010-09-28 19:09:36 -0700729 if (mAttachInfo.mHardwareRenderer != null) {
730 mAttachInfo.mHardwareRenderer.destroy(false);
Romain Guy4caa4ed2010-08-25 14:46:24 -0700731 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800732 }
733 if (viewVisibility == View.GONE) {
734 // After making a window gone, we will count it as being
735 // shown for the first time the next time it gets focus.
736 mHasHadWindowFocus = false;
737 }
738 }
739
740 boolean insetsChanged = false;
Romain Guy8506ab42009-06-11 17:35:47 -0700741
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800742 if (mLayoutRequested) {
Romain Guy15df6702009-08-17 20:17:30 -0700743 // Execute enqueued actions on every layout in case a view that was detached
744 // enqueued an action after being detached
745 getRunQueue().executeActions(attachInfo.mHandler);
746
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800747 final Resources res = mView.getContext().getResources();
748
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800749 if (mFirst) {
750 host.fitSystemWindows(mAttachInfo.mContentInsets);
751 // make sure touch mode code executes by setting cached value
752 // to opposite of the added touch mode.
753 mAttachInfo.mInTouchMode = !mAddedTouchMode;
Romain Guy2d4cff62010-04-09 15:39:00 -0700754 ensureTouchModeLocally(mAddedTouchMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800755 } else {
756 if (!mAttachInfo.mContentInsets.equals(mPendingContentInsets)) {
Dianne Hackborn0f761d62010-11-30 22:06:10 -0800757 if (mWidth > 0 && mHeight > 0 &&
758 mSurface != null && mSurface.isValid() &&
759 mAttachInfo.mHardwareRenderer != null &&
760 mAttachInfo.mHardwareRenderer.isEnabled() &&
761 lp != null && !PixelFormat.formatHasAlpha(lp.format)) {
762
763 disposeResizeBitmap();
764
765 boolean completed = false;
766 try {
767 mResizeBitmap = Bitmap.createBitmap(mWidth, mHeight,
768 Bitmap.Config.ARGB_8888);
769 mResizeBitmap.setHasAlpha(false);
770 Canvas canvas = new Canvas(mResizeBitmap);
771 int yoff;
772 final boolean scrolling = mScroller != null
773 && mScroller.computeScrollOffset();
774 if (scrolling) {
775 yoff = mScroller.getCurrY();
776 mScroller.abortAnimation();
777 } else {
778 yoff = mScrollY;
779 }
780 canvas.translate(0, -yoff);
781 if (mTranslator != null) {
782 mTranslator.translateCanvas(canvas);
783 }
784 canvas.setScreenDensity(mAttachInfo.mScalingRequired
785 ? DisplayMetrics.DENSITY_DEVICE : 0);
786 mView.draw(canvas);
787 mResizeBitmapStartTime = SystemClock.uptimeMillis();
788 mResizeBitmapDuration = mView.getResources().getInteger(
789 com.android.internal.R.integer.config_mediumAnimTime);
790 completed = true;
791 } catch (OutOfMemoryError e) {
792 Log.w(TAG, "Not enough memory for content change anim buffer", e);
793 } finally {
794 if (!completed) {
795 mResizeBitmap = null;
796 }
797 }
798 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800799 mAttachInfo.mContentInsets.set(mPendingContentInsets);
800 host.fitSystemWindows(mAttachInfo.mContentInsets);
801 insetsChanged = true;
802 if (DEBUG_LAYOUT) Log.v(TAG, "Content insets changing to: "
803 + mAttachInfo.mContentInsets);
804 }
805 if (!mAttachInfo.mVisibleInsets.equals(mPendingVisibleInsets)) {
806 mAttachInfo.mVisibleInsets.set(mPendingVisibleInsets);
807 if (DEBUG_LAYOUT) Log.v(TAG, "Visible insets changing to: "
808 + mAttachInfo.mVisibleInsets);
809 }
810 if (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT
811 || lp.height == ViewGroup.LayoutParams.WRAP_CONTENT) {
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800812 windowSizeMayChange = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800813
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800814 DisplayMetrics packageMetrics = res.getDisplayMetrics();
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700815 desiredWindowWidth = packageMetrics.widthPixels;
816 desiredWindowHeight = packageMetrics.heightPixels;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800817 }
818 }
819
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800820 // Ask host how big it wants to be
Jeff Brownc5ed5912010-07-14 18:48:53 -0700821 if (DEBUG_ORIENTATION || DEBUG_LAYOUT) Log.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800822 "Measuring " + host + " in display " + desiredWindowWidth
823 + "x" + desiredWindowHeight + "...");
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800824
825 boolean goodMeasure = false;
826 if (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT
827 || lp.height == ViewGroup.LayoutParams.WRAP_CONTENT) {
828 // On large screens, we don't want to allow dialogs to just
829 // stretch to fill the entire width of the screen to display
830 // one line of text. First try doing the layout at a smaller
831 // size to see if it will fit.
832 final DisplayMetrics packageMetrics = res.getDisplayMetrics();
833 res.getValue(com.android.internal.R.dimen.config_prefDialogWidth, mTmpValue, true);
834 int baseSize = 0;
835 if (mTmpValue.type == TypedValue.TYPE_DIMENSION) {
836 baseSize = (int)mTmpValue.getDimension(packageMetrics);
837 }
838 if (DEBUG_DIALOG) Log.v(TAG, "Window " + mView + ": baseSize=" + baseSize);
Dianne Hackborn7d3a5bc2010-11-29 22:52:12 -0800839 if (baseSize != 0 && desiredWindowWidth > baseSize) {
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800840 childWidthMeasureSpec = getRootMeasureSpec(baseSize, lp.width);
841 childHeightMeasureSpec = getRootMeasureSpec(desiredWindowHeight, lp.height);
842 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
843 if (DEBUG_DIALOG) Log.v(TAG, "Window " + mView + ": measured ("
Dianne Hackborn189ee182010-12-02 21:48:53 -0800844 + host.getMeasuredWidth() + "," + host.getMeasuredHeight() + ")");
845 if ((host.getMeasuredWidthAndState()&View.MEASURED_STATE_TOO_SMALL) == 0) {
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800846 goodMeasure = true;
847 } else {
848 // Didn't fit in that size... try expanding a bit.
849 baseSize = (baseSize+desiredWindowWidth)/2;
850 if (DEBUG_DIALOG) Log.v(TAG, "Window " + mView + ": next baseSize="
851 + baseSize);
Dianne Hackborn189ee182010-12-02 21:48:53 -0800852 childWidthMeasureSpec = getRootMeasureSpec(baseSize, lp.width);
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800853 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
854 if (DEBUG_DIALOG) Log.v(TAG, "Window " + mView + ": measured ("
Dianne Hackborn189ee182010-12-02 21:48:53 -0800855 + host.getMeasuredWidth() + "," + host.getMeasuredHeight() + ")");
856 if ((host.getMeasuredWidthAndState()&View.MEASURED_STATE_TOO_SMALL) == 0) {
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800857 if (DEBUG_DIALOG) Log.v(TAG, "Good!");
858 goodMeasure = true;
859 }
860 }
861 }
862 }
863
864 if (!goodMeasure) {
865 childWidthMeasureSpec = getRootMeasureSpec(desiredWindowWidth, lp.width);
866 childHeightMeasureSpec = getRootMeasureSpec(desiredWindowHeight, lp.height);
867 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
868 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800869
870 if (DBG) {
871 System.out.println("======================================");
872 System.out.println("performTraversals -- after measure");
873 host.debug();
874 }
875 }
876
877 if (attachInfo.mRecomputeGlobalAttributes) {
878 //Log.i(TAG, "Computing screen on!");
879 attachInfo.mRecomputeGlobalAttributes = false;
880 boolean oldVal = attachInfo.mKeepScreenOn;
881 attachInfo.mKeepScreenOn = false;
882 host.dispatchCollectViewAttributes(0);
883 if (attachInfo.mKeepScreenOn != oldVal) {
884 params = lp;
885 //Log.i(TAG, "Keep screen on changed: " + attachInfo.mKeepScreenOn);
886 }
887 }
888
889 if (mFirst || attachInfo.mViewVisibilityChanged) {
890 attachInfo.mViewVisibilityChanged = false;
891 int resizeMode = mSoftInputMode &
892 WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST;
893 // If we are in auto resize mode, then we need to determine
894 // what mode to use now.
895 if (resizeMode == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED) {
896 final int N = attachInfo.mScrollContainers.size();
897 for (int i=0; i<N; i++) {
898 if (attachInfo.mScrollContainers.get(i).isShown()) {
899 resizeMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE;
900 }
901 }
902 if (resizeMode == 0) {
903 resizeMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN;
904 }
905 if ((lp.softInputMode &
906 WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) != resizeMode) {
907 lp.softInputMode = (lp.softInputMode &
908 ~WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) |
909 resizeMode;
910 params = lp;
911 }
912 }
913 }
Romain Guy8506ab42009-06-11 17:35:47 -0700914
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800915 if (params != null && (host.mPrivateFlags & View.REQUEST_TRANSPARENT_REGIONS) != 0) {
916 if (!PixelFormat.formatHasAlpha(params.format)) {
917 params.format = PixelFormat.TRANSLUCENT;
918 }
919 }
920
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800921 boolean windowShouldResize = mLayoutRequested && windowSizeMayChange
Dianne Hackborn189ee182010-12-02 21:48:53 -0800922 && ((mWidth != host.getMeasuredWidth() || mHeight != host.getMeasuredHeight())
Romain Guy2e4f4262010-04-06 11:07:52 -0700923 || (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT &&
924 frame.width() < desiredWindowWidth && frame.width() != mWidth)
925 || (lp.height == ViewGroup.LayoutParams.WRAP_CONTENT &&
926 frame.height() < desiredWindowHeight && frame.height() != mHeight));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800927
928 final boolean computesInternalInsets =
929 attachInfo.mTreeObserver.hasComputeInternalInsetsListeners();
Romain Guy812ccbe2010-06-01 14:07:24 -0700930
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800931 boolean insetsPending = false;
932 int relayoutResult = 0;
Romain Guy812ccbe2010-06-01 14:07:24 -0700933
934 if (mFirst || windowShouldResize || insetsChanged ||
935 viewVisibilityChanged || params != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800936
937 if (viewVisibility == View.VISIBLE) {
938 // If this window is giving internal insets to the window
939 // manager, and it is being added or changing its visibility,
940 // then we want to first give the window manager "fake"
941 // insets to cause it to effectively ignore the content of
942 // the window during layout. This avoids it briefly causing
943 // other windows to resize/move based on the raw frame of the
944 // window, waiting until we can finish laying out this window
945 // and get back to the window manager with the ultimately
946 // computed insets.
Romain Guy812ccbe2010-06-01 14:07:24 -0700947 insetsPending = computesInternalInsets && (mFirst || viewVisibilityChanged);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800948 }
949
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700950 if (mSurfaceHolder != null) {
951 mSurfaceHolder.mSurfaceLock.lock();
952 mDrawingAllowed = true;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700953 }
Romain Guy812ccbe2010-06-01 14:07:24 -0700954
Romain Guyc361da82010-10-25 15:29:10 -0700955 boolean hwInitialized = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800956 boolean contentInsetsChanged = false;
Romain Guy13922e02009-05-12 17:56:14 -0700957 boolean visibleInsetsChanged;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700958 boolean hadSurface = mSurface.isValid();
Romain Guy812ccbe2010-06-01 14:07:24 -0700959
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800960 try {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800961 int fl = 0;
962 if (params != null) {
963 fl = params.flags;
964 if (attachInfo.mKeepScreenOn) {
965 params.flags |= WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
966 }
967 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700968 if (DEBUG_LAYOUT) {
Dianne Hackborn189ee182010-12-02 21:48:53 -0800969 Log.i(TAG, "host=w:" + host.getMeasuredWidth() + ", h:" +
970 host.getMeasuredHeight() + ", params=" + params);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700971 }
972 relayoutResult = relayoutWindow(params, viewVisibility, insetsPending);
973
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800974 if (params != null) {
975 params.flags = fl;
976 }
977
978 if (DEBUG_LAYOUT) Log.v(TAG, "relayout: frame=" + frame.toShortString()
979 + " content=" + mPendingContentInsets.toShortString()
980 + " visible=" + mPendingVisibleInsets.toShortString()
981 + " surface=" + mSurface);
Romain Guy8506ab42009-06-11 17:35:47 -0700982
Dianne Hackborn694f79b2010-03-17 19:44:59 -0700983 if (mPendingConfiguration.seq != 0) {
984 if (DEBUG_CONFIGURATION) Log.v(TAG, "Visible with new config: "
985 + mPendingConfiguration);
986 updateConfiguration(mPendingConfiguration, !mFirst);
987 mPendingConfiguration.seq = 0;
988 }
989
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800990 contentInsetsChanged = !mPendingContentInsets.equals(
991 mAttachInfo.mContentInsets);
992 visibleInsetsChanged = !mPendingVisibleInsets.equals(
993 mAttachInfo.mVisibleInsets);
994 if (contentInsetsChanged) {
995 mAttachInfo.mContentInsets.set(mPendingContentInsets);
996 host.fitSystemWindows(mAttachInfo.mContentInsets);
997 if (DEBUG_LAYOUT) Log.v(TAG, "Content insets changing to: "
998 + mAttachInfo.mContentInsets);
999 }
1000 if (visibleInsetsChanged) {
1001 mAttachInfo.mVisibleInsets.set(mPendingVisibleInsets);
1002 if (DEBUG_LAYOUT) Log.v(TAG, "Visible insets changing to: "
1003 + mAttachInfo.mVisibleInsets);
1004 }
1005
1006 if (!hadSurface) {
1007 if (mSurface.isValid()) {
1008 // If we are creating a new surface, then we need to
1009 // completely redraw it. Also, when we get to the
1010 // point of drawing it we will hold off and schedule
1011 // a new traversal instead. This is so we can tell the
1012 // window manager about all of the windows being displayed
1013 // before actually drawing them, so it can display then
1014 // all at once.
1015 newSurface = true;
1016 fullRedrawNeeded = true;
Jack Palevich61a6e682009-10-09 17:37:50 -07001017 mPreviousTransparentRegion.setEmpty();
Romain Guy8506ab42009-06-11 17:35:47 -07001018
Romain Guyb051e892010-09-28 19:09:36 -07001019 if (mAttachInfo.mHardwareRenderer != null) {
Romain Guyc361da82010-10-25 15:29:10 -07001020 hwInitialized = mAttachInfo.mHardwareRenderer.initialize(mHolder);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001021 }
1022 }
1023 } else if (!mSurface.isValid()) {
1024 // If the surface has been removed, then reset the scroll
1025 // positions.
1026 mLastScrolledFocus = null;
1027 mScrollY = mCurScrollY = 0;
1028 if (mScroller != null) {
1029 mScroller.abortAnimation();
1030 }
Dianne Hackborn0f761d62010-11-30 22:06:10 -08001031 disposeResizeBitmap();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001032 }
1033 } catch (RemoteException e) {
1034 }
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001035
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001036 if (DEBUG_ORIENTATION) Log.v(
Jeff Brownc5ed5912010-07-14 18:48:53 -07001037 TAG, "Relayout returned: frame=" + frame + ", surface=" + mSurface);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001038
1039 attachInfo.mWindowLeft = frame.left;
1040 attachInfo.mWindowTop = frame.top;
1041
1042 // !!FIXME!! This next section handles the case where we did not get the
1043 // window size we asked for. We should avoid this by getting a maximum size from
1044 // the window session beforehand.
1045 mWidth = frame.width();
1046 mHeight = frame.height();
1047
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001048 if (mSurfaceHolder != null) {
1049 // The app owns the surface; tell it about what is going on.
1050 if (mSurface.isValid()) {
1051 // XXX .copyFrom() doesn't work!
1052 //mSurfaceHolder.mSurface.copyFrom(mSurface);
1053 mSurfaceHolder.mSurface = mSurface;
1054 }
1055 mSurfaceHolder.mSurfaceLock.unlock();
1056 if (mSurface.isValid()) {
1057 if (!hadSurface) {
1058 mSurfaceHolder.ungetCallbacks();
1059
1060 mIsCreating = true;
1061 mSurfaceHolderCallback.surfaceCreated(mSurfaceHolder);
1062 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
1063 if (callbacks != null) {
1064 for (SurfaceHolder.Callback c : callbacks) {
1065 c.surfaceCreated(mSurfaceHolder);
1066 }
1067 }
1068 surfaceChanged = true;
Romain Guyc361da82010-10-25 15:29:10 -07001069
1070 if (mAttachInfo.mHardwareRenderer != null) {
1071 // This will bail out early if already initialized
1072 mAttachInfo.mHardwareRenderer.initialize(mHolder);
1073 }
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001074 }
1075 if (surfaceChanged) {
1076 mSurfaceHolderCallback.surfaceChanged(mSurfaceHolder,
1077 lp.format, mWidth, mHeight);
1078 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
1079 if (callbacks != null) {
1080 for (SurfaceHolder.Callback c : callbacks) {
1081 c.surfaceChanged(mSurfaceHolder, lp.format,
1082 mWidth, mHeight);
1083 }
1084 }
1085 }
1086 mIsCreating = false;
1087 } else if (hadSurface) {
1088 mSurfaceHolder.ungetCallbacks();
1089 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
1090 mSurfaceHolderCallback.surfaceDestroyed(mSurfaceHolder);
1091 if (callbacks != null) {
1092 for (SurfaceHolder.Callback c : callbacks) {
1093 c.surfaceDestroyed(mSurfaceHolder);
1094 }
1095 }
1096 mSurfaceHolder.mSurfaceLock.lock();
1097 // Make surface invalid.
1098 //mSurfaceHolder.mSurface.copyFrom(mSurface);
1099 mSurfaceHolder.mSurface = new Surface();
1100 mSurfaceHolder.mSurfaceLock.unlock();
1101 }
1102 }
Romain Guy53389bd2010-09-07 17:16:32 -07001103
Romain Guyc361da82010-10-25 15:29:10 -07001104 if (hwInitialized || (windowShouldResize && mAttachInfo.mHardwareRenderer != null)) {
Romain Guyb051e892010-09-28 19:09:36 -07001105 mAttachInfo.mHardwareRenderer.setup(mWidth, mHeight);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001106 }
1107
1108 boolean focusChangedDueToTouchMode = ensureTouchModeLocally(
Romain Guy2d4cff62010-04-09 15:39:00 -07001109 (relayoutResult&WindowManagerImpl.RELAYOUT_IN_TOUCH_MODE) != 0);
Dianne Hackborn189ee182010-12-02 21:48:53 -08001110 if (focusChangedDueToTouchMode || mWidth != host.getMeasuredWidth()
1111 || mHeight != host.getMeasuredHeight() || contentInsetsChanged) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001112 childWidthMeasureSpec = getRootMeasureSpec(mWidth, lp.width);
1113 childHeightMeasureSpec = getRootMeasureSpec(mHeight, lp.height);
1114
1115 if (DEBUG_LAYOUT) Log.v(TAG, "Ooops, something changed! mWidth="
Dianne Hackborn189ee182010-12-02 21:48:53 -08001116 + mWidth + " measuredWidth=" + host.getMeasuredWidth()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001117 + " mHeight=" + mHeight
Dianne Hackborn189ee182010-12-02 21:48:53 -08001118 + " measuredHeight" + host.getMeasuredHeight()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001119 + " coveredInsetsChanged=" + contentInsetsChanged);
Romain Guy8506ab42009-06-11 17:35:47 -07001120
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001121 // Ask host how big it wants to be
1122 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
1123
1124 // Implementation of weights from WindowManager.LayoutParams
1125 // We just grow the dimensions as needed and re-measure if
1126 // needs be
Dianne Hackborn189ee182010-12-02 21:48:53 -08001127 int width = host.getMeasuredWidth();
1128 int height = host.getMeasuredHeight();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001129 boolean measureAgain = false;
1130
1131 if (lp.horizontalWeight > 0.0f) {
1132 width += (int) ((mWidth - width) * lp.horizontalWeight);
1133 childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(width,
1134 MeasureSpec.EXACTLY);
1135 measureAgain = true;
1136 }
1137 if (lp.verticalWeight > 0.0f) {
1138 height += (int) ((mHeight - height) * lp.verticalWeight);
1139 childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(height,
1140 MeasureSpec.EXACTLY);
1141 measureAgain = true;
1142 }
1143
1144 if (measureAgain) {
1145 if (DEBUG_LAYOUT) Log.v(TAG,
1146 "And hey let's measure once more: width=" + width
1147 + " height=" + height);
1148 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
1149 }
1150
1151 mLayoutRequested = true;
1152 }
1153 }
1154
1155 final boolean didLayout = mLayoutRequested;
1156 boolean triggerGlobalLayoutListener = didLayout
1157 || attachInfo.mRecomputeGlobalAttributes;
1158 if (didLayout) {
1159 mLayoutRequested = false;
1160 mScrollMayChange = true;
1161 if (DEBUG_ORIENTATION || DEBUG_LAYOUT) Log.v(
Jeff Brownc5ed5912010-07-14 18:48:53 -07001162 TAG, "Laying out " + host + " to (" +
Dianne Hackborn189ee182010-12-02 21:48:53 -08001163 host.getMeasuredWidth() + ", " + host.getMeasuredHeight() + ")");
Romain Guy13922e02009-05-12 17:56:14 -07001164 long startTime = 0L;
Romain Guy5429e1d2010-09-07 12:38:00 -07001165 if (ViewDebug.DEBUG_PROFILE_LAYOUT) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001166 startTime = SystemClock.elapsedRealtime();
1167 }
Dianne Hackborn189ee182010-12-02 21:48:53 -08001168 host.layout(0, 0, host.getMeasuredWidth(), host.getMeasuredHeight());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001169
Romain Guy13922e02009-05-12 17:56:14 -07001170 if (Config.DEBUG && ViewDebug.consistencyCheckEnabled) {
1171 if (!host.dispatchConsistencyCheck(ViewDebug.CONSISTENCY_LAYOUT)) {
1172 throw new IllegalStateException("The view hierarchy is an inconsistent state,"
1173 + "please refer to the logs with the tag "
1174 + ViewDebug.CONSISTENCY_LOG_TAG + " for more infomation.");
1175 }
1176 }
1177
Romain Guy5429e1d2010-09-07 12:38:00 -07001178 if (ViewDebug.DEBUG_PROFILE_LAYOUT) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001179 EventLog.writeEvent(60001, SystemClock.elapsedRealtime() - startTime);
1180 }
1181
1182 // By this point all views have been sized and positionned
1183 // We can compute the transparent area
1184
1185 if ((host.mPrivateFlags & View.REQUEST_TRANSPARENT_REGIONS) != 0) {
1186 // start out transparent
1187 // TODO: AVOID THAT CALL BY CACHING THE RESULT?
1188 host.getLocationInWindow(mTmpLocation);
1189 mTransparentRegion.set(mTmpLocation[0], mTmpLocation[1],
1190 mTmpLocation[0] + host.mRight - host.mLeft,
1191 mTmpLocation[1] + host.mBottom - host.mTop);
1192
1193 host.gatherTransparentRegion(mTransparentRegion);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001194 if (mTranslator != null) {
1195 mTranslator.translateRegionInWindowToScreen(mTransparentRegion);
1196 }
1197
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001198 if (!mTransparentRegion.equals(mPreviousTransparentRegion)) {
1199 mPreviousTransparentRegion.set(mTransparentRegion);
1200 // reconfigure window manager
1201 try {
1202 sWindowSession.setTransparentRegion(mWindow, mTransparentRegion);
1203 } catch (RemoteException e) {
1204 }
1205 }
1206 }
1207
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001208 if (DBG) {
1209 System.out.println("======================================");
1210 System.out.println("performTraversals -- after setFrame");
1211 host.debug();
1212 }
1213 }
1214
1215 if (triggerGlobalLayoutListener) {
1216 attachInfo.mRecomputeGlobalAttributes = false;
1217 attachInfo.mTreeObserver.dispatchOnGlobalLayout();
1218 }
1219
1220 if (computesInternalInsets) {
1221 ViewTreeObserver.InternalInsetsInfo insets = attachInfo.mGivenInternalInsets;
1222 final Rect givenContent = attachInfo.mGivenInternalInsets.contentInsets;
1223 final Rect givenVisible = attachInfo.mGivenInternalInsets.visibleInsets;
1224 givenContent.left = givenContent.top = givenContent.right
1225 = givenContent.bottom = givenVisible.left = givenVisible.top
1226 = givenVisible.right = givenVisible.bottom = 0;
1227 attachInfo.mTreeObserver.dispatchOnComputeInternalInsets(insets);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001228 Rect contentInsets = insets.contentInsets;
1229 Rect visibleInsets = insets.visibleInsets;
1230 if (mTranslator != null) {
1231 contentInsets = mTranslator.getTranslatedContentInsets(contentInsets);
1232 visibleInsets = mTranslator.getTranslatedVisbileInsets(visibleInsets);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001233 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001234 if (insetsPending || !mLastGivenInsets.equals(insets)) {
1235 mLastGivenInsets.set(insets);
1236 try {
1237 sWindowSession.setInsets(mWindow, insets.mTouchableInsets,
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001238 contentInsets, visibleInsets);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001239 } catch (RemoteException e) {
1240 }
1241 }
1242 }
Romain Guy8506ab42009-06-11 17:35:47 -07001243
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001244 if (mFirst) {
1245 // handle first focus request
1246 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: mView.hasFocus()="
1247 + mView.hasFocus());
1248 if (mView != null) {
1249 if (!mView.hasFocus()) {
1250 mView.requestFocus(View.FOCUS_FORWARD);
1251 mFocusedView = mRealFocusedView = mView.findFocus();
1252 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: requested focused view="
1253 + mFocusedView);
1254 } else {
1255 mRealFocusedView = mView.findFocus();
1256 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: existing focused view="
1257 + mRealFocusedView);
1258 }
1259 }
1260 }
1261
1262 mFirst = false;
1263 mWillDrawSoon = false;
1264 mNewSurfaceNeeded = false;
1265 mViewVisibility = viewVisibility;
1266
1267 if (mAttachInfo.mHasWindowFocus) {
1268 final boolean imTarget = WindowManager.LayoutParams
1269 .mayUseInputMethod(mWindowAttributes.flags);
1270 if (imTarget != mLastWasImTarget) {
1271 mLastWasImTarget = imTarget;
1272 InputMethodManager imm = InputMethodManager.peekInstance();
1273 if (imm != null && imTarget) {
1274 imm.startGettingWindowFocus(mView);
1275 imm.onWindowFocus(mView, mView.findFocus(),
1276 mWindowAttributes.softInputMode,
1277 !mHasHadWindowFocus, mWindowAttributes.flags);
1278 }
1279 }
1280 }
Romain Guy8506ab42009-06-11 17:35:47 -07001281
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001282 boolean cancelDraw = attachInfo.mTreeObserver.dispatchOnPreDraw();
1283
1284 if (!cancelDraw && !newSurface) {
1285 mFullRedrawNeeded = false;
1286 draw(fullRedrawNeeded);
1287
1288 if ((relayoutResult&WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0
1289 || mReportNextDraw) {
1290 if (LOCAL_LOGV) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001291 Log.v(TAG, "FINISHED DRAWING: " + mWindowAttributes.getTitle());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001292 }
1293 mReportNextDraw = false;
Dianne Hackbornd76b67c2010-07-13 17:48:30 -07001294 if (mSurfaceHolder != null && mSurface.isValid()) {
1295 mSurfaceHolderCallback.surfaceRedrawNeeded(mSurfaceHolder);
1296 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
1297 if (callbacks != null) {
1298 for (SurfaceHolder.Callback c : callbacks) {
1299 if (c instanceof SurfaceHolder.Callback2) {
1300 ((SurfaceHolder.Callback2)c).surfaceRedrawNeeded(
1301 mSurfaceHolder);
1302 }
1303 }
1304 }
1305 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001306 try {
1307 sWindowSession.finishDrawing(mWindow);
1308 } catch (RemoteException e) {
1309 }
1310 }
1311 } else {
1312 // We were supposed to report when we are done drawing. Since we canceled the
1313 // draw, remember it here.
1314 if ((relayoutResult&WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0) {
1315 mReportNextDraw = true;
1316 }
1317 if (fullRedrawNeeded) {
1318 mFullRedrawNeeded = true;
1319 }
1320 // Try again
1321 scheduleTraversals();
1322 }
1323 }
1324
1325 public void requestTransparentRegion(View child) {
1326 // the test below should not fail unless someone is messing with us
1327 checkThread();
1328 if (mView == child) {
1329 mView.mPrivateFlags |= View.REQUEST_TRANSPARENT_REGIONS;
1330 // Need to make sure we re-evaluate the window attributes next
1331 // time around, to ensure the window has the correct format.
1332 mWindowAttributesChanged = true;
Mathias Agopian1bd80ad2010-11-04 17:13:39 -07001333 requestLayout();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001334 }
1335 }
1336
1337 /**
1338 * Figures out the measure spec for the root view in a window based on it's
1339 * layout params.
1340 *
1341 * @param windowSize
1342 * The available width or height of the window
1343 *
1344 * @param rootDimension
1345 * The layout params for one dimension (width or height) of the
1346 * window.
1347 *
1348 * @return The measure spec to use to measure the root view.
1349 */
1350 private int getRootMeasureSpec(int windowSize, int rootDimension) {
1351 int measureSpec;
1352 switch (rootDimension) {
1353
Romain Guy980a9382010-01-08 15:06:28 -08001354 case ViewGroup.LayoutParams.MATCH_PARENT:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001355 // Window can't resize. Force root view to be windowSize.
1356 measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.EXACTLY);
1357 break;
1358 case ViewGroup.LayoutParams.WRAP_CONTENT:
1359 // Window can resize. Set max size for root view.
1360 measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.AT_MOST);
1361 break;
1362 default:
1363 // Window wants to be an exact size. Force root view to be that size.
1364 measureSpec = MeasureSpec.makeMeasureSpec(rootDimension, MeasureSpec.EXACTLY);
1365 break;
1366 }
1367 return measureSpec;
1368 }
1369
Dianne Hackborn0f761d62010-11-30 22:06:10 -08001370 int mHardwareYOffset;
1371 int mResizeAlpha;
1372 final Paint mResizePaint = new Paint();
1373
1374 public void onHardwarePreDraw(Canvas canvas) {
1375 canvas.translate(0, -mHardwareYOffset);
1376 }
1377
1378 public void onHardwarePostDraw(Canvas canvas) {
1379 if (mResizeBitmap != null) {
1380 canvas.translate(0, mHardwareYOffset);
1381 mResizePaint.setAlpha(mResizeAlpha);
1382 canvas.drawBitmap(mResizeBitmap, 0, 0, mResizePaint);
1383 }
1384 }
1385
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001386 private void draw(boolean fullRedrawNeeded) {
1387 Surface surface = mSurface;
1388 if (surface == null || !surface.isValid()) {
1389 return;
1390 }
1391
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001392 if (!sFirstDrawComplete) {
1393 synchronized (sFirstDrawHandlers) {
1394 sFirstDrawComplete = true;
Romain Guy812ccbe2010-06-01 14:07:24 -07001395 final int count = sFirstDrawHandlers.size();
1396 for (int i = 0; i< count; i++) {
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001397 post(sFirstDrawHandlers.get(i));
1398 }
1399 }
1400 }
1401
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001402 scrollToRectOrFocus(null, false);
1403
1404 if (mAttachInfo.mViewScrollChanged) {
1405 mAttachInfo.mViewScrollChanged = false;
1406 mAttachInfo.mTreeObserver.dispatchOnScrollChanged();
1407 }
Romain Guy8506ab42009-06-11 17:35:47 -07001408
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001409 int yoff;
Dianne Hackborn0f761d62010-11-30 22:06:10 -08001410 boolean animating = mScroller != null && mScroller.computeScrollOffset();
1411 if (animating) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001412 yoff = mScroller.getCurrY();
1413 } else {
1414 yoff = mScrollY;
1415 }
1416 if (mCurScrollY != yoff) {
1417 mCurScrollY = yoff;
1418 fullRedrawNeeded = true;
1419 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001420 float appScale = mAttachInfo.mApplicationScale;
1421 boolean scalingRequired = mAttachInfo.mScalingRequired;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001422
Dianne Hackborn0f761d62010-11-30 22:06:10 -08001423 int resizeAlpha = 0;
1424 if (mResizeBitmap != null) {
1425 long deltaTime = SystemClock.uptimeMillis() - mResizeBitmapStartTime;
1426 if (deltaTime < mResizeBitmapDuration) {
1427 float amt = deltaTime/(float)mResizeBitmapDuration;
1428 amt = mResizeInterpolator.getInterpolation(amt);
1429 animating = true;
1430 resizeAlpha = 255 - (int)(amt*255);
1431 } else {
1432 disposeResizeBitmap();
1433 }
1434 }
1435
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001436 Rect dirty = mDirty;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001437 if (mSurfaceHolder != null) {
1438 // The app owns the surface, we won't draw.
1439 dirty.setEmpty();
Dianne Hackborn0f761d62010-11-30 22:06:10 -08001440 if (animating) {
1441 if (mScroller != null) {
1442 mScroller.abortAnimation();
1443 }
1444 disposeResizeBitmap();
1445 }
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001446 return;
1447 }
Romain Guy58ef7fb2010-09-13 12:52:37 -07001448
1449 if (fullRedrawNeeded) {
1450 mAttachInfo.mIgnoreDirtyState = true;
1451 dirty.union(0, 0, (int) (mWidth * appScale + 0.5f), (int) (mHeight * appScale + 0.5f));
1452 }
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001453
Romain Guyb051e892010-09-28 19:09:36 -07001454 if (mAttachInfo.mHardwareRenderer != null && mAttachInfo.mHardwareRenderer.isEnabled()) {
Romain Guyfd507262010-10-10 15:42:49 -07001455 if (!dirty.isEmpty() || mIsAnimating) {
Romain Guy101e2ae2010-10-11 12:41:21 -07001456 mIsAnimating = false;
Romain Guyfd507262010-10-10 15:42:49 -07001457 dirty.setEmpty();
Dianne Hackborn0f761d62010-11-30 22:06:10 -08001458 mHardwareYOffset = yoff;
1459 mResizeAlpha = resizeAlpha;
1460 mAttachInfo.mHardwareRenderer.draw(mView, mAttachInfo, this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001461 }
Romain Guy812ccbe2010-06-01 14:07:24 -07001462
Dianne Hackborn0f761d62010-11-30 22:06:10 -08001463 if (animating) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001464 mFullRedrawNeeded = true;
1465 scheduleTraversals();
1466 }
Romain Guy812ccbe2010-06-01 14:07:24 -07001467
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001468 return;
1469 }
1470
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001471 if (DEBUG_ORIENTATION || DEBUG_DRAW) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001472 Log.v(TAG, "Draw " + mView + "/"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001473 + mWindowAttributes.getTitle()
1474 + ": dirty={" + dirty.left + "," + dirty.top
1475 + "," + dirty.right + "," + dirty.bottom + "} surface="
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001476 + surface + " surface.isValid()=" + surface.isValid() + ", appScale:" +
1477 appScale + ", width=" + mWidth + ", height=" + mHeight);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001478 }
1479
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001480 if (!dirty.isEmpty() || mIsAnimating) {
1481 Canvas canvas;
1482 try {
1483 int left = dirty.left;
1484 int top = dirty.top;
1485 int right = dirty.right;
1486 int bottom = dirty.bottom;
1487 canvas = surface.lockCanvas(dirty);
Romain Guy5bcdff42009-05-14 21:27:18 -07001488
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001489 if (left != dirty.left || top != dirty.top || right != dirty.right ||
1490 bottom != dirty.bottom) {
1491 mAttachInfo.mIgnoreDirtyState = true;
1492 }
1493
1494 // TODO: Do this in native
1495 canvas.setDensity(mDensity);
1496 } catch (Surface.OutOfResourcesException e) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001497 Log.e(TAG, "OutOfResourcesException locking surface", e);
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001498 // TODO: we should ask the window manager to do something!
1499 // for now we just do nothing
1500 return;
1501 } catch (IllegalArgumentException e) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001502 Log.e(TAG, "IllegalArgumentException locking surface", e);
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001503 // TODO: we should ask the window manager to do something!
1504 // for now we just do nothing
1505 return;
Romain Guy5bcdff42009-05-14 21:27:18 -07001506 }
1507
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001508 try {
1509 if (!dirty.isEmpty() || mIsAnimating) {
1510 long startTime = 0L;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001511
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001512 if (DEBUG_ORIENTATION || DEBUG_DRAW) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001513 Log.v(TAG, "Surface " + surface + " drawing to bitmap w="
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001514 + canvas.getWidth() + ", h=" + canvas.getHeight());
1515 //canvas.drawARGB(255, 255, 0, 0);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001516 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001517
Romain Guy5429e1d2010-09-07 12:38:00 -07001518 if (ViewDebug.DEBUG_PROFILE_DRAWING) {
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001519 startTime = SystemClock.elapsedRealtime();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001520 }
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001521
1522 // If this bitmap's format includes an alpha channel, we
1523 // need to clear it before drawing so that the child will
1524 // properly re-composite its drawing on a transparent
1525 // background. This automatically respects the clip/dirty region
1526 // or
1527 // If we are applying an offset, we need to clear the area
1528 // where the offset doesn't appear to avoid having garbage
1529 // left in the blank areas.
1530 if (!canvas.isOpaque() || yoff != 0) {
1531 canvas.drawColor(0, PorterDuff.Mode.CLEAR);
1532 }
1533
1534 dirty.setEmpty();
1535 mIsAnimating = false;
1536 mAttachInfo.mDrawingTime = SystemClock.uptimeMillis();
1537 mView.mPrivateFlags |= View.DRAWN;
1538
1539 if (DEBUG_DRAW) {
1540 Context cxt = mView.getContext();
1541 Log.i(TAG, "Drawing: package:" + cxt.getPackageName() +
1542 ", metrics=" + cxt.getResources().getDisplayMetrics() +
1543 ", compatibilityInfo=" + cxt.getResources().getCompatibilityInfo());
1544 }
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001545 try {
1546 canvas.translate(0, -yoff);
1547 if (mTranslator != null) {
1548 mTranslator.translateCanvas(canvas);
1549 }
1550 canvas.setScreenDensity(scalingRequired
1551 ? DisplayMetrics.DENSITY_DEVICE : 0);
1552 mView.draw(canvas);
1553 } finally {
1554 mAttachInfo.mIgnoreDirtyState = false;
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001555 }
1556
1557 if (Config.DEBUG && ViewDebug.consistencyCheckEnabled) {
1558 mView.dispatchConsistencyCheck(ViewDebug.CONSISTENCY_DRAWING);
1559 }
1560
Romain Guy5429e1d2010-09-07 12:38:00 -07001561 if (SHOW_FPS || ViewDebug.DEBUG_SHOW_FPS) {
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001562 int now = (int)SystemClock.elapsedRealtime();
1563 if (sDrawTime != 0) {
1564 nativeShowFPS(canvas, now - sDrawTime);
1565 }
1566 sDrawTime = now;
1567 }
1568
Romain Guy5429e1d2010-09-07 12:38:00 -07001569 if (ViewDebug.DEBUG_PROFILE_DRAWING) {
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001570 EventLog.writeEvent(60000, SystemClock.elapsedRealtime() - startTime);
1571 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001572 }
1573
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001574 } finally {
1575 surface.unlockCanvasAndPost(canvas);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001576 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001577 }
1578
1579 if (LOCAL_LOGV) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001580 Log.v(TAG, "Surface " + surface + " unlockCanvasAndPost");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001581 }
Romain Guy8506ab42009-06-11 17:35:47 -07001582
Dianne Hackborn0f761d62010-11-30 22:06:10 -08001583 if (animating) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001584 mFullRedrawNeeded = true;
1585 scheduleTraversals();
1586 }
1587 }
1588
1589 boolean scrollToRectOrFocus(Rect rectangle, boolean immediate) {
1590 final View.AttachInfo attachInfo = mAttachInfo;
1591 final Rect ci = attachInfo.mContentInsets;
1592 final Rect vi = attachInfo.mVisibleInsets;
1593 int scrollY = 0;
1594 boolean handled = false;
Romain Guy8506ab42009-06-11 17:35:47 -07001595
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001596 if (vi.left > ci.left || vi.top > ci.top
1597 || vi.right > ci.right || vi.bottom > ci.bottom) {
1598 // We'll assume that we aren't going to change the scroll
1599 // offset, since we want to avoid that unless it is actually
1600 // going to make the focus visible... otherwise we scroll
1601 // all over the place.
1602 scrollY = mScrollY;
1603 // We can be called for two different situations: during a draw,
1604 // to update the scroll position if the focus has changed (in which
1605 // case 'rectangle' is null), or in response to a
1606 // requestChildRectangleOnScreen() call (in which case 'rectangle'
1607 // is non-null and we just want to scroll to whatever that
1608 // rectangle is).
1609 View focus = mRealFocusedView;
Romain Guye8b16522009-07-14 13:06:42 -07001610
1611 // When in touch mode, focus points to the previously focused view,
1612 // which may have been removed from the view hierarchy. The following
Joe Onoratob71193b2009-11-24 18:34:42 -05001613 // line checks whether the view is still in our hierarchy.
1614 if (focus == null || focus.mAttachInfo != mAttachInfo) {
Romain Guye8b16522009-07-14 13:06:42 -07001615 mRealFocusedView = null;
1616 return false;
1617 }
1618
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001619 if (focus != mLastScrolledFocus) {
1620 // If the focus has changed, then ignore any requests to scroll
1621 // to a rectangle; first we want to make sure the entire focus
1622 // view is visible.
1623 rectangle = null;
1624 }
1625 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Eval scroll: focus=" + focus
1626 + " rectangle=" + rectangle + " ci=" + ci
1627 + " vi=" + vi);
1628 if (focus == mLastScrolledFocus && !mScrollMayChange
1629 && rectangle == null) {
1630 // Optimization: if the focus hasn't changed since last
1631 // time, and no layout has happened, then just leave things
1632 // as they are.
1633 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Keeping scroll y="
1634 + mScrollY + " vi=" + vi.toShortString());
1635 } else if (focus != null) {
1636 // We need to determine if the currently focused view is
1637 // within the visible part of the window and, if not, apply
1638 // a pan so it can be seen.
1639 mLastScrolledFocus = focus;
1640 mScrollMayChange = false;
1641 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Need to scroll?");
1642 // Try to find the rectangle from the focus view.
1643 if (focus.getGlobalVisibleRect(mVisRect, null)) {
1644 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Root w="
1645 + mView.getWidth() + " h=" + mView.getHeight()
1646 + " ci=" + ci.toShortString()
1647 + " vi=" + vi.toShortString());
1648 if (rectangle == null) {
1649 focus.getFocusedRect(mTempRect);
1650 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Focus " + focus
1651 + ": focusRect=" + mTempRect.toShortString());
Dianne Hackborn1c6a8942010-03-23 16:34:20 -07001652 if (mView instanceof ViewGroup) {
1653 ((ViewGroup) mView).offsetDescendantRectToMyCoords(
1654 focus, mTempRect);
1655 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001656 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1657 "Focus in window: focusRect="
1658 + mTempRect.toShortString()
1659 + " visRect=" + mVisRect.toShortString());
1660 } else {
1661 mTempRect.set(rectangle);
1662 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1663 "Request scroll to rect: "
1664 + mTempRect.toShortString()
1665 + " visRect=" + mVisRect.toShortString());
1666 }
1667 if (mTempRect.intersect(mVisRect)) {
1668 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1669 "Focus window visible rect: "
1670 + mTempRect.toShortString());
1671 if (mTempRect.height() >
1672 (mView.getHeight()-vi.top-vi.bottom)) {
1673 // If the focus simply is not going to fit, then
1674 // best is probably just to leave things as-is.
1675 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1676 "Too tall; leaving scrollY=" + scrollY);
1677 } else if ((mTempRect.top-scrollY) < vi.top) {
1678 scrollY -= vi.top - (mTempRect.top-scrollY);
1679 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1680 "Top covered; scrollY=" + scrollY);
1681 } else if ((mTempRect.bottom-scrollY)
1682 > (mView.getHeight()-vi.bottom)) {
1683 scrollY += (mTempRect.bottom-scrollY)
1684 - (mView.getHeight()-vi.bottom);
1685 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1686 "Bottom covered; scrollY=" + scrollY);
1687 }
1688 handled = true;
1689 }
1690 }
1691 }
1692 }
Romain Guy8506ab42009-06-11 17:35:47 -07001693
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001694 if (scrollY != mScrollY) {
1695 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Pan scroll changed: old="
1696 + mScrollY + " , new=" + scrollY);
Dianne Hackborn0f761d62010-11-30 22:06:10 -08001697 if (!immediate && mResizeBitmap == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001698 if (mScroller == null) {
1699 mScroller = new Scroller(mView.getContext());
1700 }
1701 mScroller.startScroll(0, mScrollY, 0, scrollY-mScrollY);
1702 } else if (mScroller != null) {
1703 mScroller.abortAnimation();
1704 }
1705 mScrollY = scrollY;
1706 }
Romain Guy8506ab42009-06-11 17:35:47 -07001707
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001708 return handled;
1709 }
Romain Guy8506ab42009-06-11 17:35:47 -07001710
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001711 public void requestChildFocus(View child, View focused) {
1712 checkThread();
1713 if (mFocusedView != focused) {
1714 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(mFocusedView, focused);
1715 scheduleTraversals();
1716 }
1717 mFocusedView = mRealFocusedView = focused;
1718 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Request child focus: focus now "
1719 + mFocusedView);
1720 }
1721
1722 public void clearChildFocus(View child) {
1723 checkThread();
1724
1725 View oldFocus = mFocusedView;
1726
1727 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Clearing child focus");
1728 mFocusedView = mRealFocusedView = null;
1729 if (mView != null && !mView.hasFocus()) {
1730 // If a view gets the focus, the listener will be invoked from requestChildFocus()
1731 if (!mView.requestFocus(View.FOCUS_FORWARD)) {
1732 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
1733 }
1734 } else if (oldFocus != null) {
1735 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
1736 }
1737 }
1738
1739
1740 public void focusableViewAvailable(View v) {
1741 checkThread();
1742
1743 if (mView != null && !mView.hasFocus()) {
1744 v.requestFocus();
1745 } else {
1746 // the one case where will transfer focus away from the current one
1747 // is if the current view is a view group that prefers to give focus
1748 // to its children first AND the view is a descendant of it.
1749 mFocusedView = mView.findFocus();
1750 boolean descendantsHaveDibsOnFocus =
1751 (mFocusedView instanceof ViewGroup) &&
1752 (((ViewGroup) mFocusedView).getDescendantFocusability() ==
1753 ViewGroup.FOCUS_AFTER_DESCENDANTS);
1754 if (descendantsHaveDibsOnFocus && isViewDescendantOf(v, mFocusedView)) {
1755 // If a view gets the focus, the listener will be invoked from requestChildFocus()
1756 v.requestFocus();
1757 }
1758 }
1759 }
1760
1761 public void recomputeViewAttributes(View child) {
1762 checkThread();
1763 if (mView == child) {
1764 mAttachInfo.mRecomputeGlobalAttributes = true;
1765 if (!mWillDrawSoon) {
1766 scheduleTraversals();
1767 }
1768 }
1769 }
1770
1771 void dispatchDetachedFromWindow() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001772 if (mView != null) {
1773 mView.dispatchDetachedFromWindow();
1774 }
1775
1776 mView = null;
1777 mAttachInfo.mRootView = null;
Mathias Agopian5583dc62009-07-09 16:28:11 -07001778 mAttachInfo.mSurface = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001779
Romain Guy29d89972010-09-22 16:10:57 -07001780 destroyHardwareRenderer();
Romain Guy4caa4ed2010-08-25 14:46:24 -07001781
Dianne Hackborn0586a1b2009-09-06 21:08:27 -07001782 mSurface.release();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001783
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001784 if (mInputChannel != null) {
1785 if (mInputQueueCallback != null) {
1786 mInputQueueCallback.onInputQueueDestroyed(mInputQueue);
1787 mInputQueueCallback = null;
1788 } else {
1789 InputQueue.unregisterInputChannel(mInputChannel);
Jeff Brown46b9ac02010-04-22 18:58:52 -07001790 }
1791 }
1792
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001793 try {
1794 sWindowSession.remove(mWindow);
1795 } catch (RemoteException e) {
1796 }
Jeff Brown349703e2010-06-22 01:27:15 -07001797
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001798 // Dispose the input channel after removing the window so the Window Manager
1799 // doesn't interpret the input channel being closed as an abnormal termination.
1800 if (mInputChannel != null) {
1801 mInputChannel.dispose();
1802 mInputChannel = null;
Jeff Brown349703e2010-06-22 01:27:15 -07001803 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001804 }
Romain Guy8506ab42009-06-11 17:35:47 -07001805
Dianne Hackborn694f79b2010-03-17 19:44:59 -07001806 void updateConfiguration(Configuration config, boolean force) {
1807 if (DEBUG_CONFIGURATION) Log.v(TAG,
1808 "Applying new config to window "
1809 + mWindowAttributes.getTitle()
1810 + ": " + config);
1811 synchronized (sConfigCallbacks) {
1812 for (int i=sConfigCallbacks.size()-1; i>=0; i--) {
1813 sConfigCallbacks.get(i).onConfigurationChanged(config);
1814 }
1815 }
1816 if (mView != null) {
1817 // At this point the resources have been updated to
1818 // have the most recent config, whatever that is. Use
1819 // the on in them which may be newer.
1820 if (mView != null) {
1821 config = mView.getResources().getConfiguration();
1822 }
1823 if (force || mLastConfiguration.diff(config) != 0) {
1824 mLastConfiguration.setTo(config);
1825 mView.dispatchConfigurationChanged(config);
1826 }
1827 }
1828 }
1829
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001830 /**
1831 * Return true if child is an ancestor of parent, (or equal to the parent).
1832 */
1833 private static boolean isViewDescendantOf(View child, View parent) {
1834 if (child == parent) {
1835 return true;
1836 }
1837
1838 final ViewParent theParent = child.getParent();
1839 return (theParent instanceof ViewGroup) && isViewDescendantOf((View) theParent, parent);
1840 }
1841
Romain Guycdb86672010-03-18 18:54:50 -07001842 private static void forceLayout(View view) {
1843 view.forceLayout();
1844 if (view instanceof ViewGroup) {
1845 ViewGroup group = (ViewGroup) view;
1846 final int count = group.getChildCount();
1847 for (int i = 0; i < count; i++) {
1848 forceLayout(group.getChildAt(i));
1849 }
1850 }
1851 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001852
1853 public final static int DO_TRAVERSAL = 1000;
1854 public final static int DIE = 1001;
1855 public final static int RESIZED = 1002;
1856 public final static int RESIZED_REPORT = 1003;
1857 public final static int WINDOW_FOCUS_CHANGED = 1004;
1858 public final static int DISPATCH_KEY = 1005;
1859 public final static int DISPATCH_POINTER = 1006;
1860 public final static int DISPATCH_TRACKBALL = 1007;
1861 public final static int DISPATCH_APP_VISIBILITY = 1008;
1862 public final static int DISPATCH_GET_NEW_SURFACE = 1009;
1863 public final static int FINISHED_EVENT = 1010;
1864 public final static int DISPATCH_KEY_FROM_IME = 1011;
1865 public final static int FINISH_INPUT_CONNECTION = 1012;
1866 public final static int CHECK_FOCUS = 1013;
Dianne Hackbornffa42482009-09-23 22:20:11 -07001867 public final static int CLOSE_SYSTEM_DIALOGS = 1014;
Christopher Tatea53146c2010-09-07 11:57:52 -07001868 public final static int DISPATCH_DRAG_EVENT = 1015;
Chris Tate91e9bb32010-10-12 12:58:43 -07001869 public final static int DISPATCH_DRAG_LOCATION_EVENT = 1016;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001870
1871 @Override
1872 public void handleMessage(Message msg) {
1873 switch (msg.what) {
1874 case View.AttachInfo.INVALIDATE_MSG:
1875 ((View) msg.obj).invalidate();
1876 break;
1877 case View.AttachInfo.INVALIDATE_RECT_MSG:
1878 final View.AttachInfo.InvalidateInfo info = (View.AttachInfo.InvalidateInfo) msg.obj;
1879 info.target.invalidate(info.left, info.top, info.right, info.bottom);
1880 info.release();
1881 break;
1882 case DO_TRAVERSAL:
1883 if (mProfile) {
1884 Debug.startMethodTracing("ViewRoot");
1885 }
1886
1887 performTraversals();
1888
1889 if (mProfile) {
1890 Debug.stopMethodTracing();
1891 mProfile = false;
1892 }
1893 break;
1894 case FINISHED_EVENT:
1895 handleFinishedEvent(msg.arg1, msg.arg2 != 0);
1896 break;
1897 case DISPATCH_KEY:
Jeff Brown92ff1dd2010-08-11 16:16:06 -07001898 deliverKeyEvent((KeyEvent)msg.obj, msg.arg1 != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001899 break;
Jeff Brown3915bb82010-11-05 15:02:16 -07001900 case DISPATCH_POINTER:
1901 deliverPointerEvent((MotionEvent) msg.obj, msg.arg1 != 0);
1902 break;
1903 case DISPATCH_TRACKBALL:
1904 deliverTrackballEvent((MotionEvent) msg.obj, msg.arg1 != 0);
1905 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001906 case DISPATCH_APP_VISIBILITY:
1907 handleAppVisibility(msg.arg1 != 0);
1908 break;
1909 case DISPATCH_GET_NEW_SURFACE:
1910 handleGetNewSurface();
1911 break;
1912 case RESIZED:
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001913 ResizedInfo ri = (ResizedInfo)msg.obj;
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001914
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001915 if (mWinFrame.width() == msg.arg1 && mWinFrame.height() == msg.arg2
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001916 && mPendingContentInsets.equals(ri.coveredInsets)
Dianne Hackbornd49258f2010-03-26 00:44:29 -07001917 && mPendingVisibleInsets.equals(ri.visibleInsets)
1918 && ((ResizedInfo)msg.obj).newConfig == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001919 break;
1920 }
1921 // fall through...
1922 case RESIZED_REPORT:
1923 if (mAdded) {
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001924 Configuration config = ((ResizedInfo)msg.obj).newConfig;
1925 if (config != null) {
Dianne Hackborn694f79b2010-03-17 19:44:59 -07001926 updateConfiguration(config, false);
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001927 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001928 mWinFrame.left = 0;
1929 mWinFrame.right = msg.arg1;
1930 mWinFrame.top = 0;
1931 mWinFrame.bottom = msg.arg2;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001932 mPendingContentInsets.set(((ResizedInfo)msg.obj).coveredInsets);
1933 mPendingVisibleInsets.set(((ResizedInfo)msg.obj).visibleInsets);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001934 if (msg.what == RESIZED_REPORT) {
1935 mReportNextDraw = true;
1936 }
Romain Guycdb86672010-03-18 18:54:50 -07001937
1938 if (mView != null) {
1939 forceLayout(mView);
1940 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001941 requestLayout();
1942 }
1943 break;
1944 case WINDOW_FOCUS_CHANGED: {
1945 if (mAdded) {
1946 boolean hasWindowFocus = msg.arg1 != 0;
1947 mAttachInfo.mHasWindowFocus = hasWindowFocus;
1948 if (hasWindowFocus) {
1949 boolean inTouchMode = msg.arg2 != 0;
Romain Guy2d4cff62010-04-09 15:39:00 -07001950 ensureTouchModeLocally(inTouchMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001951
Romain Guyc361da82010-10-25 15:29:10 -07001952 if (mAttachInfo.mHardwareRenderer != null &&
1953 mSurface != null && mSurface.isValid()) {
Romain Guyb051e892010-09-28 19:09:36 -07001954 mAttachInfo.mHardwareRenderer.initializeIfNeeded(mWidth, mHeight,
1955 mAttachInfo, mHolder);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001956 }
1957 }
Romain Guy8506ab42009-06-11 17:35:47 -07001958
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001959 mLastWasImTarget = WindowManager.LayoutParams
1960 .mayUseInputMethod(mWindowAttributes.flags);
Romain Guy8506ab42009-06-11 17:35:47 -07001961
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001962 InputMethodManager imm = InputMethodManager.peekInstance();
1963 if (mView != null) {
1964 if (hasWindowFocus && imm != null && mLastWasImTarget) {
1965 imm.startGettingWindowFocus(mView);
1966 }
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07001967 mAttachInfo.mKeyDispatchState.reset();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001968 mView.dispatchWindowFocusChanged(hasWindowFocus);
1969 }
svetoslavganov75986cf2009-05-14 22:28:01 -07001970
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001971 // Note: must be done after the focus change callbacks,
1972 // so all of the view state is set up correctly.
1973 if (hasWindowFocus) {
1974 if (imm != null && mLastWasImTarget) {
1975 imm.onWindowFocus(mView, mView.findFocus(),
1976 mWindowAttributes.softInputMode,
1977 !mHasHadWindowFocus, mWindowAttributes.flags);
1978 }
1979 // Clear the forward bit. We can just do this directly, since
1980 // the window manager doesn't care about it.
1981 mWindowAttributes.softInputMode &=
1982 ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
1983 ((WindowManager.LayoutParams)mView.getLayoutParams())
1984 .softInputMode &=
1985 ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
1986 mHasHadWindowFocus = true;
1987 }
svetoslavganov75986cf2009-05-14 22:28:01 -07001988
1989 if (hasWindowFocus && mView != null) {
1990 sendAccessibilityEvents();
1991 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001992 }
1993 } break;
1994 case DIE:
Dianne Hackborn94d69142009-09-28 22:14:42 -07001995 doDie();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001996 break;
The Android Open Source Project10592532009-03-18 17:39:46 -07001997 case DISPATCH_KEY_FROM_IME: {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001998 if (LOCAL_LOGV) Log.v(
Jeff Brownc5ed5912010-07-14 18:48:53 -07001999 TAG, "Dispatching key "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002000 + msg.obj + " from IME to " + mView);
The Android Open Source Project10592532009-03-18 17:39:46 -07002001 KeyEvent event = (KeyEvent)msg.obj;
2002 if ((event.getFlags()&KeyEvent.FLAG_FROM_SYSTEM) != 0) {
2003 // The IME is trying to say this event is from the
2004 // system! Bad bad bad!
Romain Guy812ccbe2010-06-01 14:07:24 -07002005 event = KeyEvent.changeFlags(event, event.getFlags() & ~KeyEvent.FLAG_FROM_SYSTEM);
The Android Open Source Project10592532009-03-18 17:39:46 -07002006 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002007 deliverKeyEventPostIme((KeyEvent)msg.obj, false);
The Android Open Source Project10592532009-03-18 17:39:46 -07002008 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002009 case FINISH_INPUT_CONNECTION: {
2010 InputMethodManager imm = InputMethodManager.peekInstance();
2011 if (imm != null) {
2012 imm.reportFinishInputConnection((InputConnection)msg.obj);
2013 }
2014 } break;
2015 case CHECK_FOCUS: {
2016 InputMethodManager imm = InputMethodManager.peekInstance();
2017 if (imm != null) {
2018 imm.checkFocus();
2019 }
2020 } break;
Dianne Hackbornffa42482009-09-23 22:20:11 -07002021 case CLOSE_SYSTEM_DIALOGS: {
2022 if (mView != null) {
2023 mView.onCloseSystemDialogs((String)msg.obj);
2024 }
2025 } break;
Chris Tate91e9bb32010-10-12 12:58:43 -07002026 case DISPATCH_DRAG_EVENT:
2027 case DISPATCH_DRAG_LOCATION_EVENT: {
Christopher Tatea53146c2010-09-07 11:57:52 -07002028 handleDragEvent((DragEvent)msg.obj);
2029 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002030 }
2031 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002032
Jeff Brown3915bb82010-11-05 15:02:16 -07002033 private void startInputEvent(InputQueue.FinishedCallback finishedCallback) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07002034 if (mFinishedCallback != null) {
2035 Slog.w(TAG, "Received a new input event from the input queue but there is "
2036 + "already an unfinished input event in progress.");
2037 }
2038
2039 mFinishedCallback = finishedCallback;
2040 }
2041
Jeff Brown3915bb82010-11-05 15:02:16 -07002042 private void finishInputEvent(boolean handled) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07002043 if (LOCAL_LOGV) Log.v(TAG, "Telling window manager input event is finished");
Jeff Brown92ff1dd2010-08-11 16:16:06 -07002044
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002045 if (mFinishedCallback != null) {
Jeff Brown3915bb82010-11-05 15:02:16 -07002046 mFinishedCallback.finished(handled);
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002047 mFinishedCallback = null;
Jeff Brown92ff1dd2010-08-11 16:16:06 -07002048 } else {
Jeff Brown93ed4e32010-09-23 13:51:48 -07002049 Slog.w(TAG, "Attempted to tell the input queue that the current input event "
2050 + "is finished but there is no input event actually in progress.");
Jeff Brown46b9ac02010-04-22 18:58:52 -07002051 }
2052 }
2053
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002054 /**
2055 * Something in the current window tells us we need to change the touch mode. For
2056 * example, we are not in touch mode, and the user touches the screen.
2057 *
2058 * If the touch mode has changed, tell the window manager, and handle it locally.
2059 *
2060 * @param inTouchMode Whether we want to be in touch mode.
2061 * @return True if the touch mode changed and focus changed was changed as a result
2062 */
2063 boolean ensureTouchMode(boolean inTouchMode) {
2064 if (DBG) Log.d("touchmode", "ensureTouchMode(" + inTouchMode + "), current "
2065 + "touch mode is " + mAttachInfo.mInTouchMode);
2066 if (mAttachInfo.mInTouchMode == inTouchMode) return false;
2067
2068 // tell the window manager
2069 try {
2070 sWindowSession.setInTouchMode(inTouchMode);
2071 } catch (RemoteException e) {
2072 throw new RuntimeException(e);
2073 }
2074
2075 // handle the change
Romain Guy2d4cff62010-04-09 15:39:00 -07002076 return ensureTouchModeLocally(inTouchMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002077 }
2078
2079 /**
2080 * Ensure that the touch mode for this window is set, and if it is changing,
2081 * take the appropriate action.
2082 * @param inTouchMode Whether we want to be in touch mode.
2083 * @return True if the touch mode changed and focus changed was changed as a result
2084 */
Romain Guy2d4cff62010-04-09 15:39:00 -07002085 private boolean ensureTouchModeLocally(boolean inTouchMode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002086 if (DBG) Log.d("touchmode", "ensureTouchModeLocally(" + inTouchMode + "), current "
2087 + "touch mode is " + mAttachInfo.mInTouchMode);
2088
2089 if (mAttachInfo.mInTouchMode == inTouchMode) return false;
2090
2091 mAttachInfo.mInTouchMode = inTouchMode;
2092 mAttachInfo.mTreeObserver.dispatchOnTouchModeChanged(inTouchMode);
2093
Romain Guy2d4cff62010-04-09 15:39:00 -07002094 return (inTouchMode) ? enterTouchMode() : leaveTouchMode();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002095 }
2096
2097 private boolean enterTouchMode() {
2098 if (mView != null) {
2099 if (mView.hasFocus()) {
2100 // note: not relying on mFocusedView here because this could
2101 // be when the window is first being added, and mFocused isn't
2102 // set yet.
2103 final View focused = mView.findFocus();
2104 if (focused != null && !focused.isFocusableInTouchMode()) {
2105
2106 final ViewGroup ancestorToTakeFocus =
2107 findAncestorToTakeFocusInTouchMode(focused);
2108 if (ancestorToTakeFocus != null) {
2109 // there is an ancestor that wants focus after its descendants that
2110 // is focusable in touch mode.. give it focus
2111 return ancestorToTakeFocus.requestFocus();
2112 } else {
2113 // nothing appropriate to have focus in touch mode, clear it out
2114 mView.unFocus();
2115 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(focused, null);
2116 mFocusedView = null;
2117 return true;
2118 }
2119 }
2120 }
2121 }
2122 return false;
2123 }
2124
2125
2126 /**
2127 * Find an ancestor of focused that wants focus after its descendants and is
2128 * focusable in touch mode.
2129 * @param focused The currently focused view.
2130 * @return An appropriate view, or null if no such view exists.
2131 */
2132 private ViewGroup findAncestorToTakeFocusInTouchMode(View focused) {
2133 ViewParent parent = focused.getParent();
2134 while (parent instanceof ViewGroup) {
2135 final ViewGroup vgParent = (ViewGroup) parent;
2136 if (vgParent.getDescendantFocusability() == ViewGroup.FOCUS_AFTER_DESCENDANTS
2137 && vgParent.isFocusableInTouchMode()) {
2138 return vgParent;
2139 }
2140 if (vgParent.isRootNamespace()) {
2141 return null;
2142 } else {
2143 parent = vgParent.getParent();
2144 }
2145 }
2146 return null;
2147 }
2148
2149 private boolean leaveTouchMode() {
2150 if (mView != null) {
2151 if (mView.hasFocus()) {
2152 // i learned the hard way to not trust mFocusedView :)
2153 mFocusedView = mView.findFocus();
2154 if (!(mFocusedView instanceof ViewGroup)) {
2155 // some view has focus, let it keep it
2156 return false;
2157 } else if (((ViewGroup)mFocusedView).getDescendantFocusability() !=
2158 ViewGroup.FOCUS_AFTER_DESCENDANTS) {
2159 // some view group has focus, and doesn't prefer its children
2160 // over itself for focus, so let them keep it.
2161 return false;
2162 }
2163 }
2164
2165 // find the best view to give focus to in this brave new non-touch-mode
2166 // world
2167 final View focused = focusSearch(null, View.FOCUS_DOWN);
2168 if (focused != null) {
2169 return focused.requestFocus(View.FOCUS_DOWN);
2170 }
2171 }
2172 return false;
2173 }
2174
Jeff Brown3915bb82010-11-05 15:02:16 -07002175 private void deliverPointerEvent(MotionEvent event, boolean sendDone) {
2176 // If there is no view, then the event will not be handled.
2177 if (mView == null || !mAdded) {
2178 finishPointerEvent(event, sendDone, false);
2179 return;
2180 }
2181
2182 // Translate the pointer event for compatibility, if needed.
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002183 if (mTranslator != null) {
2184 mTranslator.translateEventInScreenToAppWindow(event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002185 }
2186
Jeff Brown3915bb82010-11-05 15:02:16 -07002187 // Enter touch mode on the down.
2188 boolean isDown = event.getAction() == MotionEvent.ACTION_DOWN;
2189 if (isDown) {
2190 ensureTouchMode(true);
2191 }
2192 if(Config.LOGV) {
2193 captureMotionLog("captureDispatchPointer", event);
2194 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002195
Jeff Brown3915bb82010-11-05 15:02:16 -07002196 // Offset the scroll position.
2197 if (mCurScrollY != 0) {
2198 event.offsetLocation(0, mCurScrollY);
2199 }
2200 if (MEASURE_LATENCY) {
2201 lt.sample("A Dispatching TouchEvents", System.nanoTime() - event.getEventTimeNano());
2202 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002203
Jeff Brown3915bb82010-11-05 15:02:16 -07002204 // Remember the touch position for possible drag-initiation.
2205 mLastTouchPoint.x = event.getRawX();
2206 mLastTouchPoint.y = event.getRawY();
2207
2208 // Dispatch touch to view hierarchy.
2209 boolean handled = mView.dispatchTouchEvent(event);
2210 if (MEASURE_LATENCY) {
2211 lt.sample("B Dispatched TouchEvents ", System.nanoTime() - event.getEventTimeNano());
2212 }
2213 if (handled) {
2214 finishPointerEvent(event, sendDone, true);
2215 return;
2216 }
2217
2218 // Apply edge slop and try again, if appropriate.
2219 final int edgeFlags = event.getEdgeFlags();
2220 if (edgeFlags != 0 && mView instanceof ViewGroup) {
2221 final int edgeSlop = mViewConfiguration.getScaledEdgeSlop();
2222 int direction = View.FOCUS_UP;
2223 int x = (int)event.getX();
2224 int y = (int)event.getY();
2225 final int[] deltas = new int[2];
2226
2227 if ((edgeFlags & MotionEvent.EDGE_TOP) != 0) {
2228 direction = View.FOCUS_DOWN;
2229 if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
2230 deltas[0] = edgeSlop;
2231 x += edgeSlop;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002232 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
Jeff Brown3915bb82010-11-05 15:02:16 -07002233 deltas[0] = -edgeSlop;
2234 x -= edgeSlop;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002235 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002236 } else if ((edgeFlags & MotionEvent.EDGE_BOTTOM) != 0) {
2237 direction = View.FOCUS_UP;
2238 if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
2239 deltas[0] = edgeSlop;
2240 x += edgeSlop;
2241 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
2242 deltas[0] = -edgeSlop;
2243 x -= edgeSlop;
2244 }
2245 } else if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
2246 direction = View.FOCUS_RIGHT;
2247 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
2248 direction = View.FOCUS_LEFT;
2249 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002250
Jeff Brown3915bb82010-11-05 15:02:16 -07002251 View nearest = FocusFinder.getInstance().findNearestTouchable(
2252 ((ViewGroup) mView), x, y, direction, deltas);
2253 if (nearest != null) {
2254 event.offsetLocation(deltas[0], deltas[1]);
2255 event.setEdgeFlags(0);
2256 if (mView.dispatchTouchEvent(event)) {
2257 finishPointerEvent(event, sendDone, true);
2258 return;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002259 }
2260 }
2261 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002262
2263 // Pointer event was unhandled.
2264 finishPointerEvent(event, sendDone, false);
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002265 }
2266
Jeff Brown3915bb82010-11-05 15:02:16 -07002267 private void finishPointerEvent(MotionEvent event, boolean sendDone, boolean handled) {
2268 event.recycle();
2269 if (sendDone) {
2270 finishInputEvent(handled);
2271 }
2272 if (LOCAL_LOGV || WATCH_POINTER) Log.i(TAG, "Done dispatching!");
2273 }
2274
2275 private void deliverTrackballEvent(MotionEvent event, boolean sendDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002276 if (DEBUG_TRACKBALL) Log.v(TAG, "Motion event:" + event);
2277
Jeff Brown3915bb82010-11-05 15:02:16 -07002278 // If there is no view, then the event will not be handled.
2279 if (mView == null || !mAdded) {
2280 finishTrackballEvent(event, sendDone, false);
2281 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002282 }
2283
Jeff Brown3915bb82010-11-05 15:02:16 -07002284 // Deliver the trackball event to the view.
2285 if (mView.dispatchTrackballEvent(event)) {
2286 // If we reach this, we delivered a trackball event to mView and
2287 // mView consumed it. Because we will not translate the trackball
2288 // event into a key event, touch mode will not exit, so we exit
2289 // touch mode here.
2290 ensureTouchMode(false);
2291
2292 finishTrackballEvent(event, sendDone, true);
2293 mLastTrackballTime = Integer.MIN_VALUE;
2294 return;
2295 }
2296
2297 // Translate the trackball event into DPAD keys and try to deliver those.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002298 final TrackballAxis x = mTrackballAxisX;
2299 final TrackballAxis y = mTrackballAxisY;
2300
2301 long curTime = SystemClock.uptimeMillis();
Jeff Brown3915bb82010-11-05 15:02:16 -07002302 if ((mLastTrackballTime + MAX_TRACKBALL_DELAY) < curTime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002303 // It has been too long since the last movement,
2304 // so restart at the beginning.
2305 x.reset(0);
2306 y.reset(0);
2307 mLastTrackballTime = curTime;
2308 }
2309
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002310 final int action = event.getAction();
2311 final int metastate = event.getMetaState();
2312 switch (action) {
2313 case MotionEvent.ACTION_DOWN:
2314 x.reset(2);
2315 y.reset(2);
2316 deliverKeyEvent(new KeyEvent(curTime, curTime,
2317 KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_CENTER,
2318 0, metastate), false);
2319 break;
2320 case MotionEvent.ACTION_UP:
2321 x.reset(2);
2322 y.reset(2);
2323 deliverKeyEvent(new KeyEvent(curTime, curTime,
2324 KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_CENTER,
2325 0, metastate), false);
2326 break;
2327 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002328
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002329 if (DEBUG_TRACKBALL) Log.v(TAG, "TB X=" + x.position + " step="
2330 + x.step + " dir=" + x.dir + " acc=" + x.acceleration
2331 + " move=" + event.getX()
2332 + " / Y=" + y.position + " step="
2333 + y.step + " dir=" + y.dir + " acc=" + y.acceleration
2334 + " move=" + event.getY());
2335 final float xOff = x.collect(event.getX(), event.getEventTime(), "X");
2336 final float yOff = y.collect(event.getY(), event.getEventTime(), "Y");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002337
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002338 // Generate DPAD events based on the trackball movement.
2339 // We pick the axis that has moved the most as the direction of
2340 // the DPAD. When we generate DPAD events for one axis, then the
2341 // other axis is reset -- we don't want to perform DPAD jumps due
2342 // to slight movements in the trackball when making major movements
2343 // along the other axis.
2344 int keycode = 0;
2345 int movement = 0;
2346 float accel = 1;
2347 if (xOff > yOff) {
2348 movement = x.generate((2/event.getXPrecision()));
2349 if (movement != 0) {
2350 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_RIGHT
2351 : KeyEvent.KEYCODE_DPAD_LEFT;
2352 accel = x.acceleration;
2353 y.reset(2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002354 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002355 } else if (yOff > 0) {
2356 movement = y.generate((2/event.getYPrecision()));
2357 if (movement != 0) {
2358 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_DOWN
2359 : KeyEvent.KEYCODE_DPAD_UP;
2360 accel = y.acceleration;
2361 x.reset(2);
2362 }
2363 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002364
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002365 if (keycode != 0) {
2366 if (movement < 0) movement = -movement;
2367 int accelMovement = (int)(movement * accel);
2368 if (DEBUG_TRACKBALL) Log.v(TAG, "Move: movement=" + movement
2369 + " accelMovement=" + accelMovement
2370 + " accel=" + accel);
2371 if (accelMovement > movement) {
2372 if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: "
2373 + keycode);
2374 movement--;
2375 deliverKeyEvent(new KeyEvent(curTime, curTime,
2376 KeyEvent.ACTION_MULTIPLE, keycode,
2377 accelMovement-movement, metastate), false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002378 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002379 while (movement > 0) {
2380 if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: "
2381 + keycode);
2382 movement--;
2383 curTime = SystemClock.uptimeMillis();
2384 deliverKeyEvent(new KeyEvent(curTime, curTime,
2385 KeyEvent.ACTION_DOWN, keycode, 0, event.getMetaState()), false);
2386 deliverKeyEvent(new KeyEvent(curTime, curTime,
2387 KeyEvent.ACTION_UP, keycode, 0, metastate), false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002388 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002389 mLastTrackballTime = curTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002390 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002391
2392 // Unfortunately we can't tell whether the application consumed the keys, so
2393 // we always consider the trackball event handled.
2394 finishTrackballEvent(event, sendDone, true);
2395 }
2396
2397 private void finishTrackballEvent(MotionEvent event, boolean sendDone, boolean handled) {
2398 event.recycle();
2399 if (sendDone) {
2400 finishInputEvent(handled);
2401 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002402 }
2403
2404 /**
2405 * @param keyCode The key code
2406 * @return True if the key is directional.
2407 */
2408 static boolean isDirectional(int keyCode) {
2409 switch (keyCode) {
2410 case KeyEvent.KEYCODE_DPAD_LEFT:
2411 case KeyEvent.KEYCODE_DPAD_RIGHT:
2412 case KeyEvent.KEYCODE_DPAD_UP:
2413 case KeyEvent.KEYCODE_DPAD_DOWN:
2414 return true;
2415 }
2416 return false;
2417 }
2418
2419 /**
2420 * Returns true if this key is a keyboard key.
2421 * @param keyEvent The key event.
2422 * @return whether this key is a keyboard key.
2423 */
2424 private static boolean isKeyboardKey(KeyEvent keyEvent) {
2425 final int convertedKey = keyEvent.getUnicodeChar();
2426 return convertedKey > 0;
2427 }
2428
2429
2430
2431 /**
2432 * See if the key event means we should leave touch mode (and leave touch
2433 * mode if so).
2434 * @param event The key event.
2435 * @return Whether this key event should be consumed (meaning the act of
2436 * leaving touch mode alone is considered the event).
2437 */
2438 private boolean checkForLeavingTouchModeAndConsume(KeyEvent event) {
Adam Powell51a6bee2010-03-15 14:07:28 -07002439 final int action = event.getAction();
2440 if (action != KeyEvent.ACTION_DOWN && action != KeyEvent.ACTION_MULTIPLE) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002441 return false;
2442 }
2443 if ((event.getFlags()&KeyEvent.FLAG_KEEP_TOUCH_MODE) != 0) {
2444 return false;
2445 }
2446
2447 // only relevant if we are in touch mode
2448 if (!mAttachInfo.mInTouchMode) {
2449 return false;
2450 }
2451
2452 // if something like an edit text has focus and the user is typing,
2453 // leave touch mode
2454 //
2455 // note: the condition of not being a keyboard key is kind of a hacky
2456 // approximation of whether we think the focused view will want the
2457 // key; if we knew for sure whether the focused view would consume
2458 // the event, that would be better.
2459 if (isKeyboardKey(event) && mView != null && mView.hasFocus()) {
2460 mFocusedView = mView.findFocus();
2461 if ((mFocusedView instanceof ViewGroup)
2462 && ((ViewGroup) mFocusedView).getDescendantFocusability() ==
2463 ViewGroup.FOCUS_AFTER_DESCENDANTS) {
2464 // something has focus, but is holding it weakly as a container
2465 return false;
2466 }
2467 if (ensureTouchMode(false)) {
2468 throw new IllegalStateException("should not have changed focus "
2469 + "when leaving touch mode while a view has focus.");
2470 }
2471 return false;
2472 }
2473
2474 if (isDirectional(event.getKeyCode())) {
2475 // no view has focus, so we leave touch mode (and find something
2476 // to give focus to). the event is consumed if we were able to
2477 // find something to give focus to.
2478 return ensureTouchMode(false);
2479 }
2480 return false;
2481 }
2482
2483 /**
Romain Guy8506ab42009-06-11 17:35:47 -07002484 * log motion events
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002485 */
2486 private static void captureMotionLog(String subTag, MotionEvent ev) {
Romain Guy8506ab42009-06-11 17:35:47 -07002487 //check dynamic switch
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002488 if (ev == null ||
2489 SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_EVENT, 0) == 0) {
2490 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002491 }
Romain Guy8506ab42009-06-11 17:35:47 -07002492
2493 StringBuilder sb = new StringBuilder(subTag + ": ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002494 sb.append(ev.getDownTime()).append(',');
2495 sb.append(ev.getEventTime()).append(',');
2496 sb.append(ev.getAction()).append(',');
Romain Guy8506ab42009-06-11 17:35:47 -07002497 sb.append(ev.getX()).append(',');
2498 sb.append(ev.getY()).append(',');
2499 sb.append(ev.getPressure()).append(',');
2500 sb.append(ev.getSize()).append(',');
2501 sb.append(ev.getMetaState()).append(',');
2502 sb.append(ev.getXPrecision()).append(',');
2503 sb.append(ev.getYPrecision()).append(',');
2504 sb.append(ev.getDeviceId()).append(',');
2505 sb.append(ev.getEdgeFlags());
2506 Log.d(TAG, sb.toString());
2507 }
2508 /**
2509 * log motion events
2510 */
2511 private static void captureKeyLog(String subTag, KeyEvent ev) {
2512 //check dynamic switch
2513 if (ev == null ||
2514 SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_EVENT, 0) == 0) {
2515 return;
2516 }
2517 StringBuilder sb = new StringBuilder(subTag + ": ");
2518 sb.append(ev.getDownTime()).append(',');
2519 sb.append(ev.getEventTime()).append(',');
2520 sb.append(ev.getAction()).append(',');
2521 sb.append(ev.getKeyCode()).append(',');
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002522 sb.append(ev.getRepeatCount()).append(',');
2523 sb.append(ev.getMetaState()).append(',');
2524 sb.append(ev.getDeviceId()).append(',');
2525 sb.append(ev.getScanCode());
Romain Guy8506ab42009-06-11 17:35:47 -07002526 Log.d(TAG, sb.toString());
2527 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002528
2529 int enqueuePendingEvent(Object event, boolean sendDone) {
2530 int seq = mPendingEventSeq+1;
2531 if (seq < 0) seq = 0;
2532 mPendingEventSeq = seq;
2533 mPendingEvents.put(seq, event);
2534 return sendDone ? seq : -seq;
2535 }
2536
2537 Object retrievePendingEvent(int seq) {
2538 if (seq < 0) seq = -seq;
2539 Object event = mPendingEvents.get(seq);
2540 if (event != null) {
2541 mPendingEvents.remove(seq);
2542 }
2543 return event;
2544 }
Romain Guy8506ab42009-06-11 17:35:47 -07002545
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002546 private void deliverKeyEvent(KeyEvent event, boolean sendDone) {
Jeff Brown3915bb82010-11-05 15:02:16 -07002547 // If there is no view, then the event will not be handled.
2548 if (mView == null || !mAdded) {
2549 finishKeyEvent(event, sendDone, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002550 return;
2551 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002552
2553 if (LOCAL_LOGV) Log.v(TAG, "Dispatching key " + event + " to " + mView);
2554
2555 // Perform predispatching before the IME.
2556 if (mView.dispatchKeyEventPreIme(event)) {
2557 finishKeyEvent(event, sendDone, true);
2558 return;
2559 }
2560
2561 // Dispatch to the IME before propagating down the view hierarchy.
2562 // The IME will eventually call back into handleFinishedEvent.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002563 if (mLastWasImTarget) {
2564 InputMethodManager imm = InputMethodManager.peekInstance();
Jeff Brown3915bb82010-11-05 15:02:16 -07002565 if (imm != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002566 int seq = enqueuePendingEvent(event, sendDone);
2567 if (DEBUG_IMF) Log.v(TAG, "Sending key event to IME: seq="
2568 + seq + " event=" + event);
Jeff Brown3915bb82010-11-05 15:02:16 -07002569 imm.dispatchKeyEvent(mView.getContext(), seq, event, mInputMethodCallback);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002570 return;
2571 }
2572 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002573
2574 // Not dispatching to IME, continue with post IME actions.
2575 deliverKeyEventPostIme(event, sendDone);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002576 }
2577
Jeff Brown3915bb82010-11-05 15:02:16 -07002578 private void handleFinishedEvent(int seq, boolean handled) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002579 final KeyEvent event = (KeyEvent)retrievePendingEvent(seq);
2580 if (DEBUG_IMF) Log.v(TAG, "IME finished event: seq=" + seq
2581 + " handled=" + handled + " event=" + event);
2582 if (event != null) {
2583 final boolean sendDone = seq >= 0;
Jeff Brown3915bb82010-11-05 15:02:16 -07002584 if (handled) {
2585 finishKeyEvent(event, sendDone, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002586 } else {
Jeff Brown3915bb82010-11-05 15:02:16 -07002587 deliverKeyEventPostIme(event, sendDone);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002588 }
2589 }
2590 }
Romain Guy8506ab42009-06-11 17:35:47 -07002591
Jeff Brown3915bb82010-11-05 15:02:16 -07002592 private void deliverKeyEventPostIme(KeyEvent event, boolean sendDone) {
2593 // If the view went away, then the event will not be handled.
2594 if (mView == null || !mAdded) {
2595 finishKeyEvent(event, sendDone, false);
2596 return;
2597 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002598
Jeff Brown3915bb82010-11-05 15:02:16 -07002599 // If the key's purpose is to exit touch mode then we consume it and consider it handled.
2600 if (checkForLeavingTouchModeAndConsume(event)) {
2601 finishKeyEvent(event, sendDone, true);
2602 return;
2603 }
Romain Guy8506ab42009-06-11 17:35:47 -07002604
Jeff Brown3915bb82010-11-05 15:02:16 -07002605 if (Config.LOGV) {
2606 captureKeyLog("captureDispatchKeyEvent", event);
2607 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002608
Jeff Brown90655042010-12-02 13:50:46 -08002609 // Make sure the fallback event policy sees all keys that will be delivered to the
2610 // view hierarchy.
2611 mFallbackEventHandler.preDispatchKeyEvent(event);
2612
Jeff Brown3915bb82010-11-05 15:02:16 -07002613 // Deliver the key to the view hierarchy.
2614 if (mView.dispatchKeyEvent(event)) {
2615 finishKeyEvent(event, sendDone, true);
2616 return;
2617 }
Joe Onorato86f67862010-11-05 18:57:34 -07002618
Jeff Brown3915bb82010-11-05 15:02:16 -07002619 // Apply the fallback event policy.
2620 if (mFallbackEventHandler.dispatchKeyEvent(event)) {
2621 finishKeyEvent(event, sendDone, true);
2622 return;
2623 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002624
Jeff Brown3915bb82010-11-05 15:02:16 -07002625 // Handle automatic focus changes.
2626 if (event.getAction() == KeyEvent.ACTION_DOWN) {
2627 int direction = 0;
2628 switch (event.getKeyCode()) {
2629 case KeyEvent.KEYCODE_DPAD_LEFT:
2630 direction = View.FOCUS_LEFT;
2631 break;
2632 case KeyEvent.KEYCODE_DPAD_RIGHT:
2633 direction = View.FOCUS_RIGHT;
2634 break;
2635 case KeyEvent.KEYCODE_DPAD_UP:
2636 direction = View.FOCUS_UP;
2637 break;
2638 case KeyEvent.KEYCODE_DPAD_DOWN:
2639 direction = View.FOCUS_DOWN;
2640 break;
2641 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002642
Jeff Brown3915bb82010-11-05 15:02:16 -07002643 if (direction != 0) {
2644 View focused = mView != null ? mView.findFocus() : null;
2645 if (focused != null) {
2646 View v = focused.focusSearch(direction);
2647 if (v != null && v != focused) {
2648 // do the math the get the interesting rect
2649 // of previous focused into the coord system of
2650 // newly focused view
2651 focused.getFocusedRect(mTempRect);
2652 if (mView instanceof ViewGroup) {
2653 ((ViewGroup) mView).offsetDescendantRectToMyCoords(
2654 focused, mTempRect);
2655 ((ViewGroup) mView).offsetRectIntoDescendantCoords(
2656 v, mTempRect);
2657 }
2658 if (v.requestFocus(direction, mTempRect)) {
2659 playSoundEffect(
2660 SoundEffectConstants.getContantForFocusDirection(direction));
2661 finishKeyEvent(event, sendDone, true);
2662 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002663 }
2664 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002665
2666 // Give the focused view a last chance to handle the dpad key.
2667 if (mView.dispatchUnhandledMove(focused, direction)) {
2668 finishKeyEvent(event, sendDone, true);
2669 return;
2670 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002671 }
2672 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002673 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002674
Jeff Brown3915bb82010-11-05 15:02:16 -07002675 // Key was unhandled.
2676 finishKeyEvent(event, sendDone, false);
2677 }
2678
2679 private void finishKeyEvent(KeyEvent event, boolean sendDone, boolean handled) {
2680 if (sendDone) {
2681 finishInputEvent(handled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002682 }
2683 }
2684
Christopher Tatea53146c2010-09-07 11:57:52 -07002685 /* drag/drop */
Christopher Tate407b4e92010-11-30 17:14:08 -08002686 void setLocalDragState(Object obj) {
2687 mLocalDragState = obj;
2688 }
2689
Christopher Tatea53146c2010-09-07 11:57:52 -07002690 private void handleDragEvent(DragEvent event) {
2691 // From the root, only drag start/end/location are dispatched. entered/exited
2692 // are determined and dispatched by the viewgroup hierarchy, who then report
2693 // that back here for ultimate reporting back to the framework.
2694 if (mView != null && mAdded) {
2695 final int what = event.mAction;
2696
2697 if (what == DragEvent.ACTION_DRAG_EXITED) {
2698 // A direct EXITED event means that the window manager knows we've just crossed
2699 // a window boundary, so the current drag target within this one must have
2700 // just been exited. Send it the usual notifications and then we're done
2701 // for now.
Chris Tate9d1ab882010-11-02 15:55:39 -07002702 mView.dispatchDragEvent(event);
Christopher Tatea53146c2010-09-07 11:57:52 -07002703 } else {
2704 // Cache the drag description when the operation starts, then fill it in
2705 // on subsequent calls as a convenience
2706 if (what == DragEvent.ACTION_DRAG_STARTED) {
Chris Tate9d1ab882010-11-02 15:55:39 -07002707 mCurrentDragView = null; // Start the current-recipient tracking
Christopher Tatea53146c2010-09-07 11:57:52 -07002708 mDragDescription = event.mClipDescription;
2709 } else {
2710 event.mClipDescription = mDragDescription;
2711 }
2712
2713 // For events with a [screen] location, translate into window coordinates
2714 if ((what == DragEvent.ACTION_DRAG_LOCATION) || (what == DragEvent.ACTION_DROP)) {
2715 mDragPoint.set(event.mX, event.mY);
2716 if (mTranslator != null) {
2717 mTranslator.translatePointInScreenToAppWindow(mDragPoint);
2718 }
2719
2720 if (mCurScrollY != 0) {
2721 mDragPoint.offset(0, mCurScrollY);
2722 }
2723
2724 event.mX = mDragPoint.x;
2725 event.mY = mDragPoint.y;
2726 }
2727
2728 // Remember who the current drag target is pre-dispatch
2729 final View prevDragView = mCurrentDragView;
2730
2731 // Now dispatch the drag/drop event
Chris Tated4533f12010-10-19 15:15:08 -07002732 boolean result = mView.dispatchDragEvent(event);
Christopher Tatea53146c2010-09-07 11:57:52 -07002733
2734 // If we changed apparent drag target, tell the OS about it
2735 if (prevDragView != mCurrentDragView) {
2736 try {
2737 if (prevDragView != null) {
2738 sWindowSession.dragRecipientExited(mWindow);
2739 }
2740 if (mCurrentDragView != null) {
2741 sWindowSession.dragRecipientEntered(mWindow);
2742 }
2743 } catch (RemoteException e) {
2744 Slog.e(TAG, "Unable to note drag target change");
2745 }
Christopher Tatea53146c2010-09-07 11:57:52 -07002746 }
Chris Tated4533f12010-10-19 15:15:08 -07002747
Christopher Tate407b4e92010-11-30 17:14:08 -08002748 // Report the drop result when we're done
Chris Tated4533f12010-10-19 15:15:08 -07002749 if (what == DragEvent.ACTION_DROP) {
2750 try {
2751 Log.i(TAG, "Reporting drop result: " + result);
2752 sWindowSession.reportDropResult(mWindow, result);
2753 } catch (RemoteException e) {
2754 Log.e(TAG, "Unable to report drop result");
2755 }
2756 }
Christopher Tate407b4e92010-11-30 17:14:08 -08002757
2758 // When the drag operation ends, release any local state object
2759 // that may have been in use
2760 if (what == DragEvent.ACTION_DRAG_ENDED) {
2761 setLocalDragState(null);
2762 }
Christopher Tatea53146c2010-09-07 11:57:52 -07002763 }
2764 }
2765 event.recycle();
2766 }
2767
Christopher Tate2c095f32010-10-04 14:13:40 -07002768 public void getLastTouchPoint(Point outLocation) {
2769 outLocation.x = (int) mLastTouchPoint.x;
2770 outLocation.y = (int) mLastTouchPoint.y;
2771 }
2772
Chris Tate9d1ab882010-11-02 15:55:39 -07002773 public void setDragFocus(View newDragTarget) {
Christopher Tatea53146c2010-09-07 11:57:52 -07002774 if (mCurrentDragView != newDragTarget) {
Chris Tate048691c2010-10-12 17:39:18 -07002775 mCurrentDragView = newDragTarget;
Christopher Tatea53146c2010-09-07 11:57:52 -07002776 }
Christopher Tatea53146c2010-09-07 11:57:52 -07002777 }
2778
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002779 private AudioManager getAudioManager() {
2780 if (mView == null) {
2781 throw new IllegalStateException("getAudioManager called when there is no mView");
2782 }
2783 if (mAudioManager == null) {
2784 mAudioManager = (AudioManager) mView.getContext().getSystemService(Context.AUDIO_SERVICE);
2785 }
2786 return mAudioManager;
2787 }
2788
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002789 private int relayoutWindow(WindowManager.LayoutParams params, int viewVisibility,
2790 boolean insetsPending) throws RemoteException {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002791
2792 float appScale = mAttachInfo.mApplicationScale;
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002793 boolean restore = false;
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002794 if (params != null && mTranslator != null) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07002795 restore = true;
2796 params.backup();
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002797 mTranslator.translateWindowLayout(params);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002798 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002799 if (params != null) {
2800 if (DBG) Log.d(TAG, "WindowLayout in layoutWindow:" + params);
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002801 }
Dianne Hackborn694f79b2010-03-17 19:44:59 -07002802 mPendingConfiguration.seq = 0;
Dianne Hackbornf123e492010-09-24 11:16:23 -07002803 //Log.d(TAG, ">>>>>> CALLING relayout");
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002804 int relayoutResult = sWindowSession.relayout(
2805 mWindow, params,
Dianne Hackborn189ee182010-12-02 21:48:53 -08002806 (int) (mView.getMeasuredWidth() * appScale + 0.5f),
2807 (int) (mView.getMeasuredHeight() * appScale + 0.5f),
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002808 viewVisibility, insetsPending, mWinFrame,
Dianne Hackborn694f79b2010-03-17 19:44:59 -07002809 mPendingContentInsets, mPendingVisibleInsets,
2810 mPendingConfiguration, mSurface);
Dianne Hackbornf123e492010-09-24 11:16:23 -07002811 //Log.d(TAG, "<<<<<< BACK FROM relayout");
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002812 if (restore) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07002813 params.restore();
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002814 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002815
2816 if (mTranslator != null) {
2817 mTranslator.translateRectInScreenToAppWinFrame(mWinFrame);
2818 mTranslator.translateRectInScreenToAppWindow(mPendingContentInsets);
2819 mTranslator.translateRectInScreenToAppWindow(mPendingVisibleInsets);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002820 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002821 return relayoutResult;
2822 }
Romain Guy8506ab42009-06-11 17:35:47 -07002823
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002824 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002825 * {@inheritDoc}
2826 */
2827 public void playSoundEffect(int effectId) {
2828 checkThread();
2829
Jean-Michel Trivi13b18fd2010-05-05 09:18:15 -07002830 try {
2831 final AudioManager audioManager = getAudioManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002832
Jean-Michel Trivi13b18fd2010-05-05 09:18:15 -07002833 switch (effectId) {
2834 case SoundEffectConstants.CLICK:
2835 audioManager.playSoundEffect(AudioManager.FX_KEY_CLICK);
2836 return;
2837 case SoundEffectConstants.NAVIGATION_DOWN:
2838 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_DOWN);
2839 return;
2840 case SoundEffectConstants.NAVIGATION_LEFT:
2841 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_LEFT);
2842 return;
2843 case SoundEffectConstants.NAVIGATION_RIGHT:
2844 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_RIGHT);
2845 return;
2846 case SoundEffectConstants.NAVIGATION_UP:
2847 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_UP);
2848 return;
2849 default:
2850 throw new IllegalArgumentException("unknown effect id " + effectId +
2851 " not defined in " + SoundEffectConstants.class.getCanonicalName());
2852 }
2853 } catch (IllegalStateException e) {
2854 // Exception thrown by getAudioManager() when mView is null
2855 Log.e(TAG, "FATAL EXCEPTION when attempting to play sound effect: " + e);
2856 e.printStackTrace();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002857 }
2858 }
2859
2860 /**
2861 * {@inheritDoc}
2862 */
2863 public boolean performHapticFeedback(int effectId, boolean always) {
2864 try {
2865 return sWindowSession.performHapticFeedback(mWindow, effectId, always);
2866 } catch (RemoteException e) {
2867 return false;
2868 }
2869 }
2870
2871 /**
2872 * {@inheritDoc}
2873 */
2874 public View focusSearch(View focused, int direction) {
2875 checkThread();
2876 if (!(mView instanceof ViewGroup)) {
2877 return null;
2878 }
2879 return FocusFinder.getInstance().findNextFocus((ViewGroup) mView, focused, direction);
2880 }
2881
2882 public void debug() {
2883 mView.debug();
2884 }
2885
2886 public void die(boolean immediate) {
Dianne Hackborn94d69142009-09-28 22:14:42 -07002887 if (immediate) {
2888 doDie();
2889 } else {
2890 sendEmptyMessage(DIE);
2891 }
2892 }
2893
2894 void doDie() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002895 checkThread();
Jeff Brownb75fa302010-07-15 23:47:29 -07002896 if (LOCAL_LOGV) Log.v(TAG, "DIE in " + this + " of " + mSurface);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002897 synchronized (this) {
2898 if (mAdded && !mFirst) {
Romain Guy29d89972010-09-22 16:10:57 -07002899 destroyHardwareRenderer();
2900
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002901 int viewVisibility = mView.getVisibility();
2902 boolean viewVisibilityChanged = mViewVisibility != viewVisibility;
2903 if (mWindowAttributesChanged || viewVisibilityChanged) {
2904 // If layout params have been changed, first give them
2905 // to the window manager to make sure it has the correct
2906 // animation info.
2907 try {
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002908 if ((relayoutWindow(mWindowAttributes, viewVisibility, false)
2909 & WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002910 sWindowSession.finishDrawing(mWindow);
2911 }
2912 } catch (RemoteException e) {
2913 }
2914 }
2915
Dianne Hackborn0586a1b2009-09-06 21:08:27 -07002916 mSurface.release();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002917 }
2918 if (mAdded) {
2919 mAdded = false;
Dianne Hackborn94d69142009-09-28 22:14:42 -07002920 dispatchDetachedFromWindow();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002921 }
2922 }
2923 }
2924
Romain Guy29d89972010-09-22 16:10:57 -07002925 private void destroyHardwareRenderer() {
Romain Guyb051e892010-09-28 19:09:36 -07002926 if (mAttachInfo.mHardwareRenderer != null) {
2927 mAttachInfo.mHardwareRenderer.destroy(true);
2928 mAttachInfo.mHardwareRenderer = null;
Romain Guy29d89972010-09-22 16:10:57 -07002929 mAttachInfo.mHardwareAccelerated = false;
2930 }
2931 }
2932
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002933 public void dispatchFinishedEvent(int seq, boolean handled) {
2934 Message msg = obtainMessage(FINISHED_EVENT);
2935 msg.arg1 = seq;
2936 msg.arg2 = handled ? 1 : 0;
2937 sendMessage(msg);
2938 }
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002939
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002940 public void dispatchResized(int w, int h, Rect coveredInsets,
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002941 Rect visibleInsets, boolean reportDraw, Configuration newConfig) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002942 if (DEBUG_LAYOUT) Log.v(TAG, "Resizing " + this + ": w=" + w
2943 + " h=" + h + " coveredInsets=" + coveredInsets.toShortString()
2944 + " visibleInsets=" + visibleInsets.toShortString()
2945 + " reportDraw=" + reportDraw);
2946 Message msg = obtainMessage(reportDraw ? RESIZED_REPORT :RESIZED);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002947 if (mTranslator != null) {
2948 mTranslator.translateRectInScreenToAppWindow(coveredInsets);
2949 mTranslator.translateRectInScreenToAppWindow(visibleInsets);
2950 w *= mTranslator.applicationInvertedScale;
2951 h *= mTranslator.applicationInvertedScale;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002952 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002953 msg.arg1 = w;
2954 msg.arg2 = h;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002955 ResizedInfo ri = new ResizedInfo();
2956 ri.coveredInsets = new Rect(coveredInsets);
2957 ri.visibleInsets = new Rect(visibleInsets);
2958 ri.newConfig = newConfig;
2959 msg.obj = ri;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002960 sendMessage(msg);
2961 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002962
Jeff Brown3915bb82010-11-05 15:02:16 -07002963 private InputQueue.FinishedCallback mFinishedCallback;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002964
2965 private final InputHandler mInputHandler = new InputHandler() {
Jeff Brown3915bb82010-11-05 15:02:16 -07002966 public void handleKey(KeyEvent event, InputQueue.FinishedCallback finishedCallback) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07002967 startInputEvent(finishedCallback);
Jeff Brown92ff1dd2010-08-11 16:16:06 -07002968 dispatchKey(event, true);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002969 }
2970
Jeff Brown3915bb82010-11-05 15:02:16 -07002971 public void handleMotion(MotionEvent event, InputQueue.FinishedCallback finishedCallback) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07002972 startInputEvent(finishedCallback);
2973 dispatchMotion(event, true);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002974 }
2975 };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002976
2977 public void dispatchKey(KeyEvent event) {
Jeff Brown92ff1dd2010-08-11 16:16:06 -07002978 dispatchKey(event, false);
2979 }
2980
2981 private void dispatchKey(KeyEvent event, boolean sendDone) {
2982 //noinspection ConstantConditions
2983 if (false && event.getAction() == KeyEvent.ACTION_DOWN) {
2984 if (event.getKeyCode() == KeyEvent.KEYCODE_CAMERA) {
Romain Guy812ccbe2010-06-01 14:07:24 -07002985 if (DBG) Log.d("keydisp", "===================================================");
2986 if (DBG) Log.d("keydisp", "Focused view Hierarchy is:");
2987
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002988 debug();
2989
Romain Guy812ccbe2010-06-01 14:07:24 -07002990 if (DBG) Log.d("keydisp", "===================================================");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002991 }
2992 }
2993
2994 Message msg = obtainMessage(DISPATCH_KEY);
2995 msg.obj = event;
Jeff Brown92ff1dd2010-08-11 16:16:06 -07002996 msg.arg1 = sendDone ? 1 : 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002997
2998 if (LOCAL_LOGV) Log.v(
Jeff Brownc5ed5912010-07-14 18:48:53 -07002999 TAG, "sending key " + event + " to " + mView);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003000
3001 sendMessageAtTime(msg, event.getEventTime());
3002 }
Jeff Brownc5ed5912010-07-14 18:48:53 -07003003
3004 public void dispatchMotion(MotionEvent event) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07003005 dispatchMotion(event, false);
3006 }
3007
3008 private void dispatchMotion(MotionEvent event, boolean sendDone) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07003009 int source = event.getSource();
3010 if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07003011 dispatchPointer(event, sendDone);
Jeff Brownc5ed5912010-07-14 18:48:53 -07003012 } else if ((source & InputDevice.SOURCE_CLASS_TRACKBALL) != 0) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07003013 dispatchTrackball(event, sendDone);
Jeff Brownc5ed5912010-07-14 18:48:53 -07003014 } else {
3015 // TODO
3016 Log.v(TAG, "Dropping unsupported motion event (unimplemented): " + event);
Jeff Brown93ed4e32010-09-23 13:51:48 -07003017 if (sendDone) {
Jeff Brown3915bb82010-11-05 15:02:16 -07003018 finishInputEvent(false);
Jeff Brown93ed4e32010-09-23 13:51:48 -07003019 }
Jeff Brownc5ed5912010-07-14 18:48:53 -07003020 }
3021 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003022
Jeff Brown00fa7bd2010-07-02 15:37:36 -07003023 public void dispatchPointer(MotionEvent event) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07003024 dispatchPointer(event, false);
3025 }
3026
3027 private void dispatchPointer(MotionEvent event, boolean sendDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003028 Message msg = obtainMessage(DISPATCH_POINTER);
3029 msg.obj = event;
Jeff Brown93ed4e32010-09-23 13:51:48 -07003030 msg.arg1 = sendDone ? 1 : 0;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07003031 sendMessageAtTime(msg, event.getEventTime());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003032 }
3033
Jeff Brown00fa7bd2010-07-02 15:37:36 -07003034 public void dispatchTrackball(MotionEvent event) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07003035 dispatchTrackball(event, false);
3036 }
3037
3038 private void dispatchTrackball(MotionEvent event, boolean sendDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003039 Message msg = obtainMessage(DISPATCH_TRACKBALL);
3040 msg.obj = event;
Jeff Brown93ed4e32010-09-23 13:51:48 -07003041 msg.arg1 = sendDone ? 1 : 0;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07003042 sendMessageAtTime(msg, event.getEventTime());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003043 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07003044
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003045 public void dispatchAppVisibility(boolean visible) {
3046 Message msg = obtainMessage(DISPATCH_APP_VISIBILITY);
3047 msg.arg1 = visible ? 1 : 0;
3048 sendMessage(msg);
3049 }
3050
3051 public void dispatchGetNewSurface() {
3052 Message msg = obtainMessage(DISPATCH_GET_NEW_SURFACE);
3053 sendMessage(msg);
3054 }
3055
3056 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
3057 Message msg = Message.obtain();
3058 msg.what = WINDOW_FOCUS_CHANGED;
3059 msg.arg1 = hasFocus ? 1 : 0;
3060 msg.arg2 = inTouchMode ? 1 : 0;
3061 sendMessage(msg);
3062 }
3063
Dianne Hackbornffa42482009-09-23 22:20:11 -07003064 public void dispatchCloseSystemDialogs(String reason) {
3065 Message msg = Message.obtain();
3066 msg.what = CLOSE_SYSTEM_DIALOGS;
3067 msg.obj = reason;
3068 sendMessage(msg);
3069 }
Christopher Tatea53146c2010-09-07 11:57:52 -07003070
3071 public void dispatchDragEvent(DragEvent event) {
Chris Tate91e9bb32010-10-12 12:58:43 -07003072 final int what;
3073 if (event.getAction() == DragEvent.ACTION_DRAG_LOCATION) {
3074 what = DISPATCH_DRAG_LOCATION_EVENT;
3075 removeMessages(what);
3076 } else {
3077 what = DISPATCH_DRAG_EVENT;
3078 }
Christopher Tate407b4e92010-11-30 17:14:08 -08003079 event.mLocalState = mLocalDragState; // only present when this app called startDrag()
Chris Tate91e9bb32010-10-12 12:58:43 -07003080 Message msg = obtainMessage(what, event);
Christopher Tatea53146c2010-09-07 11:57:52 -07003081 sendMessage(msg);
3082 }
3083
svetoslavganov75986cf2009-05-14 22:28:01 -07003084 /**
3085 * The window is getting focus so if there is anything focused/selected
3086 * send an {@link AccessibilityEvent} to announce that.
3087 */
3088 private void sendAccessibilityEvents() {
3089 if (!AccessibilityManager.getInstance(mView.getContext()).isEnabled()) {
3090 return;
3091 }
3092 mView.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
3093 View focusedView = mView.findFocus();
3094 if (focusedView != null && focusedView != mView) {
3095 focusedView.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
3096 }
3097 }
3098
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003099 public boolean showContextMenuForChild(View originalView) {
3100 return false;
3101 }
3102
Adam Powell6e346362010-07-23 10:18:23 -07003103 public ActionMode startActionModeForChild(View originalView, ActionMode.Callback callback) {
3104 return null;
3105 }
3106
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003107 public void createContextMenu(ContextMenu menu) {
3108 }
3109
3110 public void childDrawableStateChanged(View child) {
3111 }
3112
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003113 void checkThread() {
3114 if (mThread != Thread.currentThread()) {
3115 throw new CalledFromWrongThreadException(
3116 "Only the original thread that created a view hierarchy can touch its views.");
3117 }
3118 }
3119
3120 public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
3121 // ViewRoot never intercepts touch event, so this can be a no-op
3122 }
3123
3124 public boolean requestChildRectangleOnScreen(View child, Rect rectangle,
3125 boolean immediate) {
3126 return scrollToRectOrFocus(rectangle, immediate);
3127 }
Romain Guy8506ab42009-06-11 17:35:47 -07003128
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07003129 class TakenSurfaceHolder extends BaseSurfaceHolder {
3130 @Override
3131 public boolean onAllowLockCanvas() {
3132 return mDrawingAllowed;
3133 }
3134
3135 @Override
3136 public void onRelayoutContainer() {
3137 // Not currently interesting -- from changing between fixed and layout size.
3138 }
3139
3140 public void setFormat(int format) {
3141 ((RootViewSurfaceTaker)mView).setSurfaceFormat(format);
3142 }
3143
3144 public void setType(int type) {
3145 ((RootViewSurfaceTaker)mView).setSurfaceType(type);
3146 }
3147
3148 @Override
3149 public void onUpdateSurface() {
3150 // We take care of format and type changes on our own.
3151 throw new IllegalStateException("Shouldn't be here");
3152 }
3153
3154 public boolean isCreating() {
3155 return mIsCreating;
3156 }
3157
3158 @Override
3159 public void setFixedSize(int width, int height) {
3160 throw new UnsupportedOperationException(
3161 "Currently only support sizing from layout");
3162 }
3163
3164 public void setKeepScreenOn(boolean screenOn) {
3165 ((RootViewSurfaceTaker)mView).setSurfaceKeepScreenOn(screenOn);
3166 }
3167 }
3168
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003169 static class InputMethodCallback extends IInputMethodCallback.Stub {
3170 private WeakReference<ViewRoot> mViewRoot;
3171
3172 public InputMethodCallback(ViewRoot viewRoot) {
3173 mViewRoot = new WeakReference<ViewRoot>(viewRoot);
3174 }
Romain Guy8506ab42009-06-11 17:35:47 -07003175
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003176 public void finishedEvent(int seq, boolean handled) {
3177 final ViewRoot viewRoot = mViewRoot.get();
3178 if (viewRoot != null) {
3179 viewRoot.dispatchFinishedEvent(seq, handled);
3180 }
3181 }
3182
3183 public void sessionCreated(IInputMethodSession session) throws RemoteException {
3184 // Stub -- not for use in the client.
3185 }
3186 }
Romain Guy8506ab42009-06-11 17:35:47 -07003187
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003188 static class W extends IWindow.Stub {
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07003189 private final WeakReference<ViewRoot> mViewRoot;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003190
Romain Guyfb8b7632010-08-23 21:05:08 -07003191 W(ViewRoot viewRoot) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003192 mViewRoot = new WeakReference<ViewRoot>(viewRoot);
3193 }
3194
Romain Guyfb8b7632010-08-23 21:05:08 -07003195 public void resized(int w, int h, Rect coveredInsets, Rect visibleInsets,
3196 boolean reportDraw, Configuration newConfig) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003197 final ViewRoot viewRoot = mViewRoot.get();
3198 if (viewRoot != null) {
Romain Guyfb8b7632010-08-23 21:05:08 -07003199 viewRoot.dispatchResized(w, h, coveredInsets, visibleInsets, reportDraw, newConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003200 }
3201 }
3202
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003203 public void dispatchAppVisibility(boolean visible) {
3204 final ViewRoot viewRoot = mViewRoot.get();
3205 if (viewRoot != null) {
3206 viewRoot.dispatchAppVisibility(visible);
3207 }
3208 }
3209
3210 public void dispatchGetNewSurface() {
3211 final ViewRoot viewRoot = mViewRoot.get();
3212 if (viewRoot != null) {
3213 viewRoot.dispatchGetNewSurface();
3214 }
3215 }
3216
3217 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
3218 final ViewRoot viewRoot = mViewRoot.get();
3219 if (viewRoot != null) {
3220 viewRoot.windowFocusChanged(hasFocus, inTouchMode);
3221 }
3222 }
3223
3224 private static int checkCallingPermission(String permission) {
3225 if (!Process.supportsProcesses()) {
3226 return PackageManager.PERMISSION_GRANTED;
3227 }
3228
3229 try {
3230 return ActivityManagerNative.getDefault().checkPermission(
3231 permission, Binder.getCallingPid(), Binder.getCallingUid());
3232 } catch (RemoteException e) {
3233 return PackageManager.PERMISSION_DENIED;
3234 }
3235 }
3236
3237 public void executeCommand(String command, String parameters, ParcelFileDescriptor out) {
3238 final ViewRoot viewRoot = mViewRoot.get();
3239 if (viewRoot != null) {
3240 final View view = viewRoot.mView;
3241 if (view != null) {
3242 if (checkCallingPermission(Manifest.permission.DUMP) !=
3243 PackageManager.PERMISSION_GRANTED) {
3244 throw new SecurityException("Insufficient permissions to invoke"
3245 + " executeCommand() from pid=" + Binder.getCallingPid()
3246 + ", uid=" + Binder.getCallingUid());
3247 }
3248
3249 OutputStream clientStream = null;
3250 try {
3251 clientStream = new ParcelFileDescriptor.AutoCloseOutputStream(out);
3252 ViewDebug.dispatchCommand(view, command, parameters, clientStream);
3253 } catch (IOException e) {
3254 e.printStackTrace();
3255 } finally {
3256 if (clientStream != null) {
3257 try {
3258 clientStream.close();
3259 } catch (IOException e) {
3260 e.printStackTrace();
3261 }
3262 }
3263 }
3264 }
3265 }
3266 }
Dianne Hackborn72c82ab2009-08-11 21:13:54 -07003267
Dianne Hackbornffa42482009-09-23 22:20:11 -07003268 public void closeSystemDialogs(String reason) {
3269 final ViewRoot viewRoot = mViewRoot.get();
3270 if (viewRoot != null) {
3271 viewRoot.dispatchCloseSystemDialogs(reason);
3272 }
3273 }
3274
Marco Nelissenbf6956b2009-11-09 15:21:13 -08003275 public void dispatchWallpaperOffsets(float x, float y, float xStep, float yStep,
3276 boolean sync) {
Dianne Hackborn19382ac2009-09-11 21:13:37 -07003277 if (sync) {
3278 try {
3279 sWindowSession.wallpaperOffsetsComplete(asBinder());
3280 } catch (RemoteException e) {
3281 }
3282 }
Dianne Hackborn72c82ab2009-08-11 21:13:54 -07003283 }
Dianne Hackborn75804932009-10-20 20:15:20 -07003284
3285 public void dispatchWallpaperCommand(String action, int x, int y,
3286 int z, Bundle extras, boolean sync) {
3287 if (sync) {
3288 try {
3289 sWindowSession.wallpaperCommandComplete(asBinder(), null);
3290 } catch (RemoteException e) {
3291 }
3292 }
3293 }
Christopher Tatea53146c2010-09-07 11:57:52 -07003294
3295 /* Drag/drop */
3296 public void dispatchDragEvent(DragEvent event) {
3297 final ViewRoot viewRoot = mViewRoot.get();
3298 if (viewRoot != null) {
3299 viewRoot.dispatchDragEvent(event);
3300 }
3301 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003302 }
3303
3304 /**
3305 * Maintains state information for a single trackball axis, generating
3306 * discrete (DPAD) movements based on raw trackball motion.
3307 */
3308 static final class TrackballAxis {
3309 /**
3310 * The maximum amount of acceleration we will apply.
3311 */
3312 static final float MAX_ACCELERATION = 20;
Romain Guy8506ab42009-06-11 17:35:47 -07003313
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003314 /**
3315 * The maximum amount of time (in milliseconds) between events in order
3316 * for us to consider the user to be doing fast trackball movements,
3317 * and thus apply an acceleration.
3318 */
3319 static final long FAST_MOVE_TIME = 150;
Romain Guy8506ab42009-06-11 17:35:47 -07003320
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003321 /**
3322 * Scaling factor to the time (in milliseconds) between events to how
3323 * much to multiple/divide the current acceleration. When movement
3324 * is < FAST_MOVE_TIME this multiplies the acceleration; when >
3325 * FAST_MOVE_TIME it divides it.
3326 */
3327 static final float ACCEL_MOVE_SCALING_FACTOR = (1.0f/40);
Romain Guy8506ab42009-06-11 17:35:47 -07003328
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003329 float position;
3330 float absPosition;
3331 float acceleration = 1;
3332 long lastMoveTime = 0;
3333 int step;
3334 int dir;
3335 int nonAccelMovement;
3336
3337 void reset(int _step) {
3338 position = 0;
3339 acceleration = 1;
3340 lastMoveTime = 0;
3341 step = _step;
3342 dir = 0;
3343 }
3344
3345 /**
3346 * Add trackball movement into the state. If the direction of movement
3347 * has been reversed, the state is reset before adding the
3348 * movement (so that you don't have to compensate for any previously
3349 * collected movement before see the result of the movement in the
3350 * new direction).
3351 *
3352 * @return Returns the absolute value of the amount of movement
3353 * collected so far.
3354 */
3355 float collect(float off, long time, String axis) {
3356 long normTime;
3357 if (off > 0) {
3358 normTime = (long)(off * FAST_MOVE_TIME);
3359 if (dir < 0) {
3360 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to positive!");
3361 position = 0;
3362 step = 0;
3363 acceleration = 1;
3364 lastMoveTime = 0;
3365 }
3366 dir = 1;
3367 } else if (off < 0) {
3368 normTime = (long)((-off) * FAST_MOVE_TIME);
3369 if (dir > 0) {
3370 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to negative!");
3371 position = 0;
3372 step = 0;
3373 acceleration = 1;
3374 lastMoveTime = 0;
3375 }
3376 dir = -1;
3377 } else {
3378 normTime = 0;
3379 }
Romain Guy8506ab42009-06-11 17:35:47 -07003380
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003381 // The number of milliseconds between each movement that is
3382 // considered "normal" and will not result in any acceleration
3383 // or deceleration, scaled by the offset we have here.
3384 if (normTime > 0) {
3385 long delta = time - lastMoveTime;
3386 lastMoveTime = time;
3387 float acc = acceleration;
3388 if (delta < normTime) {
3389 // The user is scrolling rapidly, so increase acceleration.
3390 float scale = (normTime-delta) * ACCEL_MOVE_SCALING_FACTOR;
3391 if (scale > 1) acc *= scale;
3392 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " accelerate: off="
3393 + off + " normTime=" + normTime + " delta=" + delta
3394 + " scale=" + scale + " acc=" + acc);
3395 acceleration = acc < MAX_ACCELERATION ? acc : MAX_ACCELERATION;
3396 } else {
3397 // The user is scrolling slowly, so decrease acceleration.
3398 float scale = (delta-normTime) * ACCEL_MOVE_SCALING_FACTOR;
3399 if (scale > 1) acc /= scale;
3400 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " deccelerate: off="
3401 + off + " normTime=" + normTime + " delta=" + delta
3402 + " scale=" + scale + " acc=" + acc);
3403 acceleration = acc > 1 ? acc : 1;
3404 }
3405 }
3406 position += off;
3407 return (absPosition = Math.abs(position));
3408 }
3409
3410 /**
3411 * Generate the number of discrete movement events appropriate for
3412 * the currently collected trackball movement.
3413 *
3414 * @param precision The minimum movement required to generate the
3415 * first discrete movement.
3416 *
3417 * @return Returns the number of discrete movements, either positive
3418 * or negative, or 0 if there is not enough trackball movement yet
3419 * for a discrete movement.
3420 */
3421 int generate(float precision) {
3422 int movement = 0;
3423 nonAccelMovement = 0;
3424 do {
3425 final int dir = position >= 0 ? 1 : -1;
3426 switch (step) {
3427 // If we are going to execute the first step, then we want
3428 // to do this as soon as possible instead of waiting for
3429 // a full movement, in order to make things look responsive.
3430 case 0:
3431 if (absPosition < precision) {
3432 return movement;
3433 }
3434 movement += dir;
3435 nonAccelMovement += dir;
3436 step = 1;
3437 break;
3438 // If we have generated the first movement, then we need
3439 // to wait for the second complete trackball motion before
3440 // generating the second discrete movement.
3441 case 1:
3442 if (absPosition < 2) {
3443 return movement;
3444 }
3445 movement += dir;
3446 nonAccelMovement += dir;
3447 position += dir > 0 ? -2 : 2;
3448 absPosition = Math.abs(position);
3449 step = 2;
3450 break;
3451 // After the first two, we generate discrete movements
3452 // consistently with the trackball, applying an acceleration
3453 // if the trackball is moving quickly. This is a simple
3454 // acceleration on top of what we already compute based
3455 // on how quickly the wheel is being turned, to apply
3456 // a longer increasing acceleration to continuous movement
3457 // in one direction.
3458 default:
3459 if (absPosition < 1) {
3460 return movement;
3461 }
3462 movement += dir;
3463 position += dir >= 0 ? -1 : 1;
3464 absPosition = Math.abs(position);
3465 float acc = acceleration;
3466 acc *= 1.1f;
3467 acceleration = acc < MAX_ACCELERATION ? acc : acceleration;
3468 break;
3469 }
3470 } while (true);
3471 }
3472 }
3473
3474 public static final class CalledFromWrongThreadException extends AndroidRuntimeException {
3475 public CalledFromWrongThreadException(String msg) {
3476 super(msg);
3477 }
3478 }
3479
3480 private SurfaceHolder mHolder = new SurfaceHolder() {
3481 // we only need a SurfaceHolder for opengl. it would be nice
3482 // to implement everything else though, especially the callback
3483 // support (opengl doesn't make use of it right now, but eventually
3484 // will).
3485 public Surface getSurface() {
3486 return mSurface;
3487 }
3488
3489 public boolean isCreating() {
3490 return false;
3491 }
3492
3493 public void addCallback(Callback callback) {
3494 }
3495
3496 public void removeCallback(Callback callback) {
3497 }
3498
3499 public void setFixedSize(int width, int height) {
3500 }
3501
3502 public void setSizeFromLayout() {
3503 }
3504
3505 public void setFormat(int format) {
3506 }
3507
3508 public void setType(int type) {
3509 }
3510
3511 public void setKeepScreenOn(boolean screenOn) {
3512 }
3513
3514 public Canvas lockCanvas() {
3515 return null;
3516 }
3517
3518 public Canvas lockCanvas(Rect dirty) {
3519 return null;
3520 }
3521
3522 public void unlockCanvasAndPost(Canvas canvas) {
3523 }
3524 public Rect getSurfaceFrame() {
3525 return null;
3526 }
3527 };
3528
3529 static RunQueue getRunQueue() {
3530 RunQueue rq = sRunQueues.get();
3531 if (rq != null) {
3532 return rq;
3533 }
3534 rq = new RunQueue();
3535 sRunQueues.set(rq);
3536 return rq;
3537 }
Romain Guy8506ab42009-06-11 17:35:47 -07003538
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003539 /**
3540 * @hide
3541 */
3542 static final class RunQueue {
3543 private final ArrayList<HandlerAction> mActions = new ArrayList<HandlerAction>();
3544
3545 void post(Runnable action) {
3546 postDelayed(action, 0);
3547 }
3548
3549 void postDelayed(Runnable action, long delayMillis) {
3550 HandlerAction handlerAction = new HandlerAction();
3551 handlerAction.action = action;
3552 handlerAction.delay = delayMillis;
3553
3554 synchronized (mActions) {
3555 mActions.add(handlerAction);
3556 }
3557 }
3558
3559 void removeCallbacks(Runnable action) {
3560 final HandlerAction handlerAction = new HandlerAction();
3561 handlerAction.action = action;
3562
3563 synchronized (mActions) {
3564 final ArrayList<HandlerAction> actions = mActions;
3565
3566 while (actions.remove(handlerAction)) {
3567 // Keep going
3568 }
3569 }
3570 }
3571
3572 void executeActions(Handler handler) {
3573 synchronized (mActions) {
3574 final ArrayList<HandlerAction> actions = mActions;
3575 final int count = actions.size();
3576
3577 for (int i = 0; i < count; i++) {
3578 final HandlerAction handlerAction = actions.get(i);
3579 handler.postDelayed(handlerAction.action, handlerAction.delay);
3580 }
3581
Romain Guy15df6702009-08-17 20:17:30 -07003582 actions.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003583 }
3584 }
3585
3586 private static class HandlerAction {
3587 Runnable action;
3588 long delay;
3589
3590 @Override
3591 public boolean equals(Object o) {
3592 if (this == o) return true;
3593 if (o == null || getClass() != o.getClass()) return false;
3594
3595 HandlerAction that = (HandlerAction) o;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003596 return !(action != null ? !action.equals(that.action) : that.action != null);
3597
3598 }
3599
3600 @Override
3601 public int hashCode() {
3602 int result = action != null ? action.hashCode() : 0;
3603 result = 31 * result + (int) (delay ^ (delay >>> 32));
3604 return result;
3605 }
3606 }
3607 }
3608
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003609 private static native void nativeShowFPS(Canvas canvas, int durationMillis);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003610}