blob: 9bda637c2268c740249b3476edd45f8d41758cab [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 Guydbf78bd2010-12-07 17:04:03 -08001104 if (hwInitialized || (windowShouldResize &&
1105 mAttachInfo.mHardwareRenderer != null &&
1106 mAttachInfo.mHardwareRenderer.isEnabled())) {
Romain Guyb051e892010-09-28 19:09:36 -07001107 mAttachInfo.mHardwareRenderer.setup(mWidth, mHeight);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001108 }
1109
1110 boolean focusChangedDueToTouchMode = ensureTouchModeLocally(
Romain Guy2d4cff62010-04-09 15:39:00 -07001111 (relayoutResult&WindowManagerImpl.RELAYOUT_IN_TOUCH_MODE) != 0);
Dianne Hackborn189ee182010-12-02 21:48:53 -08001112 if (focusChangedDueToTouchMode || mWidth != host.getMeasuredWidth()
1113 || mHeight != host.getMeasuredHeight() || contentInsetsChanged) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001114 childWidthMeasureSpec = getRootMeasureSpec(mWidth, lp.width);
1115 childHeightMeasureSpec = getRootMeasureSpec(mHeight, lp.height);
1116
1117 if (DEBUG_LAYOUT) Log.v(TAG, "Ooops, something changed! mWidth="
Dianne Hackborn189ee182010-12-02 21:48:53 -08001118 + mWidth + " measuredWidth=" + host.getMeasuredWidth()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001119 + " mHeight=" + mHeight
Dianne Hackborn189ee182010-12-02 21:48:53 -08001120 + " measuredHeight" + host.getMeasuredHeight()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001121 + " coveredInsetsChanged=" + contentInsetsChanged);
Romain Guy8506ab42009-06-11 17:35:47 -07001122
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001123 // Ask host how big it wants to be
1124 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
1125
1126 // Implementation of weights from WindowManager.LayoutParams
1127 // We just grow the dimensions as needed and re-measure if
1128 // needs be
Dianne Hackborn189ee182010-12-02 21:48:53 -08001129 int width = host.getMeasuredWidth();
1130 int height = host.getMeasuredHeight();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001131 boolean measureAgain = false;
1132
1133 if (lp.horizontalWeight > 0.0f) {
1134 width += (int) ((mWidth - width) * lp.horizontalWeight);
1135 childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(width,
1136 MeasureSpec.EXACTLY);
1137 measureAgain = true;
1138 }
1139 if (lp.verticalWeight > 0.0f) {
1140 height += (int) ((mHeight - height) * lp.verticalWeight);
1141 childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(height,
1142 MeasureSpec.EXACTLY);
1143 measureAgain = true;
1144 }
1145
1146 if (measureAgain) {
1147 if (DEBUG_LAYOUT) Log.v(TAG,
1148 "And hey let's measure once more: width=" + width
1149 + " height=" + height);
1150 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
1151 }
1152
1153 mLayoutRequested = true;
1154 }
1155 }
1156
1157 final boolean didLayout = mLayoutRequested;
1158 boolean triggerGlobalLayoutListener = didLayout
1159 || attachInfo.mRecomputeGlobalAttributes;
1160 if (didLayout) {
1161 mLayoutRequested = false;
1162 mScrollMayChange = true;
1163 if (DEBUG_ORIENTATION || DEBUG_LAYOUT) Log.v(
Jeff Brownc5ed5912010-07-14 18:48:53 -07001164 TAG, "Laying out " + host + " to (" +
Dianne Hackborn189ee182010-12-02 21:48:53 -08001165 host.getMeasuredWidth() + ", " + host.getMeasuredHeight() + ")");
Romain Guy13922e02009-05-12 17:56:14 -07001166 long startTime = 0L;
Romain Guy5429e1d2010-09-07 12:38:00 -07001167 if (ViewDebug.DEBUG_PROFILE_LAYOUT) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001168 startTime = SystemClock.elapsedRealtime();
1169 }
Dianne Hackborn189ee182010-12-02 21:48:53 -08001170 host.layout(0, 0, host.getMeasuredWidth(), host.getMeasuredHeight());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001171
Romain Guy13922e02009-05-12 17:56:14 -07001172 if (Config.DEBUG && ViewDebug.consistencyCheckEnabled) {
1173 if (!host.dispatchConsistencyCheck(ViewDebug.CONSISTENCY_LAYOUT)) {
1174 throw new IllegalStateException("The view hierarchy is an inconsistent state,"
1175 + "please refer to the logs with the tag "
1176 + ViewDebug.CONSISTENCY_LOG_TAG + " for more infomation.");
1177 }
1178 }
1179
Romain Guy5429e1d2010-09-07 12:38:00 -07001180 if (ViewDebug.DEBUG_PROFILE_LAYOUT) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001181 EventLog.writeEvent(60001, SystemClock.elapsedRealtime() - startTime);
1182 }
1183
1184 // By this point all views have been sized and positionned
1185 // We can compute the transparent area
1186
1187 if ((host.mPrivateFlags & View.REQUEST_TRANSPARENT_REGIONS) != 0) {
1188 // start out transparent
1189 // TODO: AVOID THAT CALL BY CACHING THE RESULT?
1190 host.getLocationInWindow(mTmpLocation);
1191 mTransparentRegion.set(mTmpLocation[0], mTmpLocation[1],
1192 mTmpLocation[0] + host.mRight - host.mLeft,
1193 mTmpLocation[1] + host.mBottom - host.mTop);
1194
1195 host.gatherTransparentRegion(mTransparentRegion);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001196 if (mTranslator != null) {
1197 mTranslator.translateRegionInWindowToScreen(mTransparentRegion);
1198 }
1199
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001200 if (!mTransparentRegion.equals(mPreviousTransparentRegion)) {
1201 mPreviousTransparentRegion.set(mTransparentRegion);
1202 // reconfigure window manager
1203 try {
1204 sWindowSession.setTransparentRegion(mWindow, mTransparentRegion);
1205 } catch (RemoteException e) {
1206 }
1207 }
1208 }
1209
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001210 if (DBG) {
1211 System.out.println("======================================");
1212 System.out.println("performTraversals -- after setFrame");
1213 host.debug();
1214 }
1215 }
1216
1217 if (triggerGlobalLayoutListener) {
1218 attachInfo.mRecomputeGlobalAttributes = false;
1219 attachInfo.mTreeObserver.dispatchOnGlobalLayout();
1220 }
1221
1222 if (computesInternalInsets) {
1223 ViewTreeObserver.InternalInsetsInfo insets = attachInfo.mGivenInternalInsets;
1224 final Rect givenContent = attachInfo.mGivenInternalInsets.contentInsets;
1225 final Rect givenVisible = attachInfo.mGivenInternalInsets.visibleInsets;
1226 givenContent.left = givenContent.top = givenContent.right
1227 = givenContent.bottom = givenVisible.left = givenVisible.top
1228 = givenVisible.right = givenVisible.bottom = 0;
1229 attachInfo.mTreeObserver.dispatchOnComputeInternalInsets(insets);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001230 Rect contentInsets = insets.contentInsets;
1231 Rect visibleInsets = insets.visibleInsets;
1232 if (mTranslator != null) {
1233 contentInsets = mTranslator.getTranslatedContentInsets(contentInsets);
1234 visibleInsets = mTranslator.getTranslatedVisbileInsets(visibleInsets);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001235 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001236 if (insetsPending || !mLastGivenInsets.equals(insets)) {
1237 mLastGivenInsets.set(insets);
1238 try {
1239 sWindowSession.setInsets(mWindow, insets.mTouchableInsets,
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001240 contentInsets, visibleInsets);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001241 } catch (RemoteException e) {
1242 }
1243 }
1244 }
Romain Guy8506ab42009-06-11 17:35:47 -07001245
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001246 if (mFirst) {
1247 // handle first focus request
1248 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: mView.hasFocus()="
1249 + mView.hasFocus());
1250 if (mView != null) {
1251 if (!mView.hasFocus()) {
1252 mView.requestFocus(View.FOCUS_FORWARD);
1253 mFocusedView = mRealFocusedView = mView.findFocus();
1254 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: requested focused view="
1255 + mFocusedView);
1256 } else {
1257 mRealFocusedView = mView.findFocus();
1258 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: existing focused view="
1259 + mRealFocusedView);
1260 }
1261 }
1262 }
1263
1264 mFirst = false;
1265 mWillDrawSoon = false;
1266 mNewSurfaceNeeded = false;
1267 mViewVisibility = viewVisibility;
1268
1269 if (mAttachInfo.mHasWindowFocus) {
1270 final boolean imTarget = WindowManager.LayoutParams
1271 .mayUseInputMethod(mWindowAttributes.flags);
1272 if (imTarget != mLastWasImTarget) {
1273 mLastWasImTarget = imTarget;
1274 InputMethodManager imm = InputMethodManager.peekInstance();
1275 if (imm != null && imTarget) {
1276 imm.startGettingWindowFocus(mView);
1277 imm.onWindowFocus(mView, mView.findFocus(),
1278 mWindowAttributes.softInputMode,
1279 !mHasHadWindowFocus, mWindowAttributes.flags);
1280 }
1281 }
1282 }
Romain Guy8506ab42009-06-11 17:35:47 -07001283
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001284 boolean cancelDraw = attachInfo.mTreeObserver.dispatchOnPreDraw();
1285
1286 if (!cancelDraw && !newSurface) {
1287 mFullRedrawNeeded = false;
1288 draw(fullRedrawNeeded);
1289
1290 if ((relayoutResult&WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0
1291 || mReportNextDraw) {
1292 if (LOCAL_LOGV) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001293 Log.v(TAG, "FINISHED DRAWING: " + mWindowAttributes.getTitle());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001294 }
1295 mReportNextDraw = false;
Dianne Hackbornd76b67c2010-07-13 17:48:30 -07001296 if (mSurfaceHolder != null && mSurface.isValid()) {
1297 mSurfaceHolderCallback.surfaceRedrawNeeded(mSurfaceHolder);
1298 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
1299 if (callbacks != null) {
1300 for (SurfaceHolder.Callback c : callbacks) {
1301 if (c instanceof SurfaceHolder.Callback2) {
1302 ((SurfaceHolder.Callback2)c).surfaceRedrawNeeded(
1303 mSurfaceHolder);
1304 }
1305 }
1306 }
1307 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001308 try {
1309 sWindowSession.finishDrawing(mWindow);
1310 } catch (RemoteException e) {
1311 }
1312 }
1313 } else {
1314 // We were supposed to report when we are done drawing. Since we canceled the
1315 // draw, remember it here.
1316 if ((relayoutResult&WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0) {
1317 mReportNextDraw = true;
1318 }
1319 if (fullRedrawNeeded) {
1320 mFullRedrawNeeded = true;
1321 }
1322 // Try again
1323 scheduleTraversals();
1324 }
1325 }
1326
1327 public void requestTransparentRegion(View child) {
1328 // the test below should not fail unless someone is messing with us
1329 checkThread();
1330 if (mView == child) {
1331 mView.mPrivateFlags |= View.REQUEST_TRANSPARENT_REGIONS;
1332 // Need to make sure we re-evaluate the window attributes next
1333 // time around, to ensure the window has the correct format.
1334 mWindowAttributesChanged = true;
Mathias Agopian1bd80ad2010-11-04 17:13:39 -07001335 requestLayout();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001336 }
1337 }
1338
1339 /**
1340 * Figures out the measure spec for the root view in a window based on it's
1341 * layout params.
1342 *
1343 * @param windowSize
1344 * The available width or height of the window
1345 *
1346 * @param rootDimension
1347 * The layout params for one dimension (width or height) of the
1348 * window.
1349 *
1350 * @return The measure spec to use to measure the root view.
1351 */
1352 private int getRootMeasureSpec(int windowSize, int rootDimension) {
1353 int measureSpec;
1354 switch (rootDimension) {
1355
Romain Guy980a9382010-01-08 15:06:28 -08001356 case ViewGroup.LayoutParams.MATCH_PARENT:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001357 // Window can't resize. Force root view to be windowSize.
1358 measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.EXACTLY);
1359 break;
1360 case ViewGroup.LayoutParams.WRAP_CONTENT:
1361 // Window can resize. Set max size for root view.
1362 measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.AT_MOST);
1363 break;
1364 default:
1365 // Window wants to be an exact size. Force root view to be that size.
1366 measureSpec = MeasureSpec.makeMeasureSpec(rootDimension, MeasureSpec.EXACTLY);
1367 break;
1368 }
1369 return measureSpec;
1370 }
1371
Dianne Hackborn0f761d62010-11-30 22:06:10 -08001372 int mHardwareYOffset;
1373 int mResizeAlpha;
1374 final Paint mResizePaint = new Paint();
1375
1376 public void onHardwarePreDraw(Canvas canvas) {
1377 canvas.translate(0, -mHardwareYOffset);
1378 }
1379
1380 public void onHardwarePostDraw(Canvas canvas) {
1381 if (mResizeBitmap != null) {
1382 canvas.translate(0, mHardwareYOffset);
1383 mResizePaint.setAlpha(mResizeAlpha);
1384 canvas.drawBitmap(mResizeBitmap, 0, 0, mResizePaint);
1385 }
1386 }
1387
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001388 private void draw(boolean fullRedrawNeeded) {
1389 Surface surface = mSurface;
1390 if (surface == null || !surface.isValid()) {
1391 return;
1392 }
1393
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001394 if (!sFirstDrawComplete) {
1395 synchronized (sFirstDrawHandlers) {
1396 sFirstDrawComplete = true;
Romain Guy812ccbe2010-06-01 14:07:24 -07001397 final int count = sFirstDrawHandlers.size();
1398 for (int i = 0; i< count; i++) {
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001399 post(sFirstDrawHandlers.get(i));
1400 }
1401 }
1402 }
1403
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001404 scrollToRectOrFocus(null, false);
1405
1406 if (mAttachInfo.mViewScrollChanged) {
1407 mAttachInfo.mViewScrollChanged = false;
1408 mAttachInfo.mTreeObserver.dispatchOnScrollChanged();
1409 }
Romain Guy8506ab42009-06-11 17:35:47 -07001410
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001411 int yoff;
Dianne Hackborn0f761d62010-11-30 22:06:10 -08001412 boolean animating = mScroller != null && mScroller.computeScrollOffset();
1413 if (animating) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001414 yoff = mScroller.getCurrY();
1415 } else {
1416 yoff = mScrollY;
1417 }
1418 if (mCurScrollY != yoff) {
1419 mCurScrollY = yoff;
1420 fullRedrawNeeded = true;
1421 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001422 float appScale = mAttachInfo.mApplicationScale;
1423 boolean scalingRequired = mAttachInfo.mScalingRequired;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001424
Dianne Hackborn0f761d62010-11-30 22:06:10 -08001425 int resizeAlpha = 0;
1426 if (mResizeBitmap != null) {
1427 long deltaTime = SystemClock.uptimeMillis() - mResizeBitmapStartTime;
1428 if (deltaTime < mResizeBitmapDuration) {
1429 float amt = deltaTime/(float)mResizeBitmapDuration;
1430 amt = mResizeInterpolator.getInterpolation(amt);
1431 animating = true;
1432 resizeAlpha = 255 - (int)(amt*255);
1433 } else {
1434 disposeResizeBitmap();
1435 }
1436 }
1437
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001438 Rect dirty = mDirty;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001439 if (mSurfaceHolder != null) {
1440 // The app owns the surface, we won't draw.
1441 dirty.setEmpty();
Dianne Hackborn0f761d62010-11-30 22:06:10 -08001442 if (animating) {
1443 if (mScroller != null) {
1444 mScroller.abortAnimation();
1445 }
1446 disposeResizeBitmap();
1447 }
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001448 return;
1449 }
Romain Guy58ef7fb2010-09-13 12:52:37 -07001450
1451 if (fullRedrawNeeded) {
1452 mAttachInfo.mIgnoreDirtyState = true;
1453 dirty.union(0, 0, (int) (mWidth * appScale + 0.5f), (int) (mHeight * appScale + 0.5f));
1454 }
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001455
Romain Guyb051e892010-09-28 19:09:36 -07001456 if (mAttachInfo.mHardwareRenderer != null && mAttachInfo.mHardwareRenderer.isEnabled()) {
Romain Guyfd507262010-10-10 15:42:49 -07001457 if (!dirty.isEmpty() || mIsAnimating) {
Romain Guy101e2ae2010-10-11 12:41:21 -07001458 mIsAnimating = false;
Romain Guyfd507262010-10-10 15:42:49 -07001459 dirty.setEmpty();
Dianne Hackborn0f761d62010-11-30 22:06:10 -08001460 mHardwareYOffset = yoff;
1461 mResizeAlpha = resizeAlpha;
1462 mAttachInfo.mHardwareRenderer.draw(mView, mAttachInfo, this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001463 }
Romain Guy812ccbe2010-06-01 14:07:24 -07001464
Dianne Hackborn0f761d62010-11-30 22:06:10 -08001465 if (animating) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001466 mFullRedrawNeeded = true;
1467 scheduleTraversals();
1468 }
Romain Guy812ccbe2010-06-01 14:07:24 -07001469
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001470 return;
1471 }
1472
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001473 if (DEBUG_ORIENTATION || DEBUG_DRAW) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001474 Log.v(TAG, "Draw " + mView + "/"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001475 + mWindowAttributes.getTitle()
1476 + ": dirty={" + dirty.left + "," + dirty.top
1477 + "," + dirty.right + "," + dirty.bottom + "} surface="
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001478 + surface + " surface.isValid()=" + surface.isValid() + ", appScale:" +
1479 appScale + ", width=" + mWidth + ", height=" + mHeight);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001480 }
1481
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001482 if (!dirty.isEmpty() || mIsAnimating) {
1483 Canvas canvas;
1484 try {
1485 int left = dirty.left;
1486 int top = dirty.top;
1487 int right = dirty.right;
1488 int bottom = dirty.bottom;
1489 canvas = surface.lockCanvas(dirty);
Romain Guy5bcdff42009-05-14 21:27:18 -07001490
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001491 if (left != dirty.left || top != dirty.top || right != dirty.right ||
1492 bottom != dirty.bottom) {
1493 mAttachInfo.mIgnoreDirtyState = true;
1494 }
1495
1496 // TODO: Do this in native
1497 canvas.setDensity(mDensity);
1498 } catch (Surface.OutOfResourcesException e) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001499 Log.e(TAG, "OutOfResourcesException locking surface", e);
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001500 // TODO: we should ask the window manager to do something!
1501 // for now we just do nothing
1502 return;
1503 } catch (IllegalArgumentException e) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001504 Log.e(TAG, "IllegalArgumentException locking surface", e);
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001505 // TODO: we should ask the window manager to do something!
1506 // for now we just do nothing
1507 return;
Romain Guy5bcdff42009-05-14 21:27:18 -07001508 }
1509
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001510 try {
1511 if (!dirty.isEmpty() || mIsAnimating) {
1512 long startTime = 0L;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001513
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001514 if (DEBUG_ORIENTATION || DEBUG_DRAW) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001515 Log.v(TAG, "Surface " + surface + " drawing to bitmap w="
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001516 + canvas.getWidth() + ", h=" + canvas.getHeight());
1517 //canvas.drawARGB(255, 255, 0, 0);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001518 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001519
Romain Guy5429e1d2010-09-07 12:38:00 -07001520 if (ViewDebug.DEBUG_PROFILE_DRAWING) {
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001521 startTime = SystemClock.elapsedRealtime();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001522 }
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001523
1524 // If this bitmap's format includes an alpha channel, we
1525 // need to clear it before drawing so that the child will
1526 // properly re-composite its drawing on a transparent
1527 // background. This automatically respects the clip/dirty region
1528 // or
1529 // If we are applying an offset, we need to clear the area
1530 // where the offset doesn't appear to avoid having garbage
1531 // left in the blank areas.
1532 if (!canvas.isOpaque() || yoff != 0) {
1533 canvas.drawColor(0, PorterDuff.Mode.CLEAR);
1534 }
1535
1536 dirty.setEmpty();
1537 mIsAnimating = false;
1538 mAttachInfo.mDrawingTime = SystemClock.uptimeMillis();
1539 mView.mPrivateFlags |= View.DRAWN;
1540
1541 if (DEBUG_DRAW) {
1542 Context cxt = mView.getContext();
1543 Log.i(TAG, "Drawing: package:" + cxt.getPackageName() +
1544 ", metrics=" + cxt.getResources().getDisplayMetrics() +
1545 ", compatibilityInfo=" + cxt.getResources().getCompatibilityInfo());
1546 }
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001547 try {
1548 canvas.translate(0, -yoff);
1549 if (mTranslator != null) {
1550 mTranslator.translateCanvas(canvas);
1551 }
1552 canvas.setScreenDensity(scalingRequired
1553 ? DisplayMetrics.DENSITY_DEVICE : 0);
1554 mView.draw(canvas);
1555 } finally {
1556 mAttachInfo.mIgnoreDirtyState = false;
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001557 }
1558
1559 if (Config.DEBUG && ViewDebug.consistencyCheckEnabled) {
1560 mView.dispatchConsistencyCheck(ViewDebug.CONSISTENCY_DRAWING);
1561 }
1562
Romain Guy5429e1d2010-09-07 12:38:00 -07001563 if (SHOW_FPS || ViewDebug.DEBUG_SHOW_FPS) {
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001564 int now = (int)SystemClock.elapsedRealtime();
1565 if (sDrawTime != 0) {
1566 nativeShowFPS(canvas, now - sDrawTime);
1567 }
1568 sDrawTime = now;
1569 }
1570
Romain Guy5429e1d2010-09-07 12:38:00 -07001571 if (ViewDebug.DEBUG_PROFILE_DRAWING) {
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001572 EventLog.writeEvent(60000, SystemClock.elapsedRealtime() - startTime);
1573 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001574 }
1575
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001576 } finally {
1577 surface.unlockCanvasAndPost(canvas);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001578 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001579 }
1580
1581 if (LOCAL_LOGV) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001582 Log.v(TAG, "Surface " + surface + " unlockCanvasAndPost");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001583 }
Romain Guy8506ab42009-06-11 17:35:47 -07001584
Dianne Hackborn0f761d62010-11-30 22:06:10 -08001585 if (animating) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001586 mFullRedrawNeeded = true;
1587 scheduleTraversals();
1588 }
1589 }
1590
1591 boolean scrollToRectOrFocus(Rect rectangle, boolean immediate) {
1592 final View.AttachInfo attachInfo = mAttachInfo;
1593 final Rect ci = attachInfo.mContentInsets;
1594 final Rect vi = attachInfo.mVisibleInsets;
1595 int scrollY = 0;
1596 boolean handled = false;
Romain Guy8506ab42009-06-11 17:35:47 -07001597
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001598 if (vi.left > ci.left || vi.top > ci.top
1599 || vi.right > ci.right || vi.bottom > ci.bottom) {
1600 // We'll assume that we aren't going to change the scroll
1601 // offset, since we want to avoid that unless it is actually
1602 // going to make the focus visible... otherwise we scroll
1603 // all over the place.
1604 scrollY = mScrollY;
1605 // We can be called for two different situations: during a draw,
1606 // to update the scroll position if the focus has changed (in which
1607 // case 'rectangle' is null), or in response to a
1608 // requestChildRectangleOnScreen() call (in which case 'rectangle'
1609 // is non-null and we just want to scroll to whatever that
1610 // rectangle is).
1611 View focus = mRealFocusedView;
Romain Guye8b16522009-07-14 13:06:42 -07001612
1613 // When in touch mode, focus points to the previously focused view,
1614 // which may have been removed from the view hierarchy. The following
Joe Onoratob71193b2009-11-24 18:34:42 -05001615 // line checks whether the view is still in our hierarchy.
1616 if (focus == null || focus.mAttachInfo != mAttachInfo) {
Romain Guye8b16522009-07-14 13:06:42 -07001617 mRealFocusedView = null;
1618 return false;
1619 }
1620
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001621 if (focus != mLastScrolledFocus) {
1622 // If the focus has changed, then ignore any requests to scroll
1623 // to a rectangle; first we want to make sure the entire focus
1624 // view is visible.
1625 rectangle = null;
1626 }
1627 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Eval scroll: focus=" + focus
1628 + " rectangle=" + rectangle + " ci=" + ci
1629 + " vi=" + vi);
1630 if (focus == mLastScrolledFocus && !mScrollMayChange
1631 && rectangle == null) {
1632 // Optimization: if the focus hasn't changed since last
1633 // time, and no layout has happened, then just leave things
1634 // as they are.
1635 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Keeping scroll y="
1636 + mScrollY + " vi=" + vi.toShortString());
1637 } else if (focus != null) {
1638 // We need to determine if the currently focused view is
1639 // within the visible part of the window and, if not, apply
1640 // a pan so it can be seen.
1641 mLastScrolledFocus = focus;
1642 mScrollMayChange = false;
1643 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Need to scroll?");
1644 // Try to find the rectangle from the focus view.
1645 if (focus.getGlobalVisibleRect(mVisRect, null)) {
1646 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Root w="
1647 + mView.getWidth() + " h=" + mView.getHeight()
1648 + " ci=" + ci.toShortString()
1649 + " vi=" + vi.toShortString());
1650 if (rectangle == null) {
1651 focus.getFocusedRect(mTempRect);
1652 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Focus " + focus
1653 + ": focusRect=" + mTempRect.toShortString());
Dianne Hackborn1c6a8942010-03-23 16:34:20 -07001654 if (mView instanceof ViewGroup) {
1655 ((ViewGroup) mView).offsetDescendantRectToMyCoords(
1656 focus, mTempRect);
1657 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001658 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1659 "Focus in window: focusRect="
1660 + mTempRect.toShortString()
1661 + " visRect=" + mVisRect.toShortString());
1662 } else {
1663 mTempRect.set(rectangle);
1664 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1665 "Request scroll to rect: "
1666 + mTempRect.toShortString()
1667 + " visRect=" + mVisRect.toShortString());
1668 }
1669 if (mTempRect.intersect(mVisRect)) {
1670 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1671 "Focus window visible rect: "
1672 + mTempRect.toShortString());
1673 if (mTempRect.height() >
1674 (mView.getHeight()-vi.top-vi.bottom)) {
1675 // If the focus simply is not going to fit, then
1676 // best is probably just to leave things as-is.
1677 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1678 "Too tall; leaving scrollY=" + scrollY);
1679 } else if ((mTempRect.top-scrollY) < vi.top) {
1680 scrollY -= vi.top - (mTempRect.top-scrollY);
1681 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1682 "Top covered; scrollY=" + scrollY);
1683 } else if ((mTempRect.bottom-scrollY)
1684 > (mView.getHeight()-vi.bottom)) {
1685 scrollY += (mTempRect.bottom-scrollY)
1686 - (mView.getHeight()-vi.bottom);
1687 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1688 "Bottom covered; scrollY=" + scrollY);
1689 }
1690 handled = true;
1691 }
1692 }
1693 }
1694 }
Romain Guy8506ab42009-06-11 17:35:47 -07001695
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001696 if (scrollY != mScrollY) {
1697 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Pan scroll changed: old="
1698 + mScrollY + " , new=" + scrollY);
Dianne Hackborn0f761d62010-11-30 22:06:10 -08001699 if (!immediate && mResizeBitmap == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001700 if (mScroller == null) {
1701 mScroller = new Scroller(mView.getContext());
1702 }
1703 mScroller.startScroll(0, mScrollY, 0, scrollY-mScrollY);
1704 } else if (mScroller != null) {
1705 mScroller.abortAnimation();
1706 }
1707 mScrollY = scrollY;
1708 }
Romain Guy8506ab42009-06-11 17:35:47 -07001709
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001710 return handled;
1711 }
Romain Guy8506ab42009-06-11 17:35:47 -07001712
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001713 public void requestChildFocus(View child, View focused) {
1714 checkThread();
1715 if (mFocusedView != focused) {
1716 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(mFocusedView, focused);
1717 scheduleTraversals();
1718 }
1719 mFocusedView = mRealFocusedView = focused;
1720 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Request child focus: focus now "
1721 + mFocusedView);
1722 }
1723
1724 public void clearChildFocus(View child) {
1725 checkThread();
1726
1727 View oldFocus = mFocusedView;
1728
1729 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Clearing child focus");
1730 mFocusedView = mRealFocusedView = null;
1731 if (mView != null && !mView.hasFocus()) {
1732 // If a view gets the focus, the listener will be invoked from requestChildFocus()
1733 if (!mView.requestFocus(View.FOCUS_FORWARD)) {
1734 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
1735 }
1736 } else if (oldFocus != null) {
1737 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
1738 }
1739 }
1740
1741
1742 public void focusableViewAvailable(View v) {
1743 checkThread();
1744
1745 if (mView != null && !mView.hasFocus()) {
1746 v.requestFocus();
1747 } else {
1748 // the one case where will transfer focus away from the current one
1749 // is if the current view is a view group that prefers to give focus
1750 // to its children first AND the view is a descendant of it.
1751 mFocusedView = mView.findFocus();
1752 boolean descendantsHaveDibsOnFocus =
1753 (mFocusedView instanceof ViewGroup) &&
1754 (((ViewGroup) mFocusedView).getDescendantFocusability() ==
1755 ViewGroup.FOCUS_AFTER_DESCENDANTS);
1756 if (descendantsHaveDibsOnFocus && isViewDescendantOf(v, mFocusedView)) {
1757 // If a view gets the focus, the listener will be invoked from requestChildFocus()
1758 v.requestFocus();
1759 }
1760 }
1761 }
1762
1763 public void recomputeViewAttributes(View child) {
1764 checkThread();
1765 if (mView == child) {
1766 mAttachInfo.mRecomputeGlobalAttributes = true;
1767 if (!mWillDrawSoon) {
1768 scheduleTraversals();
1769 }
1770 }
1771 }
1772
1773 void dispatchDetachedFromWindow() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001774 if (mView != null) {
1775 mView.dispatchDetachedFromWindow();
1776 }
1777
1778 mView = null;
1779 mAttachInfo.mRootView = null;
Mathias Agopian5583dc62009-07-09 16:28:11 -07001780 mAttachInfo.mSurface = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001781
Romain Guy29d89972010-09-22 16:10:57 -07001782 destroyHardwareRenderer();
Romain Guy4caa4ed2010-08-25 14:46:24 -07001783
Dianne Hackborn0586a1b2009-09-06 21:08:27 -07001784 mSurface.release();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001785
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001786 if (mInputChannel != null) {
1787 if (mInputQueueCallback != null) {
1788 mInputQueueCallback.onInputQueueDestroyed(mInputQueue);
1789 mInputQueueCallback = null;
1790 } else {
1791 InputQueue.unregisterInputChannel(mInputChannel);
Jeff Brown46b9ac02010-04-22 18:58:52 -07001792 }
1793 }
1794
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001795 try {
1796 sWindowSession.remove(mWindow);
1797 } catch (RemoteException e) {
1798 }
Jeff Brown349703e2010-06-22 01:27:15 -07001799
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001800 // Dispose the input channel after removing the window so the Window Manager
1801 // doesn't interpret the input channel being closed as an abnormal termination.
1802 if (mInputChannel != null) {
1803 mInputChannel.dispose();
1804 mInputChannel = null;
Jeff Brown349703e2010-06-22 01:27:15 -07001805 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001806 }
Romain Guy8506ab42009-06-11 17:35:47 -07001807
Dianne Hackborn694f79b2010-03-17 19:44:59 -07001808 void updateConfiguration(Configuration config, boolean force) {
1809 if (DEBUG_CONFIGURATION) Log.v(TAG,
1810 "Applying new config to window "
1811 + mWindowAttributes.getTitle()
1812 + ": " + config);
1813 synchronized (sConfigCallbacks) {
1814 for (int i=sConfigCallbacks.size()-1; i>=0; i--) {
1815 sConfigCallbacks.get(i).onConfigurationChanged(config);
1816 }
1817 }
1818 if (mView != null) {
1819 // At this point the resources have been updated to
1820 // have the most recent config, whatever that is. Use
1821 // the on in them which may be newer.
1822 if (mView != null) {
1823 config = mView.getResources().getConfiguration();
1824 }
1825 if (force || mLastConfiguration.diff(config) != 0) {
1826 mLastConfiguration.setTo(config);
1827 mView.dispatchConfigurationChanged(config);
1828 }
1829 }
1830 }
1831
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001832 /**
1833 * Return true if child is an ancestor of parent, (or equal to the parent).
1834 */
1835 private static boolean isViewDescendantOf(View child, View parent) {
1836 if (child == parent) {
1837 return true;
1838 }
1839
1840 final ViewParent theParent = child.getParent();
1841 return (theParent instanceof ViewGroup) && isViewDescendantOf((View) theParent, parent);
1842 }
1843
Romain Guycdb86672010-03-18 18:54:50 -07001844 private static void forceLayout(View view) {
1845 view.forceLayout();
1846 if (view instanceof ViewGroup) {
1847 ViewGroup group = (ViewGroup) view;
1848 final int count = group.getChildCount();
1849 for (int i = 0; i < count; i++) {
1850 forceLayout(group.getChildAt(i));
1851 }
1852 }
1853 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001854
1855 public final static int DO_TRAVERSAL = 1000;
1856 public final static int DIE = 1001;
1857 public final static int RESIZED = 1002;
1858 public final static int RESIZED_REPORT = 1003;
1859 public final static int WINDOW_FOCUS_CHANGED = 1004;
1860 public final static int DISPATCH_KEY = 1005;
1861 public final static int DISPATCH_POINTER = 1006;
1862 public final static int DISPATCH_TRACKBALL = 1007;
1863 public final static int DISPATCH_APP_VISIBILITY = 1008;
1864 public final static int DISPATCH_GET_NEW_SURFACE = 1009;
1865 public final static int FINISHED_EVENT = 1010;
1866 public final static int DISPATCH_KEY_FROM_IME = 1011;
1867 public final static int FINISH_INPUT_CONNECTION = 1012;
1868 public final static int CHECK_FOCUS = 1013;
Dianne Hackbornffa42482009-09-23 22:20:11 -07001869 public final static int CLOSE_SYSTEM_DIALOGS = 1014;
Christopher Tatea53146c2010-09-07 11:57:52 -07001870 public final static int DISPATCH_DRAG_EVENT = 1015;
Chris Tate91e9bb32010-10-12 12:58:43 -07001871 public final static int DISPATCH_DRAG_LOCATION_EVENT = 1016;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001872
1873 @Override
1874 public void handleMessage(Message msg) {
1875 switch (msg.what) {
1876 case View.AttachInfo.INVALIDATE_MSG:
1877 ((View) msg.obj).invalidate();
1878 break;
1879 case View.AttachInfo.INVALIDATE_RECT_MSG:
1880 final View.AttachInfo.InvalidateInfo info = (View.AttachInfo.InvalidateInfo) msg.obj;
1881 info.target.invalidate(info.left, info.top, info.right, info.bottom);
1882 info.release();
1883 break;
1884 case DO_TRAVERSAL:
1885 if (mProfile) {
1886 Debug.startMethodTracing("ViewRoot");
1887 }
1888
1889 performTraversals();
1890
1891 if (mProfile) {
1892 Debug.stopMethodTracing();
1893 mProfile = false;
1894 }
1895 break;
1896 case FINISHED_EVENT:
1897 handleFinishedEvent(msg.arg1, msg.arg2 != 0);
1898 break;
1899 case DISPATCH_KEY:
Jeff Brown92ff1dd2010-08-11 16:16:06 -07001900 deliverKeyEvent((KeyEvent)msg.obj, msg.arg1 != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001901 break;
Jeff Brown3915bb82010-11-05 15:02:16 -07001902 case DISPATCH_POINTER:
1903 deliverPointerEvent((MotionEvent) msg.obj, msg.arg1 != 0);
1904 break;
1905 case DISPATCH_TRACKBALL:
1906 deliverTrackballEvent((MotionEvent) msg.obj, msg.arg1 != 0);
1907 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001908 case DISPATCH_APP_VISIBILITY:
1909 handleAppVisibility(msg.arg1 != 0);
1910 break;
1911 case DISPATCH_GET_NEW_SURFACE:
1912 handleGetNewSurface();
1913 break;
1914 case RESIZED:
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001915 ResizedInfo ri = (ResizedInfo)msg.obj;
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001916
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001917 if (mWinFrame.width() == msg.arg1 && mWinFrame.height() == msg.arg2
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001918 && mPendingContentInsets.equals(ri.coveredInsets)
Dianne Hackbornd49258f2010-03-26 00:44:29 -07001919 && mPendingVisibleInsets.equals(ri.visibleInsets)
1920 && ((ResizedInfo)msg.obj).newConfig == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001921 break;
1922 }
1923 // fall through...
1924 case RESIZED_REPORT:
1925 if (mAdded) {
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001926 Configuration config = ((ResizedInfo)msg.obj).newConfig;
1927 if (config != null) {
Dianne Hackborn694f79b2010-03-17 19:44:59 -07001928 updateConfiguration(config, false);
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001929 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001930 mWinFrame.left = 0;
1931 mWinFrame.right = msg.arg1;
1932 mWinFrame.top = 0;
1933 mWinFrame.bottom = msg.arg2;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001934 mPendingContentInsets.set(((ResizedInfo)msg.obj).coveredInsets);
1935 mPendingVisibleInsets.set(((ResizedInfo)msg.obj).visibleInsets);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001936 if (msg.what == RESIZED_REPORT) {
1937 mReportNextDraw = true;
1938 }
Romain Guycdb86672010-03-18 18:54:50 -07001939
1940 if (mView != null) {
1941 forceLayout(mView);
1942 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001943 requestLayout();
1944 }
1945 break;
1946 case WINDOW_FOCUS_CHANGED: {
1947 if (mAdded) {
1948 boolean hasWindowFocus = msg.arg1 != 0;
1949 mAttachInfo.mHasWindowFocus = hasWindowFocus;
1950 if (hasWindowFocus) {
1951 boolean inTouchMode = msg.arg2 != 0;
Romain Guy2d4cff62010-04-09 15:39:00 -07001952 ensureTouchModeLocally(inTouchMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001953
Romain Guyc361da82010-10-25 15:29:10 -07001954 if (mAttachInfo.mHardwareRenderer != null &&
1955 mSurface != null && mSurface.isValid()) {
Romain Guyb051e892010-09-28 19:09:36 -07001956 mAttachInfo.mHardwareRenderer.initializeIfNeeded(mWidth, mHeight,
1957 mAttachInfo, mHolder);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001958 }
1959 }
Romain Guy8506ab42009-06-11 17:35:47 -07001960
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001961 mLastWasImTarget = WindowManager.LayoutParams
1962 .mayUseInputMethod(mWindowAttributes.flags);
Romain Guy8506ab42009-06-11 17:35:47 -07001963
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001964 InputMethodManager imm = InputMethodManager.peekInstance();
1965 if (mView != null) {
1966 if (hasWindowFocus && imm != null && mLastWasImTarget) {
1967 imm.startGettingWindowFocus(mView);
1968 }
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07001969 mAttachInfo.mKeyDispatchState.reset();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001970 mView.dispatchWindowFocusChanged(hasWindowFocus);
1971 }
svetoslavganov75986cf2009-05-14 22:28:01 -07001972
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001973 // Note: must be done after the focus change callbacks,
1974 // so all of the view state is set up correctly.
1975 if (hasWindowFocus) {
1976 if (imm != null && mLastWasImTarget) {
1977 imm.onWindowFocus(mView, mView.findFocus(),
1978 mWindowAttributes.softInputMode,
1979 !mHasHadWindowFocus, mWindowAttributes.flags);
1980 }
1981 // Clear the forward bit. We can just do this directly, since
1982 // the window manager doesn't care about it.
1983 mWindowAttributes.softInputMode &=
1984 ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
1985 ((WindowManager.LayoutParams)mView.getLayoutParams())
1986 .softInputMode &=
1987 ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
1988 mHasHadWindowFocus = true;
1989 }
svetoslavganov75986cf2009-05-14 22:28:01 -07001990
1991 if (hasWindowFocus && mView != null) {
1992 sendAccessibilityEvents();
1993 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001994 }
1995 } break;
1996 case DIE:
Dianne Hackborn94d69142009-09-28 22:14:42 -07001997 doDie();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001998 break;
The Android Open Source Project10592532009-03-18 17:39:46 -07001999 case DISPATCH_KEY_FROM_IME: {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002000 if (LOCAL_LOGV) Log.v(
Jeff Brownc5ed5912010-07-14 18:48:53 -07002001 TAG, "Dispatching key "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002002 + msg.obj + " from IME to " + mView);
The Android Open Source Project10592532009-03-18 17:39:46 -07002003 KeyEvent event = (KeyEvent)msg.obj;
2004 if ((event.getFlags()&KeyEvent.FLAG_FROM_SYSTEM) != 0) {
2005 // The IME is trying to say this event is from the
2006 // system! Bad bad bad!
Romain Guy812ccbe2010-06-01 14:07:24 -07002007 event = KeyEvent.changeFlags(event, event.getFlags() & ~KeyEvent.FLAG_FROM_SYSTEM);
The Android Open Source Project10592532009-03-18 17:39:46 -07002008 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002009 deliverKeyEventPostIme((KeyEvent)msg.obj, false);
The Android Open Source Project10592532009-03-18 17:39:46 -07002010 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002011 case FINISH_INPUT_CONNECTION: {
2012 InputMethodManager imm = InputMethodManager.peekInstance();
2013 if (imm != null) {
2014 imm.reportFinishInputConnection((InputConnection)msg.obj);
2015 }
2016 } break;
2017 case CHECK_FOCUS: {
2018 InputMethodManager imm = InputMethodManager.peekInstance();
2019 if (imm != null) {
2020 imm.checkFocus();
2021 }
2022 } break;
Dianne Hackbornffa42482009-09-23 22:20:11 -07002023 case CLOSE_SYSTEM_DIALOGS: {
2024 if (mView != null) {
2025 mView.onCloseSystemDialogs((String)msg.obj);
2026 }
2027 } break;
Chris Tate91e9bb32010-10-12 12:58:43 -07002028 case DISPATCH_DRAG_EVENT:
2029 case DISPATCH_DRAG_LOCATION_EVENT: {
Christopher Tatea53146c2010-09-07 11:57:52 -07002030 handleDragEvent((DragEvent)msg.obj);
2031 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002032 }
2033 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002034
Jeff Brown3915bb82010-11-05 15:02:16 -07002035 private void startInputEvent(InputQueue.FinishedCallback finishedCallback) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07002036 if (mFinishedCallback != null) {
2037 Slog.w(TAG, "Received a new input event from the input queue but there is "
2038 + "already an unfinished input event in progress.");
2039 }
2040
2041 mFinishedCallback = finishedCallback;
2042 }
2043
Jeff Brown3915bb82010-11-05 15:02:16 -07002044 private void finishInputEvent(boolean handled) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07002045 if (LOCAL_LOGV) Log.v(TAG, "Telling window manager input event is finished");
Jeff Brown92ff1dd2010-08-11 16:16:06 -07002046
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002047 if (mFinishedCallback != null) {
Jeff Brown3915bb82010-11-05 15:02:16 -07002048 mFinishedCallback.finished(handled);
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002049 mFinishedCallback = null;
Jeff Brown92ff1dd2010-08-11 16:16:06 -07002050 } else {
Jeff Brown93ed4e32010-09-23 13:51:48 -07002051 Slog.w(TAG, "Attempted to tell the input queue that the current input event "
2052 + "is finished but there is no input event actually in progress.");
Jeff Brown46b9ac02010-04-22 18:58:52 -07002053 }
2054 }
2055
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002056 /**
2057 * Something in the current window tells us we need to change the touch mode. For
2058 * example, we are not in touch mode, and the user touches the screen.
2059 *
2060 * If the touch mode has changed, tell the window manager, and handle it locally.
2061 *
2062 * @param inTouchMode Whether we want to be in touch mode.
2063 * @return True if the touch mode changed and focus changed was changed as a result
2064 */
2065 boolean ensureTouchMode(boolean inTouchMode) {
2066 if (DBG) Log.d("touchmode", "ensureTouchMode(" + inTouchMode + "), current "
2067 + "touch mode is " + mAttachInfo.mInTouchMode);
2068 if (mAttachInfo.mInTouchMode == inTouchMode) return false;
2069
2070 // tell the window manager
2071 try {
2072 sWindowSession.setInTouchMode(inTouchMode);
2073 } catch (RemoteException e) {
2074 throw new RuntimeException(e);
2075 }
2076
2077 // handle the change
Romain Guy2d4cff62010-04-09 15:39:00 -07002078 return ensureTouchModeLocally(inTouchMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002079 }
2080
2081 /**
2082 * Ensure that the touch mode for this window is set, and if it is changing,
2083 * take the appropriate action.
2084 * @param inTouchMode Whether we want to be in touch mode.
2085 * @return True if the touch mode changed and focus changed was changed as a result
2086 */
Romain Guy2d4cff62010-04-09 15:39:00 -07002087 private boolean ensureTouchModeLocally(boolean inTouchMode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002088 if (DBG) Log.d("touchmode", "ensureTouchModeLocally(" + inTouchMode + "), current "
2089 + "touch mode is " + mAttachInfo.mInTouchMode);
2090
2091 if (mAttachInfo.mInTouchMode == inTouchMode) return false;
2092
2093 mAttachInfo.mInTouchMode = inTouchMode;
2094 mAttachInfo.mTreeObserver.dispatchOnTouchModeChanged(inTouchMode);
2095
Romain Guy2d4cff62010-04-09 15:39:00 -07002096 return (inTouchMode) ? enterTouchMode() : leaveTouchMode();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002097 }
2098
2099 private boolean enterTouchMode() {
2100 if (mView != null) {
2101 if (mView.hasFocus()) {
2102 // note: not relying on mFocusedView here because this could
2103 // be when the window is first being added, and mFocused isn't
2104 // set yet.
2105 final View focused = mView.findFocus();
2106 if (focused != null && !focused.isFocusableInTouchMode()) {
2107
2108 final ViewGroup ancestorToTakeFocus =
2109 findAncestorToTakeFocusInTouchMode(focused);
2110 if (ancestorToTakeFocus != null) {
2111 // there is an ancestor that wants focus after its descendants that
2112 // is focusable in touch mode.. give it focus
2113 return ancestorToTakeFocus.requestFocus();
2114 } else {
2115 // nothing appropriate to have focus in touch mode, clear it out
2116 mView.unFocus();
2117 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(focused, null);
2118 mFocusedView = null;
2119 return true;
2120 }
2121 }
2122 }
2123 }
2124 return false;
2125 }
2126
2127
2128 /**
2129 * Find an ancestor of focused that wants focus after its descendants and is
2130 * focusable in touch mode.
2131 * @param focused The currently focused view.
2132 * @return An appropriate view, or null if no such view exists.
2133 */
2134 private ViewGroup findAncestorToTakeFocusInTouchMode(View focused) {
2135 ViewParent parent = focused.getParent();
2136 while (parent instanceof ViewGroup) {
2137 final ViewGroup vgParent = (ViewGroup) parent;
2138 if (vgParent.getDescendantFocusability() == ViewGroup.FOCUS_AFTER_DESCENDANTS
2139 && vgParent.isFocusableInTouchMode()) {
2140 return vgParent;
2141 }
2142 if (vgParent.isRootNamespace()) {
2143 return null;
2144 } else {
2145 parent = vgParent.getParent();
2146 }
2147 }
2148 return null;
2149 }
2150
2151 private boolean leaveTouchMode() {
2152 if (mView != null) {
2153 if (mView.hasFocus()) {
2154 // i learned the hard way to not trust mFocusedView :)
2155 mFocusedView = mView.findFocus();
2156 if (!(mFocusedView instanceof ViewGroup)) {
2157 // some view has focus, let it keep it
2158 return false;
2159 } else if (((ViewGroup)mFocusedView).getDescendantFocusability() !=
2160 ViewGroup.FOCUS_AFTER_DESCENDANTS) {
2161 // some view group has focus, and doesn't prefer its children
2162 // over itself for focus, so let them keep it.
2163 return false;
2164 }
2165 }
2166
2167 // find the best view to give focus to in this brave new non-touch-mode
2168 // world
2169 final View focused = focusSearch(null, View.FOCUS_DOWN);
2170 if (focused != null) {
2171 return focused.requestFocus(View.FOCUS_DOWN);
2172 }
2173 }
2174 return false;
2175 }
2176
Jeff Brown3915bb82010-11-05 15:02:16 -07002177 private void deliverPointerEvent(MotionEvent event, boolean sendDone) {
2178 // If there is no view, then the event will not be handled.
2179 if (mView == null || !mAdded) {
2180 finishPointerEvent(event, sendDone, false);
2181 return;
2182 }
2183
2184 // Translate the pointer event for compatibility, if needed.
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002185 if (mTranslator != null) {
2186 mTranslator.translateEventInScreenToAppWindow(event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002187 }
2188
Jeff Brown3915bb82010-11-05 15:02:16 -07002189 // Enter touch mode on the down.
2190 boolean isDown = event.getAction() == MotionEvent.ACTION_DOWN;
2191 if (isDown) {
2192 ensureTouchMode(true);
2193 }
2194 if(Config.LOGV) {
2195 captureMotionLog("captureDispatchPointer", event);
2196 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002197
Jeff Brown3915bb82010-11-05 15:02:16 -07002198 // Offset the scroll position.
2199 if (mCurScrollY != 0) {
2200 event.offsetLocation(0, mCurScrollY);
2201 }
2202 if (MEASURE_LATENCY) {
2203 lt.sample("A Dispatching TouchEvents", System.nanoTime() - event.getEventTimeNano());
2204 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002205
Jeff Brown3915bb82010-11-05 15:02:16 -07002206 // Remember the touch position for possible drag-initiation.
2207 mLastTouchPoint.x = event.getRawX();
2208 mLastTouchPoint.y = event.getRawY();
2209
2210 // Dispatch touch to view hierarchy.
2211 boolean handled = mView.dispatchTouchEvent(event);
2212 if (MEASURE_LATENCY) {
2213 lt.sample("B Dispatched TouchEvents ", System.nanoTime() - event.getEventTimeNano());
2214 }
2215 if (handled) {
2216 finishPointerEvent(event, sendDone, true);
2217 return;
2218 }
2219
2220 // Apply edge slop and try again, if appropriate.
2221 final int edgeFlags = event.getEdgeFlags();
2222 if (edgeFlags != 0 && mView instanceof ViewGroup) {
2223 final int edgeSlop = mViewConfiguration.getScaledEdgeSlop();
2224 int direction = View.FOCUS_UP;
2225 int x = (int)event.getX();
2226 int y = (int)event.getY();
2227 final int[] deltas = new int[2];
2228
2229 if ((edgeFlags & MotionEvent.EDGE_TOP) != 0) {
2230 direction = View.FOCUS_DOWN;
2231 if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
2232 deltas[0] = edgeSlop;
2233 x += edgeSlop;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002234 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
Jeff Brown3915bb82010-11-05 15:02:16 -07002235 deltas[0] = -edgeSlop;
2236 x -= edgeSlop;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002237 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002238 } else if ((edgeFlags & MotionEvent.EDGE_BOTTOM) != 0) {
2239 direction = View.FOCUS_UP;
2240 if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
2241 deltas[0] = edgeSlop;
2242 x += edgeSlop;
2243 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
2244 deltas[0] = -edgeSlop;
2245 x -= edgeSlop;
2246 }
2247 } else if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
2248 direction = View.FOCUS_RIGHT;
2249 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
2250 direction = View.FOCUS_LEFT;
2251 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002252
Jeff Brown3915bb82010-11-05 15:02:16 -07002253 View nearest = FocusFinder.getInstance().findNearestTouchable(
2254 ((ViewGroup) mView), x, y, direction, deltas);
2255 if (nearest != null) {
2256 event.offsetLocation(deltas[0], deltas[1]);
2257 event.setEdgeFlags(0);
2258 if (mView.dispatchTouchEvent(event)) {
2259 finishPointerEvent(event, sendDone, true);
2260 return;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002261 }
2262 }
2263 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002264
2265 // Pointer event was unhandled.
2266 finishPointerEvent(event, sendDone, false);
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002267 }
2268
Jeff Brown3915bb82010-11-05 15:02:16 -07002269 private void finishPointerEvent(MotionEvent event, boolean sendDone, boolean handled) {
2270 event.recycle();
2271 if (sendDone) {
2272 finishInputEvent(handled);
2273 }
2274 if (LOCAL_LOGV || WATCH_POINTER) Log.i(TAG, "Done dispatching!");
2275 }
2276
2277 private void deliverTrackballEvent(MotionEvent event, boolean sendDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002278 if (DEBUG_TRACKBALL) Log.v(TAG, "Motion event:" + event);
2279
Jeff Brown3915bb82010-11-05 15:02:16 -07002280 // If there is no view, then the event will not be handled.
2281 if (mView == null || !mAdded) {
2282 finishTrackballEvent(event, sendDone, false);
2283 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002284 }
2285
Jeff Brown3915bb82010-11-05 15:02:16 -07002286 // Deliver the trackball event to the view.
2287 if (mView.dispatchTrackballEvent(event)) {
2288 // If we reach this, we delivered a trackball event to mView and
2289 // mView consumed it. Because we will not translate the trackball
2290 // event into a key event, touch mode will not exit, so we exit
2291 // touch mode here.
2292 ensureTouchMode(false);
2293
2294 finishTrackballEvent(event, sendDone, true);
2295 mLastTrackballTime = Integer.MIN_VALUE;
2296 return;
2297 }
2298
2299 // Translate the trackball event into DPAD keys and try to deliver those.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002300 final TrackballAxis x = mTrackballAxisX;
2301 final TrackballAxis y = mTrackballAxisY;
2302
2303 long curTime = SystemClock.uptimeMillis();
Jeff Brown3915bb82010-11-05 15:02:16 -07002304 if ((mLastTrackballTime + MAX_TRACKBALL_DELAY) < curTime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002305 // It has been too long since the last movement,
2306 // so restart at the beginning.
2307 x.reset(0);
2308 y.reset(0);
2309 mLastTrackballTime = curTime;
2310 }
2311
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002312 final int action = event.getAction();
Jeff Brown49ed71d2010-12-06 17:13:33 -08002313 final int metaState = event.getMetaState();
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002314 switch (action) {
2315 case MotionEvent.ACTION_DOWN:
2316 x.reset(2);
2317 y.reset(2);
2318 deliverKeyEvent(new KeyEvent(curTime, curTime,
Jeff Brown49ed71d2010-12-06 17:13:33 -08002319 KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_CENTER, 0, metaState,
2320 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
2321 InputDevice.SOURCE_KEYBOARD), false);
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002322 break;
2323 case MotionEvent.ACTION_UP:
2324 x.reset(2);
2325 y.reset(2);
2326 deliverKeyEvent(new KeyEvent(curTime, curTime,
Jeff Brown49ed71d2010-12-06 17:13:33 -08002327 KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_CENTER, 0, metaState,
2328 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
2329 InputDevice.SOURCE_KEYBOARD), false);
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002330 break;
2331 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002332
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002333 if (DEBUG_TRACKBALL) Log.v(TAG, "TB X=" + x.position + " step="
2334 + x.step + " dir=" + x.dir + " acc=" + x.acceleration
2335 + " move=" + event.getX()
2336 + " / Y=" + y.position + " step="
2337 + y.step + " dir=" + y.dir + " acc=" + y.acceleration
2338 + " move=" + event.getY());
2339 final float xOff = x.collect(event.getX(), event.getEventTime(), "X");
2340 final float yOff = y.collect(event.getY(), event.getEventTime(), "Y");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002341
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002342 // Generate DPAD events based on the trackball movement.
2343 // We pick the axis that has moved the most as the direction of
2344 // the DPAD. When we generate DPAD events for one axis, then the
2345 // other axis is reset -- we don't want to perform DPAD jumps due
2346 // to slight movements in the trackball when making major movements
2347 // along the other axis.
2348 int keycode = 0;
2349 int movement = 0;
2350 float accel = 1;
2351 if (xOff > yOff) {
2352 movement = x.generate((2/event.getXPrecision()));
2353 if (movement != 0) {
2354 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_RIGHT
2355 : KeyEvent.KEYCODE_DPAD_LEFT;
2356 accel = x.acceleration;
2357 y.reset(2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002358 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002359 } else if (yOff > 0) {
2360 movement = y.generate((2/event.getYPrecision()));
2361 if (movement != 0) {
2362 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_DOWN
2363 : KeyEvent.KEYCODE_DPAD_UP;
2364 accel = y.acceleration;
2365 x.reset(2);
2366 }
2367 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002368
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002369 if (keycode != 0) {
2370 if (movement < 0) movement = -movement;
2371 int accelMovement = (int)(movement * accel);
2372 if (DEBUG_TRACKBALL) Log.v(TAG, "Move: movement=" + movement
2373 + " accelMovement=" + accelMovement
2374 + " accel=" + accel);
2375 if (accelMovement > movement) {
2376 if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: "
2377 + keycode);
2378 movement--;
Jeff Brown49ed71d2010-12-06 17:13:33 -08002379 int repeatCount = accelMovement - movement;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002380 deliverKeyEvent(new KeyEvent(curTime, curTime,
Jeff Brown49ed71d2010-12-06 17:13:33 -08002381 KeyEvent.ACTION_MULTIPLE, keycode, repeatCount, metaState,
2382 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
2383 InputDevice.SOURCE_KEYBOARD), false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002384 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002385 while (movement > 0) {
2386 if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: "
2387 + keycode);
2388 movement--;
2389 curTime = SystemClock.uptimeMillis();
2390 deliverKeyEvent(new KeyEvent(curTime, curTime,
Jeff Brown49ed71d2010-12-06 17:13:33 -08002391 KeyEvent.ACTION_DOWN, keycode, 0, metaState,
2392 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
2393 InputDevice.SOURCE_KEYBOARD), false);
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002394 deliverKeyEvent(new KeyEvent(curTime, curTime,
Jeff Brown49ed71d2010-12-06 17:13:33 -08002395 KeyEvent.ACTION_UP, keycode, 0, metaState,
2396 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
2397 InputDevice.SOURCE_KEYBOARD), false);
2398 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002399 mLastTrackballTime = curTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002400 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002401
2402 // Unfortunately we can't tell whether the application consumed the keys, so
2403 // we always consider the trackball event handled.
2404 finishTrackballEvent(event, sendDone, true);
2405 }
2406
2407 private void finishTrackballEvent(MotionEvent event, boolean sendDone, boolean handled) {
2408 event.recycle();
2409 if (sendDone) {
2410 finishInputEvent(handled);
2411 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002412 }
2413
2414 /**
2415 * @param keyCode The key code
2416 * @return True if the key is directional.
2417 */
2418 static boolean isDirectional(int keyCode) {
2419 switch (keyCode) {
2420 case KeyEvent.KEYCODE_DPAD_LEFT:
2421 case KeyEvent.KEYCODE_DPAD_RIGHT:
2422 case KeyEvent.KEYCODE_DPAD_UP:
2423 case KeyEvent.KEYCODE_DPAD_DOWN:
2424 return true;
2425 }
2426 return false;
2427 }
2428
2429 /**
2430 * Returns true if this key is a keyboard key.
2431 * @param keyEvent The key event.
2432 * @return whether this key is a keyboard key.
2433 */
2434 private static boolean isKeyboardKey(KeyEvent keyEvent) {
2435 final int convertedKey = keyEvent.getUnicodeChar();
2436 return convertedKey > 0;
2437 }
2438
2439
2440
2441 /**
2442 * See if the key event means we should leave touch mode (and leave touch
2443 * mode if so).
2444 * @param event The key event.
2445 * @return Whether this key event should be consumed (meaning the act of
2446 * leaving touch mode alone is considered the event).
2447 */
2448 private boolean checkForLeavingTouchModeAndConsume(KeyEvent event) {
Adam Powell51a6bee2010-03-15 14:07:28 -07002449 final int action = event.getAction();
2450 if (action != KeyEvent.ACTION_DOWN && action != KeyEvent.ACTION_MULTIPLE) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002451 return false;
2452 }
2453 if ((event.getFlags()&KeyEvent.FLAG_KEEP_TOUCH_MODE) != 0) {
2454 return false;
2455 }
2456
2457 // only relevant if we are in touch mode
2458 if (!mAttachInfo.mInTouchMode) {
2459 return false;
2460 }
2461
2462 // if something like an edit text has focus and the user is typing,
2463 // leave touch mode
2464 //
2465 // note: the condition of not being a keyboard key is kind of a hacky
2466 // approximation of whether we think the focused view will want the
2467 // key; if we knew for sure whether the focused view would consume
2468 // the event, that would be better.
2469 if (isKeyboardKey(event) && mView != null && mView.hasFocus()) {
2470 mFocusedView = mView.findFocus();
2471 if ((mFocusedView instanceof ViewGroup)
2472 && ((ViewGroup) mFocusedView).getDescendantFocusability() ==
2473 ViewGroup.FOCUS_AFTER_DESCENDANTS) {
2474 // something has focus, but is holding it weakly as a container
2475 return false;
2476 }
2477 if (ensureTouchMode(false)) {
2478 throw new IllegalStateException("should not have changed focus "
2479 + "when leaving touch mode while a view has focus.");
2480 }
2481 return false;
2482 }
2483
2484 if (isDirectional(event.getKeyCode())) {
2485 // no view has focus, so we leave touch mode (and find something
2486 // to give focus to). the event is consumed if we were able to
2487 // find something to give focus to.
2488 return ensureTouchMode(false);
2489 }
2490 return false;
2491 }
2492
2493 /**
Romain Guy8506ab42009-06-11 17:35:47 -07002494 * log motion events
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002495 */
2496 private static void captureMotionLog(String subTag, MotionEvent ev) {
Romain Guy8506ab42009-06-11 17:35:47 -07002497 //check dynamic switch
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002498 if (ev == null ||
2499 SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_EVENT, 0) == 0) {
2500 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002501 }
Romain Guy8506ab42009-06-11 17:35:47 -07002502
2503 StringBuilder sb = new StringBuilder(subTag + ": ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002504 sb.append(ev.getDownTime()).append(',');
2505 sb.append(ev.getEventTime()).append(',');
2506 sb.append(ev.getAction()).append(',');
Romain Guy8506ab42009-06-11 17:35:47 -07002507 sb.append(ev.getX()).append(',');
2508 sb.append(ev.getY()).append(',');
2509 sb.append(ev.getPressure()).append(',');
2510 sb.append(ev.getSize()).append(',');
2511 sb.append(ev.getMetaState()).append(',');
2512 sb.append(ev.getXPrecision()).append(',');
2513 sb.append(ev.getYPrecision()).append(',');
2514 sb.append(ev.getDeviceId()).append(',');
2515 sb.append(ev.getEdgeFlags());
2516 Log.d(TAG, sb.toString());
2517 }
2518 /**
2519 * log motion events
2520 */
2521 private static void captureKeyLog(String subTag, KeyEvent ev) {
2522 //check dynamic switch
2523 if (ev == null ||
2524 SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_EVENT, 0) == 0) {
2525 return;
2526 }
2527 StringBuilder sb = new StringBuilder(subTag + ": ");
2528 sb.append(ev.getDownTime()).append(',');
2529 sb.append(ev.getEventTime()).append(',');
2530 sb.append(ev.getAction()).append(',');
2531 sb.append(ev.getKeyCode()).append(',');
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002532 sb.append(ev.getRepeatCount()).append(',');
2533 sb.append(ev.getMetaState()).append(',');
2534 sb.append(ev.getDeviceId()).append(',');
2535 sb.append(ev.getScanCode());
Romain Guy8506ab42009-06-11 17:35:47 -07002536 Log.d(TAG, sb.toString());
2537 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002538
2539 int enqueuePendingEvent(Object event, boolean sendDone) {
2540 int seq = mPendingEventSeq+1;
2541 if (seq < 0) seq = 0;
2542 mPendingEventSeq = seq;
2543 mPendingEvents.put(seq, event);
2544 return sendDone ? seq : -seq;
2545 }
2546
2547 Object retrievePendingEvent(int seq) {
2548 if (seq < 0) seq = -seq;
2549 Object event = mPendingEvents.get(seq);
2550 if (event != null) {
2551 mPendingEvents.remove(seq);
2552 }
2553 return event;
2554 }
Romain Guy8506ab42009-06-11 17:35:47 -07002555
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002556 private void deliverKeyEvent(KeyEvent event, boolean sendDone) {
Jeff Brown3915bb82010-11-05 15:02:16 -07002557 // If there is no view, then the event will not be handled.
2558 if (mView == null || !mAdded) {
2559 finishKeyEvent(event, sendDone, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002560 return;
2561 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002562
2563 if (LOCAL_LOGV) Log.v(TAG, "Dispatching key " + event + " to " + mView);
2564
2565 // Perform predispatching before the IME.
2566 if (mView.dispatchKeyEventPreIme(event)) {
2567 finishKeyEvent(event, sendDone, true);
2568 return;
2569 }
2570
2571 // Dispatch to the IME before propagating down the view hierarchy.
2572 // The IME will eventually call back into handleFinishedEvent.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002573 if (mLastWasImTarget) {
2574 InputMethodManager imm = InputMethodManager.peekInstance();
Jeff Brown3915bb82010-11-05 15:02:16 -07002575 if (imm != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002576 int seq = enqueuePendingEvent(event, sendDone);
2577 if (DEBUG_IMF) Log.v(TAG, "Sending key event to IME: seq="
2578 + seq + " event=" + event);
Jeff Brown3915bb82010-11-05 15:02:16 -07002579 imm.dispatchKeyEvent(mView.getContext(), seq, event, mInputMethodCallback);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002580 return;
2581 }
2582 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002583
2584 // Not dispatching to IME, continue with post IME actions.
2585 deliverKeyEventPostIme(event, sendDone);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002586 }
2587
Jeff Brown3915bb82010-11-05 15:02:16 -07002588 private void handleFinishedEvent(int seq, boolean handled) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002589 final KeyEvent event = (KeyEvent)retrievePendingEvent(seq);
2590 if (DEBUG_IMF) Log.v(TAG, "IME finished event: seq=" + seq
2591 + " handled=" + handled + " event=" + event);
2592 if (event != null) {
2593 final boolean sendDone = seq >= 0;
Jeff Brown3915bb82010-11-05 15:02:16 -07002594 if (handled) {
2595 finishKeyEvent(event, sendDone, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002596 } else {
Jeff Brown3915bb82010-11-05 15:02:16 -07002597 deliverKeyEventPostIme(event, sendDone);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002598 }
2599 }
2600 }
Romain Guy8506ab42009-06-11 17:35:47 -07002601
Jeff Brown3915bb82010-11-05 15:02:16 -07002602 private void deliverKeyEventPostIme(KeyEvent event, boolean sendDone) {
2603 // If the view went away, then the event will not be handled.
2604 if (mView == null || !mAdded) {
2605 finishKeyEvent(event, sendDone, false);
2606 return;
2607 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002608
Jeff Brown3915bb82010-11-05 15:02:16 -07002609 // If the key's purpose is to exit touch mode then we consume it and consider it handled.
2610 if (checkForLeavingTouchModeAndConsume(event)) {
2611 finishKeyEvent(event, sendDone, true);
2612 return;
2613 }
Romain Guy8506ab42009-06-11 17:35:47 -07002614
Jeff Brown3915bb82010-11-05 15:02:16 -07002615 if (Config.LOGV) {
2616 captureKeyLog("captureDispatchKeyEvent", event);
2617 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002618
Jeff Brown90655042010-12-02 13:50:46 -08002619 // Make sure the fallback event policy sees all keys that will be delivered to the
2620 // view hierarchy.
2621 mFallbackEventHandler.preDispatchKeyEvent(event);
2622
Jeff Brown3915bb82010-11-05 15:02:16 -07002623 // Deliver the key to the view hierarchy.
2624 if (mView.dispatchKeyEvent(event)) {
2625 finishKeyEvent(event, sendDone, true);
2626 return;
2627 }
Joe Onorato86f67862010-11-05 18:57:34 -07002628
Jeff Brown3915bb82010-11-05 15:02:16 -07002629 // Apply the fallback event policy.
2630 if (mFallbackEventHandler.dispatchKeyEvent(event)) {
2631 finishKeyEvent(event, sendDone, true);
2632 return;
2633 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002634
Jeff Brown3915bb82010-11-05 15:02:16 -07002635 // Handle automatic focus changes.
2636 if (event.getAction() == KeyEvent.ACTION_DOWN) {
2637 int direction = 0;
2638 switch (event.getKeyCode()) {
2639 case KeyEvent.KEYCODE_DPAD_LEFT:
2640 direction = View.FOCUS_LEFT;
2641 break;
2642 case KeyEvent.KEYCODE_DPAD_RIGHT:
2643 direction = View.FOCUS_RIGHT;
2644 break;
2645 case KeyEvent.KEYCODE_DPAD_UP:
2646 direction = View.FOCUS_UP;
2647 break;
2648 case KeyEvent.KEYCODE_DPAD_DOWN:
2649 direction = View.FOCUS_DOWN;
2650 break;
2651 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002652
Jeff Brown3915bb82010-11-05 15:02:16 -07002653 if (direction != 0) {
2654 View focused = mView != null ? mView.findFocus() : null;
2655 if (focused != null) {
2656 View v = focused.focusSearch(direction);
2657 if (v != null && v != focused) {
2658 // do the math the get the interesting rect
2659 // of previous focused into the coord system of
2660 // newly focused view
2661 focused.getFocusedRect(mTempRect);
2662 if (mView instanceof ViewGroup) {
2663 ((ViewGroup) mView).offsetDescendantRectToMyCoords(
2664 focused, mTempRect);
2665 ((ViewGroup) mView).offsetRectIntoDescendantCoords(
2666 v, mTempRect);
2667 }
2668 if (v.requestFocus(direction, mTempRect)) {
2669 playSoundEffect(
2670 SoundEffectConstants.getContantForFocusDirection(direction));
2671 finishKeyEvent(event, sendDone, true);
2672 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002673 }
2674 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002675
2676 // Give the focused view a last chance to handle the dpad key.
2677 if (mView.dispatchUnhandledMove(focused, direction)) {
2678 finishKeyEvent(event, sendDone, true);
2679 return;
2680 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002681 }
2682 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002683 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002684
Jeff Brown3915bb82010-11-05 15:02:16 -07002685 // Key was unhandled.
2686 finishKeyEvent(event, sendDone, false);
2687 }
2688
2689 private void finishKeyEvent(KeyEvent event, boolean sendDone, boolean handled) {
2690 if (sendDone) {
2691 finishInputEvent(handled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002692 }
2693 }
2694
Christopher Tatea53146c2010-09-07 11:57:52 -07002695 /* drag/drop */
Christopher Tate407b4e92010-11-30 17:14:08 -08002696 void setLocalDragState(Object obj) {
2697 mLocalDragState = obj;
2698 }
2699
Christopher Tatea53146c2010-09-07 11:57:52 -07002700 private void handleDragEvent(DragEvent event) {
2701 // From the root, only drag start/end/location are dispatched. entered/exited
2702 // are determined and dispatched by the viewgroup hierarchy, who then report
2703 // that back here for ultimate reporting back to the framework.
2704 if (mView != null && mAdded) {
2705 final int what = event.mAction;
2706
2707 if (what == DragEvent.ACTION_DRAG_EXITED) {
2708 // A direct EXITED event means that the window manager knows we've just crossed
2709 // a window boundary, so the current drag target within this one must have
2710 // just been exited. Send it the usual notifications and then we're done
2711 // for now.
Chris Tate9d1ab882010-11-02 15:55:39 -07002712 mView.dispatchDragEvent(event);
Christopher Tatea53146c2010-09-07 11:57:52 -07002713 } else {
2714 // Cache the drag description when the operation starts, then fill it in
2715 // on subsequent calls as a convenience
2716 if (what == DragEvent.ACTION_DRAG_STARTED) {
Chris Tate9d1ab882010-11-02 15:55:39 -07002717 mCurrentDragView = null; // Start the current-recipient tracking
Christopher Tatea53146c2010-09-07 11:57:52 -07002718 mDragDescription = event.mClipDescription;
2719 } else {
2720 event.mClipDescription = mDragDescription;
2721 }
2722
2723 // For events with a [screen] location, translate into window coordinates
2724 if ((what == DragEvent.ACTION_DRAG_LOCATION) || (what == DragEvent.ACTION_DROP)) {
2725 mDragPoint.set(event.mX, event.mY);
2726 if (mTranslator != null) {
2727 mTranslator.translatePointInScreenToAppWindow(mDragPoint);
2728 }
2729
2730 if (mCurScrollY != 0) {
2731 mDragPoint.offset(0, mCurScrollY);
2732 }
2733
2734 event.mX = mDragPoint.x;
2735 event.mY = mDragPoint.y;
2736 }
2737
2738 // Remember who the current drag target is pre-dispatch
2739 final View prevDragView = mCurrentDragView;
2740
2741 // Now dispatch the drag/drop event
Chris Tated4533f12010-10-19 15:15:08 -07002742 boolean result = mView.dispatchDragEvent(event);
Christopher Tatea53146c2010-09-07 11:57:52 -07002743
2744 // If we changed apparent drag target, tell the OS about it
2745 if (prevDragView != mCurrentDragView) {
2746 try {
2747 if (prevDragView != null) {
2748 sWindowSession.dragRecipientExited(mWindow);
2749 }
2750 if (mCurrentDragView != null) {
2751 sWindowSession.dragRecipientEntered(mWindow);
2752 }
2753 } catch (RemoteException e) {
2754 Slog.e(TAG, "Unable to note drag target change");
2755 }
Christopher Tatea53146c2010-09-07 11:57:52 -07002756 }
Chris Tated4533f12010-10-19 15:15:08 -07002757
Christopher Tate407b4e92010-11-30 17:14:08 -08002758 // Report the drop result when we're done
Chris Tated4533f12010-10-19 15:15:08 -07002759 if (what == DragEvent.ACTION_DROP) {
2760 try {
2761 Log.i(TAG, "Reporting drop result: " + result);
2762 sWindowSession.reportDropResult(mWindow, result);
2763 } catch (RemoteException e) {
2764 Log.e(TAG, "Unable to report drop result");
2765 }
2766 }
Christopher Tate407b4e92010-11-30 17:14:08 -08002767
2768 // When the drag operation ends, release any local state object
2769 // that may have been in use
2770 if (what == DragEvent.ACTION_DRAG_ENDED) {
2771 setLocalDragState(null);
2772 }
Christopher Tatea53146c2010-09-07 11:57:52 -07002773 }
2774 }
2775 event.recycle();
2776 }
2777
Christopher Tate2c095f32010-10-04 14:13:40 -07002778 public void getLastTouchPoint(Point outLocation) {
2779 outLocation.x = (int) mLastTouchPoint.x;
2780 outLocation.y = (int) mLastTouchPoint.y;
2781 }
2782
Chris Tate9d1ab882010-11-02 15:55:39 -07002783 public void setDragFocus(View newDragTarget) {
Christopher Tatea53146c2010-09-07 11:57:52 -07002784 if (mCurrentDragView != newDragTarget) {
Chris Tate048691c2010-10-12 17:39:18 -07002785 mCurrentDragView = newDragTarget;
Christopher Tatea53146c2010-09-07 11:57:52 -07002786 }
Christopher Tatea53146c2010-09-07 11:57:52 -07002787 }
2788
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002789 private AudioManager getAudioManager() {
2790 if (mView == null) {
2791 throw new IllegalStateException("getAudioManager called when there is no mView");
2792 }
2793 if (mAudioManager == null) {
2794 mAudioManager = (AudioManager) mView.getContext().getSystemService(Context.AUDIO_SERVICE);
2795 }
2796 return mAudioManager;
2797 }
2798
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002799 private int relayoutWindow(WindowManager.LayoutParams params, int viewVisibility,
2800 boolean insetsPending) throws RemoteException {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002801
2802 float appScale = mAttachInfo.mApplicationScale;
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002803 boolean restore = false;
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002804 if (params != null && mTranslator != null) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07002805 restore = true;
2806 params.backup();
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002807 mTranslator.translateWindowLayout(params);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002808 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002809 if (params != null) {
2810 if (DBG) Log.d(TAG, "WindowLayout in layoutWindow:" + params);
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002811 }
Dianne Hackborn694f79b2010-03-17 19:44:59 -07002812 mPendingConfiguration.seq = 0;
Dianne Hackbornf123e492010-09-24 11:16:23 -07002813 //Log.d(TAG, ">>>>>> CALLING relayout");
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002814 int relayoutResult = sWindowSession.relayout(
2815 mWindow, params,
Dianne Hackborn189ee182010-12-02 21:48:53 -08002816 (int) (mView.getMeasuredWidth() * appScale + 0.5f),
2817 (int) (mView.getMeasuredHeight() * appScale + 0.5f),
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002818 viewVisibility, insetsPending, mWinFrame,
Dianne Hackborn694f79b2010-03-17 19:44:59 -07002819 mPendingContentInsets, mPendingVisibleInsets,
2820 mPendingConfiguration, mSurface);
Dianne Hackbornf123e492010-09-24 11:16:23 -07002821 //Log.d(TAG, "<<<<<< BACK FROM relayout");
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002822 if (restore) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07002823 params.restore();
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002824 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002825
2826 if (mTranslator != null) {
2827 mTranslator.translateRectInScreenToAppWinFrame(mWinFrame);
2828 mTranslator.translateRectInScreenToAppWindow(mPendingContentInsets);
2829 mTranslator.translateRectInScreenToAppWindow(mPendingVisibleInsets);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002830 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002831 return relayoutResult;
2832 }
Romain Guy8506ab42009-06-11 17:35:47 -07002833
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002834 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002835 * {@inheritDoc}
2836 */
2837 public void playSoundEffect(int effectId) {
2838 checkThread();
2839
Jean-Michel Trivi13b18fd2010-05-05 09:18:15 -07002840 try {
2841 final AudioManager audioManager = getAudioManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002842
Jean-Michel Trivi13b18fd2010-05-05 09:18:15 -07002843 switch (effectId) {
2844 case SoundEffectConstants.CLICK:
2845 audioManager.playSoundEffect(AudioManager.FX_KEY_CLICK);
2846 return;
2847 case SoundEffectConstants.NAVIGATION_DOWN:
2848 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_DOWN);
2849 return;
2850 case SoundEffectConstants.NAVIGATION_LEFT:
2851 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_LEFT);
2852 return;
2853 case SoundEffectConstants.NAVIGATION_RIGHT:
2854 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_RIGHT);
2855 return;
2856 case SoundEffectConstants.NAVIGATION_UP:
2857 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_UP);
2858 return;
2859 default:
2860 throw new IllegalArgumentException("unknown effect id " + effectId +
2861 " not defined in " + SoundEffectConstants.class.getCanonicalName());
2862 }
2863 } catch (IllegalStateException e) {
2864 // Exception thrown by getAudioManager() when mView is null
2865 Log.e(TAG, "FATAL EXCEPTION when attempting to play sound effect: " + e);
2866 e.printStackTrace();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002867 }
2868 }
2869
2870 /**
2871 * {@inheritDoc}
2872 */
2873 public boolean performHapticFeedback(int effectId, boolean always) {
2874 try {
2875 return sWindowSession.performHapticFeedback(mWindow, effectId, always);
2876 } catch (RemoteException e) {
2877 return false;
2878 }
2879 }
2880
2881 /**
2882 * {@inheritDoc}
2883 */
2884 public View focusSearch(View focused, int direction) {
2885 checkThread();
2886 if (!(mView instanceof ViewGroup)) {
2887 return null;
2888 }
2889 return FocusFinder.getInstance().findNextFocus((ViewGroup) mView, focused, direction);
2890 }
2891
2892 public void debug() {
2893 mView.debug();
2894 }
2895
2896 public void die(boolean immediate) {
Dianne Hackborn94d69142009-09-28 22:14:42 -07002897 if (immediate) {
2898 doDie();
2899 } else {
2900 sendEmptyMessage(DIE);
2901 }
2902 }
2903
2904 void doDie() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002905 checkThread();
Jeff Brownb75fa302010-07-15 23:47:29 -07002906 if (LOCAL_LOGV) Log.v(TAG, "DIE in " + this + " of " + mSurface);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002907 synchronized (this) {
2908 if (mAdded && !mFirst) {
Romain Guy29d89972010-09-22 16:10:57 -07002909 destroyHardwareRenderer();
2910
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002911 int viewVisibility = mView.getVisibility();
2912 boolean viewVisibilityChanged = mViewVisibility != viewVisibility;
2913 if (mWindowAttributesChanged || viewVisibilityChanged) {
2914 // If layout params have been changed, first give them
2915 // to the window manager to make sure it has the correct
2916 // animation info.
2917 try {
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002918 if ((relayoutWindow(mWindowAttributes, viewVisibility, false)
2919 & WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002920 sWindowSession.finishDrawing(mWindow);
2921 }
2922 } catch (RemoteException e) {
2923 }
2924 }
2925
Dianne Hackborn0586a1b2009-09-06 21:08:27 -07002926 mSurface.release();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002927 }
2928 if (mAdded) {
2929 mAdded = false;
Dianne Hackborn94d69142009-09-28 22:14:42 -07002930 dispatchDetachedFromWindow();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002931 }
2932 }
2933 }
2934
Romain Guy29d89972010-09-22 16:10:57 -07002935 private void destroyHardwareRenderer() {
Romain Guyb051e892010-09-28 19:09:36 -07002936 if (mAttachInfo.mHardwareRenderer != null) {
2937 mAttachInfo.mHardwareRenderer.destroy(true);
2938 mAttachInfo.mHardwareRenderer = null;
Romain Guy29d89972010-09-22 16:10:57 -07002939 mAttachInfo.mHardwareAccelerated = false;
2940 }
2941 }
2942
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002943 public void dispatchFinishedEvent(int seq, boolean handled) {
2944 Message msg = obtainMessage(FINISHED_EVENT);
2945 msg.arg1 = seq;
2946 msg.arg2 = handled ? 1 : 0;
2947 sendMessage(msg);
2948 }
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002949
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002950 public void dispatchResized(int w, int h, Rect coveredInsets,
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002951 Rect visibleInsets, boolean reportDraw, Configuration newConfig) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002952 if (DEBUG_LAYOUT) Log.v(TAG, "Resizing " + this + ": w=" + w
2953 + " h=" + h + " coveredInsets=" + coveredInsets.toShortString()
2954 + " visibleInsets=" + visibleInsets.toShortString()
2955 + " reportDraw=" + reportDraw);
2956 Message msg = obtainMessage(reportDraw ? RESIZED_REPORT :RESIZED);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002957 if (mTranslator != null) {
2958 mTranslator.translateRectInScreenToAppWindow(coveredInsets);
2959 mTranslator.translateRectInScreenToAppWindow(visibleInsets);
2960 w *= mTranslator.applicationInvertedScale;
2961 h *= mTranslator.applicationInvertedScale;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002962 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002963 msg.arg1 = w;
2964 msg.arg2 = h;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002965 ResizedInfo ri = new ResizedInfo();
2966 ri.coveredInsets = new Rect(coveredInsets);
2967 ri.visibleInsets = new Rect(visibleInsets);
2968 ri.newConfig = newConfig;
2969 msg.obj = ri;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002970 sendMessage(msg);
2971 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002972
Jeff Brown3915bb82010-11-05 15:02:16 -07002973 private InputQueue.FinishedCallback mFinishedCallback;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002974
2975 private final InputHandler mInputHandler = new InputHandler() {
Jeff Brown3915bb82010-11-05 15:02:16 -07002976 public void handleKey(KeyEvent event, InputQueue.FinishedCallback finishedCallback) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07002977 startInputEvent(finishedCallback);
Jeff Brown92ff1dd2010-08-11 16:16:06 -07002978 dispatchKey(event, true);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002979 }
2980
Jeff Brown3915bb82010-11-05 15:02:16 -07002981 public void handleMotion(MotionEvent event, InputQueue.FinishedCallback finishedCallback) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07002982 startInputEvent(finishedCallback);
2983 dispatchMotion(event, true);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002984 }
2985 };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002986
2987 public void dispatchKey(KeyEvent event) {
Jeff Brown92ff1dd2010-08-11 16:16:06 -07002988 dispatchKey(event, false);
2989 }
2990
2991 private void dispatchKey(KeyEvent event, boolean sendDone) {
2992 //noinspection ConstantConditions
2993 if (false && event.getAction() == KeyEvent.ACTION_DOWN) {
2994 if (event.getKeyCode() == KeyEvent.KEYCODE_CAMERA) {
Romain Guy812ccbe2010-06-01 14:07:24 -07002995 if (DBG) Log.d("keydisp", "===================================================");
2996 if (DBG) Log.d("keydisp", "Focused view Hierarchy is:");
2997
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002998 debug();
2999
Romain Guy812ccbe2010-06-01 14:07:24 -07003000 if (DBG) Log.d("keydisp", "===================================================");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003001 }
3002 }
3003
3004 Message msg = obtainMessage(DISPATCH_KEY);
3005 msg.obj = event;
Jeff Brown92ff1dd2010-08-11 16:16:06 -07003006 msg.arg1 = sendDone ? 1 : 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003007
3008 if (LOCAL_LOGV) Log.v(
Jeff Brownc5ed5912010-07-14 18:48:53 -07003009 TAG, "sending key " + event + " to " + mView);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003010
3011 sendMessageAtTime(msg, event.getEventTime());
3012 }
Jeff Brownc5ed5912010-07-14 18:48:53 -07003013
3014 public void dispatchMotion(MotionEvent event) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07003015 dispatchMotion(event, false);
3016 }
3017
3018 private void dispatchMotion(MotionEvent event, boolean sendDone) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07003019 int source = event.getSource();
3020 if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07003021 dispatchPointer(event, sendDone);
Jeff Brownc5ed5912010-07-14 18:48:53 -07003022 } else if ((source & InputDevice.SOURCE_CLASS_TRACKBALL) != 0) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07003023 dispatchTrackball(event, sendDone);
Jeff Brownc5ed5912010-07-14 18:48:53 -07003024 } else {
3025 // TODO
3026 Log.v(TAG, "Dropping unsupported motion event (unimplemented): " + event);
Jeff Brown93ed4e32010-09-23 13:51:48 -07003027 if (sendDone) {
Jeff Brown3915bb82010-11-05 15:02:16 -07003028 finishInputEvent(false);
Jeff Brown93ed4e32010-09-23 13:51:48 -07003029 }
Jeff Brownc5ed5912010-07-14 18:48:53 -07003030 }
3031 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003032
Jeff Brown00fa7bd2010-07-02 15:37:36 -07003033 public void dispatchPointer(MotionEvent event) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07003034 dispatchPointer(event, false);
3035 }
3036
3037 private void dispatchPointer(MotionEvent event, boolean sendDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003038 Message msg = obtainMessage(DISPATCH_POINTER);
3039 msg.obj = event;
Jeff Brown93ed4e32010-09-23 13:51:48 -07003040 msg.arg1 = sendDone ? 1 : 0;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07003041 sendMessageAtTime(msg, event.getEventTime());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003042 }
3043
Jeff Brown00fa7bd2010-07-02 15:37:36 -07003044 public void dispatchTrackball(MotionEvent event) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07003045 dispatchTrackball(event, false);
3046 }
3047
3048 private void dispatchTrackball(MotionEvent event, boolean sendDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003049 Message msg = obtainMessage(DISPATCH_TRACKBALL);
3050 msg.obj = event;
Jeff Brown93ed4e32010-09-23 13:51:48 -07003051 msg.arg1 = sendDone ? 1 : 0;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07003052 sendMessageAtTime(msg, event.getEventTime());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003053 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07003054
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003055 public void dispatchAppVisibility(boolean visible) {
3056 Message msg = obtainMessage(DISPATCH_APP_VISIBILITY);
3057 msg.arg1 = visible ? 1 : 0;
3058 sendMessage(msg);
3059 }
3060
3061 public void dispatchGetNewSurface() {
3062 Message msg = obtainMessage(DISPATCH_GET_NEW_SURFACE);
3063 sendMessage(msg);
3064 }
3065
3066 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
3067 Message msg = Message.obtain();
3068 msg.what = WINDOW_FOCUS_CHANGED;
3069 msg.arg1 = hasFocus ? 1 : 0;
3070 msg.arg2 = inTouchMode ? 1 : 0;
3071 sendMessage(msg);
3072 }
3073
Dianne Hackbornffa42482009-09-23 22:20:11 -07003074 public void dispatchCloseSystemDialogs(String reason) {
3075 Message msg = Message.obtain();
3076 msg.what = CLOSE_SYSTEM_DIALOGS;
3077 msg.obj = reason;
3078 sendMessage(msg);
3079 }
Christopher Tatea53146c2010-09-07 11:57:52 -07003080
3081 public void dispatchDragEvent(DragEvent event) {
Chris Tate91e9bb32010-10-12 12:58:43 -07003082 final int what;
3083 if (event.getAction() == DragEvent.ACTION_DRAG_LOCATION) {
3084 what = DISPATCH_DRAG_LOCATION_EVENT;
3085 removeMessages(what);
3086 } else {
3087 what = DISPATCH_DRAG_EVENT;
3088 }
Christopher Tate407b4e92010-11-30 17:14:08 -08003089 event.mLocalState = mLocalDragState; // only present when this app called startDrag()
Chris Tate91e9bb32010-10-12 12:58:43 -07003090 Message msg = obtainMessage(what, event);
Christopher Tatea53146c2010-09-07 11:57:52 -07003091 sendMessage(msg);
3092 }
3093
svetoslavganov75986cf2009-05-14 22:28:01 -07003094 /**
3095 * The window is getting focus so if there is anything focused/selected
3096 * send an {@link AccessibilityEvent} to announce that.
3097 */
3098 private void sendAccessibilityEvents() {
3099 if (!AccessibilityManager.getInstance(mView.getContext()).isEnabled()) {
3100 return;
3101 }
3102 mView.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
3103 View focusedView = mView.findFocus();
3104 if (focusedView != null && focusedView != mView) {
3105 focusedView.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
3106 }
3107 }
3108
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003109 public boolean showContextMenuForChild(View originalView) {
3110 return false;
3111 }
3112
Adam Powell6e346362010-07-23 10:18:23 -07003113 public ActionMode startActionModeForChild(View originalView, ActionMode.Callback callback) {
3114 return null;
3115 }
3116
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003117 public void createContextMenu(ContextMenu menu) {
3118 }
3119
3120 public void childDrawableStateChanged(View child) {
3121 }
3122
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003123 void checkThread() {
3124 if (mThread != Thread.currentThread()) {
3125 throw new CalledFromWrongThreadException(
3126 "Only the original thread that created a view hierarchy can touch its views.");
3127 }
3128 }
3129
3130 public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
3131 // ViewRoot never intercepts touch event, so this can be a no-op
3132 }
3133
3134 public boolean requestChildRectangleOnScreen(View child, Rect rectangle,
3135 boolean immediate) {
3136 return scrollToRectOrFocus(rectangle, immediate);
3137 }
Romain Guy8506ab42009-06-11 17:35:47 -07003138
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07003139 class TakenSurfaceHolder extends BaseSurfaceHolder {
3140 @Override
3141 public boolean onAllowLockCanvas() {
3142 return mDrawingAllowed;
3143 }
3144
3145 @Override
3146 public void onRelayoutContainer() {
3147 // Not currently interesting -- from changing between fixed and layout size.
3148 }
3149
3150 public void setFormat(int format) {
3151 ((RootViewSurfaceTaker)mView).setSurfaceFormat(format);
3152 }
3153
3154 public void setType(int type) {
3155 ((RootViewSurfaceTaker)mView).setSurfaceType(type);
3156 }
3157
3158 @Override
3159 public void onUpdateSurface() {
3160 // We take care of format and type changes on our own.
3161 throw new IllegalStateException("Shouldn't be here");
3162 }
3163
3164 public boolean isCreating() {
3165 return mIsCreating;
3166 }
3167
3168 @Override
3169 public void setFixedSize(int width, int height) {
3170 throw new UnsupportedOperationException(
3171 "Currently only support sizing from layout");
3172 }
3173
3174 public void setKeepScreenOn(boolean screenOn) {
3175 ((RootViewSurfaceTaker)mView).setSurfaceKeepScreenOn(screenOn);
3176 }
3177 }
3178
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003179 static class InputMethodCallback extends IInputMethodCallback.Stub {
3180 private WeakReference<ViewRoot> mViewRoot;
3181
3182 public InputMethodCallback(ViewRoot viewRoot) {
3183 mViewRoot = new WeakReference<ViewRoot>(viewRoot);
3184 }
Romain Guy8506ab42009-06-11 17:35:47 -07003185
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003186 public void finishedEvent(int seq, boolean handled) {
3187 final ViewRoot viewRoot = mViewRoot.get();
3188 if (viewRoot != null) {
3189 viewRoot.dispatchFinishedEvent(seq, handled);
3190 }
3191 }
3192
3193 public void sessionCreated(IInputMethodSession session) throws RemoteException {
3194 // Stub -- not for use in the client.
3195 }
3196 }
Romain Guy8506ab42009-06-11 17:35:47 -07003197
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003198 static class W extends IWindow.Stub {
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07003199 private final WeakReference<ViewRoot> mViewRoot;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003200
Romain Guyfb8b7632010-08-23 21:05:08 -07003201 W(ViewRoot viewRoot) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003202 mViewRoot = new WeakReference<ViewRoot>(viewRoot);
3203 }
3204
Romain Guyfb8b7632010-08-23 21:05:08 -07003205 public void resized(int w, int h, Rect coveredInsets, Rect visibleInsets,
3206 boolean reportDraw, Configuration newConfig) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003207 final ViewRoot viewRoot = mViewRoot.get();
3208 if (viewRoot != null) {
Romain Guyfb8b7632010-08-23 21:05:08 -07003209 viewRoot.dispatchResized(w, h, coveredInsets, visibleInsets, reportDraw, newConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003210 }
3211 }
3212
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003213 public void dispatchAppVisibility(boolean visible) {
3214 final ViewRoot viewRoot = mViewRoot.get();
3215 if (viewRoot != null) {
3216 viewRoot.dispatchAppVisibility(visible);
3217 }
3218 }
3219
3220 public void dispatchGetNewSurface() {
3221 final ViewRoot viewRoot = mViewRoot.get();
3222 if (viewRoot != null) {
3223 viewRoot.dispatchGetNewSurface();
3224 }
3225 }
3226
3227 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
3228 final ViewRoot viewRoot = mViewRoot.get();
3229 if (viewRoot != null) {
3230 viewRoot.windowFocusChanged(hasFocus, inTouchMode);
3231 }
3232 }
3233
3234 private static int checkCallingPermission(String permission) {
3235 if (!Process.supportsProcesses()) {
3236 return PackageManager.PERMISSION_GRANTED;
3237 }
3238
3239 try {
3240 return ActivityManagerNative.getDefault().checkPermission(
3241 permission, Binder.getCallingPid(), Binder.getCallingUid());
3242 } catch (RemoteException e) {
3243 return PackageManager.PERMISSION_DENIED;
3244 }
3245 }
3246
3247 public void executeCommand(String command, String parameters, ParcelFileDescriptor out) {
3248 final ViewRoot viewRoot = mViewRoot.get();
3249 if (viewRoot != null) {
3250 final View view = viewRoot.mView;
3251 if (view != null) {
3252 if (checkCallingPermission(Manifest.permission.DUMP) !=
3253 PackageManager.PERMISSION_GRANTED) {
3254 throw new SecurityException("Insufficient permissions to invoke"
3255 + " executeCommand() from pid=" + Binder.getCallingPid()
3256 + ", uid=" + Binder.getCallingUid());
3257 }
3258
3259 OutputStream clientStream = null;
3260 try {
3261 clientStream = new ParcelFileDescriptor.AutoCloseOutputStream(out);
3262 ViewDebug.dispatchCommand(view, command, parameters, clientStream);
3263 } catch (IOException e) {
3264 e.printStackTrace();
3265 } finally {
3266 if (clientStream != null) {
3267 try {
3268 clientStream.close();
3269 } catch (IOException e) {
3270 e.printStackTrace();
3271 }
3272 }
3273 }
3274 }
3275 }
3276 }
Dianne Hackborn72c82ab2009-08-11 21:13:54 -07003277
Dianne Hackbornffa42482009-09-23 22:20:11 -07003278 public void closeSystemDialogs(String reason) {
3279 final ViewRoot viewRoot = mViewRoot.get();
3280 if (viewRoot != null) {
3281 viewRoot.dispatchCloseSystemDialogs(reason);
3282 }
3283 }
3284
Marco Nelissenbf6956b2009-11-09 15:21:13 -08003285 public void dispatchWallpaperOffsets(float x, float y, float xStep, float yStep,
3286 boolean sync) {
Dianne Hackborn19382ac2009-09-11 21:13:37 -07003287 if (sync) {
3288 try {
3289 sWindowSession.wallpaperOffsetsComplete(asBinder());
3290 } catch (RemoteException e) {
3291 }
3292 }
Dianne Hackborn72c82ab2009-08-11 21:13:54 -07003293 }
Dianne Hackborn75804932009-10-20 20:15:20 -07003294
3295 public void dispatchWallpaperCommand(String action, int x, int y,
3296 int z, Bundle extras, boolean sync) {
3297 if (sync) {
3298 try {
3299 sWindowSession.wallpaperCommandComplete(asBinder(), null);
3300 } catch (RemoteException e) {
3301 }
3302 }
3303 }
Christopher Tatea53146c2010-09-07 11:57:52 -07003304
3305 /* Drag/drop */
3306 public void dispatchDragEvent(DragEvent event) {
3307 final ViewRoot viewRoot = mViewRoot.get();
3308 if (viewRoot != null) {
3309 viewRoot.dispatchDragEvent(event);
3310 }
3311 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003312 }
3313
3314 /**
3315 * Maintains state information for a single trackball axis, generating
3316 * discrete (DPAD) movements based on raw trackball motion.
3317 */
3318 static final class TrackballAxis {
3319 /**
3320 * The maximum amount of acceleration we will apply.
3321 */
3322 static final float MAX_ACCELERATION = 20;
Romain Guy8506ab42009-06-11 17:35:47 -07003323
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003324 /**
3325 * The maximum amount of time (in milliseconds) between events in order
3326 * for us to consider the user to be doing fast trackball movements,
3327 * and thus apply an acceleration.
3328 */
3329 static final long FAST_MOVE_TIME = 150;
Romain Guy8506ab42009-06-11 17:35:47 -07003330
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003331 /**
3332 * Scaling factor to the time (in milliseconds) between events to how
3333 * much to multiple/divide the current acceleration. When movement
3334 * is < FAST_MOVE_TIME this multiplies the acceleration; when >
3335 * FAST_MOVE_TIME it divides it.
3336 */
3337 static final float ACCEL_MOVE_SCALING_FACTOR = (1.0f/40);
Romain Guy8506ab42009-06-11 17:35:47 -07003338
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003339 float position;
3340 float absPosition;
3341 float acceleration = 1;
3342 long lastMoveTime = 0;
3343 int step;
3344 int dir;
3345 int nonAccelMovement;
3346
3347 void reset(int _step) {
3348 position = 0;
3349 acceleration = 1;
3350 lastMoveTime = 0;
3351 step = _step;
3352 dir = 0;
3353 }
3354
3355 /**
3356 * Add trackball movement into the state. If the direction of movement
3357 * has been reversed, the state is reset before adding the
3358 * movement (so that you don't have to compensate for any previously
3359 * collected movement before see the result of the movement in the
3360 * new direction).
3361 *
3362 * @return Returns the absolute value of the amount of movement
3363 * collected so far.
3364 */
3365 float collect(float off, long time, String axis) {
3366 long normTime;
3367 if (off > 0) {
3368 normTime = (long)(off * FAST_MOVE_TIME);
3369 if (dir < 0) {
3370 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to positive!");
3371 position = 0;
3372 step = 0;
3373 acceleration = 1;
3374 lastMoveTime = 0;
3375 }
3376 dir = 1;
3377 } else if (off < 0) {
3378 normTime = (long)((-off) * FAST_MOVE_TIME);
3379 if (dir > 0) {
3380 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to negative!");
3381 position = 0;
3382 step = 0;
3383 acceleration = 1;
3384 lastMoveTime = 0;
3385 }
3386 dir = -1;
3387 } else {
3388 normTime = 0;
3389 }
Romain Guy8506ab42009-06-11 17:35:47 -07003390
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003391 // The number of milliseconds between each movement that is
3392 // considered "normal" and will not result in any acceleration
3393 // or deceleration, scaled by the offset we have here.
3394 if (normTime > 0) {
3395 long delta = time - lastMoveTime;
3396 lastMoveTime = time;
3397 float acc = acceleration;
3398 if (delta < normTime) {
3399 // The user is scrolling rapidly, so increase acceleration.
3400 float scale = (normTime-delta) * ACCEL_MOVE_SCALING_FACTOR;
3401 if (scale > 1) acc *= scale;
3402 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " accelerate: off="
3403 + off + " normTime=" + normTime + " delta=" + delta
3404 + " scale=" + scale + " acc=" + acc);
3405 acceleration = acc < MAX_ACCELERATION ? acc : MAX_ACCELERATION;
3406 } else {
3407 // The user is scrolling slowly, so decrease acceleration.
3408 float scale = (delta-normTime) * ACCEL_MOVE_SCALING_FACTOR;
3409 if (scale > 1) acc /= scale;
3410 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " deccelerate: off="
3411 + off + " normTime=" + normTime + " delta=" + delta
3412 + " scale=" + scale + " acc=" + acc);
3413 acceleration = acc > 1 ? acc : 1;
3414 }
3415 }
3416 position += off;
3417 return (absPosition = Math.abs(position));
3418 }
3419
3420 /**
3421 * Generate the number of discrete movement events appropriate for
3422 * the currently collected trackball movement.
3423 *
3424 * @param precision The minimum movement required to generate the
3425 * first discrete movement.
3426 *
3427 * @return Returns the number of discrete movements, either positive
3428 * or negative, or 0 if there is not enough trackball movement yet
3429 * for a discrete movement.
3430 */
3431 int generate(float precision) {
3432 int movement = 0;
3433 nonAccelMovement = 0;
3434 do {
3435 final int dir = position >= 0 ? 1 : -1;
3436 switch (step) {
3437 // If we are going to execute the first step, then we want
3438 // to do this as soon as possible instead of waiting for
3439 // a full movement, in order to make things look responsive.
3440 case 0:
3441 if (absPosition < precision) {
3442 return movement;
3443 }
3444 movement += dir;
3445 nonAccelMovement += dir;
3446 step = 1;
3447 break;
3448 // If we have generated the first movement, then we need
3449 // to wait for the second complete trackball motion before
3450 // generating the second discrete movement.
3451 case 1:
3452 if (absPosition < 2) {
3453 return movement;
3454 }
3455 movement += dir;
3456 nonAccelMovement += dir;
3457 position += dir > 0 ? -2 : 2;
3458 absPosition = Math.abs(position);
3459 step = 2;
3460 break;
3461 // After the first two, we generate discrete movements
3462 // consistently with the trackball, applying an acceleration
3463 // if the trackball is moving quickly. This is a simple
3464 // acceleration on top of what we already compute based
3465 // on how quickly the wheel is being turned, to apply
3466 // a longer increasing acceleration to continuous movement
3467 // in one direction.
3468 default:
3469 if (absPosition < 1) {
3470 return movement;
3471 }
3472 movement += dir;
3473 position += dir >= 0 ? -1 : 1;
3474 absPosition = Math.abs(position);
3475 float acc = acceleration;
3476 acc *= 1.1f;
3477 acceleration = acc < MAX_ACCELERATION ? acc : acceleration;
3478 break;
3479 }
3480 } while (true);
3481 }
3482 }
3483
3484 public static final class CalledFromWrongThreadException extends AndroidRuntimeException {
3485 public CalledFromWrongThreadException(String msg) {
3486 super(msg);
3487 }
3488 }
3489
3490 private SurfaceHolder mHolder = new SurfaceHolder() {
3491 // we only need a SurfaceHolder for opengl. it would be nice
3492 // to implement everything else though, especially the callback
3493 // support (opengl doesn't make use of it right now, but eventually
3494 // will).
3495 public Surface getSurface() {
3496 return mSurface;
3497 }
3498
3499 public boolean isCreating() {
3500 return false;
3501 }
3502
3503 public void addCallback(Callback callback) {
3504 }
3505
3506 public void removeCallback(Callback callback) {
3507 }
3508
3509 public void setFixedSize(int width, int height) {
3510 }
3511
3512 public void setSizeFromLayout() {
3513 }
3514
3515 public void setFormat(int format) {
3516 }
3517
3518 public void setType(int type) {
3519 }
3520
3521 public void setKeepScreenOn(boolean screenOn) {
3522 }
3523
3524 public Canvas lockCanvas() {
3525 return null;
3526 }
3527
3528 public Canvas lockCanvas(Rect dirty) {
3529 return null;
3530 }
3531
3532 public void unlockCanvasAndPost(Canvas canvas) {
3533 }
3534 public Rect getSurfaceFrame() {
3535 return null;
3536 }
3537 };
3538
3539 static RunQueue getRunQueue() {
3540 RunQueue rq = sRunQueues.get();
3541 if (rq != null) {
3542 return rq;
3543 }
3544 rq = new RunQueue();
3545 sRunQueues.set(rq);
3546 return rq;
3547 }
Romain Guy8506ab42009-06-11 17:35:47 -07003548
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003549 /**
3550 * @hide
3551 */
3552 static final class RunQueue {
3553 private final ArrayList<HandlerAction> mActions = new ArrayList<HandlerAction>();
3554
3555 void post(Runnable action) {
3556 postDelayed(action, 0);
3557 }
3558
3559 void postDelayed(Runnable action, long delayMillis) {
3560 HandlerAction handlerAction = new HandlerAction();
3561 handlerAction.action = action;
3562 handlerAction.delay = delayMillis;
3563
3564 synchronized (mActions) {
3565 mActions.add(handlerAction);
3566 }
3567 }
3568
3569 void removeCallbacks(Runnable action) {
3570 final HandlerAction handlerAction = new HandlerAction();
3571 handlerAction.action = action;
3572
3573 synchronized (mActions) {
3574 final ArrayList<HandlerAction> actions = mActions;
3575
3576 while (actions.remove(handlerAction)) {
3577 // Keep going
3578 }
3579 }
3580 }
3581
3582 void executeActions(Handler handler) {
3583 synchronized (mActions) {
3584 final ArrayList<HandlerAction> actions = mActions;
3585 final int count = actions.size();
3586
3587 for (int i = 0; i < count; i++) {
3588 final HandlerAction handlerAction = actions.get(i);
3589 handler.postDelayed(handlerAction.action, handlerAction.delay);
3590 }
3591
Romain Guy15df6702009-08-17 20:17:30 -07003592 actions.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003593 }
3594 }
3595
3596 private static class HandlerAction {
3597 Runnable action;
3598 long delay;
3599
3600 @Override
3601 public boolean equals(Object o) {
3602 if (this == o) return true;
3603 if (o == null || getClass() != o.getClass()) return false;
3604
3605 HandlerAction that = (HandlerAction) o;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003606 return !(action != null ? !action.equals(that.action) : that.action != null);
3607
3608 }
3609
3610 @Override
3611 public int hashCode() {
3612 int result = action != null ? action.hashCode() : 0;
3613 result = 31 * result + (int) (delay ^ (delay >>> 32));
3614 return result;
3615 }
3616 }
3617 }
3618
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003619 private static native void nativeShowFPS(Canvas canvas, int durationMillis);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003620}