blob: 17d413a5eb44df7aaa8f613a678350783afb561b [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 }
589 mDirty.union(dirty);
590 if (!mWillDrawSoon) {
591 scheduleTraversals();
592 }
593 }
Romain Guy0d9275e2010-10-26 14:22:30 -0700594
595 void invalidate() {
596 mDirty.set(0, 0, mWidth, mHeight);
597 scheduleTraversals();
598 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800599
600 public ViewParent getParent() {
601 return null;
602 }
603
604 public ViewParent invalidateChildInParent(final int[] location, final Rect dirty) {
605 invalidateChild(null, dirty);
606 return null;
607 }
608
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700609 public boolean getChildVisibleRect(View child, Rect r, android.graphics.Point offset) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800610 if (child != mView) {
611 throw new RuntimeException("child is not mine, honest!");
612 }
613 // Note: don't apply scroll offset, because we want to know its
614 // visibility in the virtual canvas being given to the view hierarchy.
615 return r.intersect(0, 0, mWidth, mHeight);
616 }
617
618 public void bringChildToFront(View child) {
619 }
620
621 public void scheduleTraversals() {
622 if (!mTraversalScheduled) {
623 mTraversalScheduled = true;
624 sendEmptyMessage(DO_TRAVERSAL);
625 }
626 }
627
628 public void unscheduleTraversals() {
629 if (mTraversalScheduled) {
630 mTraversalScheduled = false;
631 removeMessages(DO_TRAVERSAL);
632 }
633 }
634
635 int getHostVisibility() {
636 return mAppVisible ? mView.getVisibility() : View.GONE;
637 }
Romain Guy8506ab42009-06-11 17:35:47 -0700638
Dianne Hackborn0f761d62010-11-30 22:06:10 -0800639 void disposeResizeBitmap() {
640 if (mResizeBitmap != null) {
641 mResizeBitmap.recycle();
642 mResizeBitmap = null;
643 }
644 }
645
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800646 private void performTraversals() {
647 // cache mView since it is used so much below...
648 final View host = mView;
649
650 if (DBG) {
651 System.out.println("======================================");
652 System.out.println("performTraversals");
653 host.debug();
654 }
655
656 if (host == null || !mAdded)
657 return;
658
659 mTraversalScheduled = false;
660 mWillDrawSoon = true;
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800661 boolean windowSizeMayChange = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800662 boolean fullRedrawNeeded = mFullRedrawNeeded;
663 boolean newSurface = false;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700664 boolean surfaceChanged = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800665 WindowManager.LayoutParams lp = mWindowAttributes;
666
667 int desiredWindowWidth;
668 int desiredWindowHeight;
669 int childWidthMeasureSpec;
670 int childHeightMeasureSpec;
671
672 final View.AttachInfo attachInfo = mAttachInfo;
673
674 final int viewVisibility = getHostVisibility();
675 boolean viewVisibilityChanged = mViewVisibility != viewVisibility
676 || mNewSurfaceNeeded;
677
678 WindowManager.LayoutParams params = null;
679 if (mWindowAttributesChanged) {
680 mWindowAttributesChanged = false;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700681 surfaceChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800682 params = lp;
683 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700684 Rect frame = mWinFrame;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800685 if (mFirst) {
686 fullRedrawNeeded = true;
687 mLayoutRequested = true;
688
Romain Guy8506ab42009-06-11 17:35:47 -0700689 DisplayMetrics packageMetrics =
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700690 mView.getContext().getResources().getDisplayMetrics();
691 desiredWindowWidth = packageMetrics.widthPixels;
692 desiredWindowHeight = packageMetrics.heightPixels;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800693
694 // For the very first time, tell the view hierarchy that it
695 // is attached to the window. Note that at this point the surface
696 // object is not initialized to its backing store, but soon it
697 // will be (assuming the window is visible).
698 attachInfo.mSurface = mSurface;
Adam Powell26153a32010-11-08 15:22:27 -0800699 attachInfo.mUse32BitDrawingCache = PixelFormat.formatHasAlpha(lp.format) ||
700 lp.format == PixelFormat.RGBX_8888;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800701 attachInfo.mHasWindowFocus = false;
702 attachInfo.mWindowVisibility = viewVisibility;
703 attachInfo.mRecomputeGlobalAttributes = false;
704 attachInfo.mKeepScreenOn = false;
705 viewVisibilityChanged = false;
Dianne Hackborn694f79b2010-03-17 19:44:59 -0700706 mLastConfiguration.setTo(host.getResources().getConfiguration());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800707 host.dispatchAttachedToWindow(attachInfo, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800708 //Log.i(TAG, "Screen on initialized: " + attachInfo.mKeepScreenOn);
svetoslavganov75986cf2009-05-14 22:28:01 -0700709
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800710 } else {
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700711 desiredWindowWidth = frame.width();
712 desiredWindowHeight = frame.height();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800713 if (desiredWindowWidth != mWidth || desiredWindowHeight != mHeight) {
Jeff Brownc5ed5912010-07-14 18:48:53 -0700714 if (DEBUG_ORIENTATION) Log.v(TAG,
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700715 "View " + host + " resized to: " + frame);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800716 fullRedrawNeeded = true;
717 mLayoutRequested = true;
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800718 windowSizeMayChange = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800719 }
720 }
721
722 if (viewVisibilityChanged) {
723 attachInfo.mWindowVisibility = viewVisibility;
724 host.dispatchWindowVisibilityChanged(viewVisibility);
725 if (viewVisibility != View.VISIBLE || mNewSurfaceNeeded) {
Romain Guyb051e892010-09-28 19:09:36 -0700726 if (mAttachInfo.mHardwareRenderer != null) {
727 mAttachInfo.mHardwareRenderer.destroy(false);
Romain Guy4caa4ed2010-08-25 14:46:24 -0700728 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800729 }
730 if (viewVisibility == View.GONE) {
731 // After making a window gone, we will count it as being
732 // shown for the first time the next time it gets focus.
733 mHasHadWindowFocus = false;
734 }
735 }
736
737 boolean insetsChanged = false;
Romain Guy8506ab42009-06-11 17:35:47 -0700738
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800739 if (mLayoutRequested) {
Romain Guy15df6702009-08-17 20:17:30 -0700740 // Execute enqueued actions on every layout in case a view that was detached
741 // enqueued an action after being detached
742 getRunQueue().executeActions(attachInfo.mHandler);
743
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800744 final Resources res = mView.getContext().getResources();
745
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800746 if (mFirst) {
747 host.fitSystemWindows(mAttachInfo.mContentInsets);
748 // make sure touch mode code executes by setting cached value
749 // to opposite of the added touch mode.
750 mAttachInfo.mInTouchMode = !mAddedTouchMode;
Romain Guy2d4cff62010-04-09 15:39:00 -0700751 ensureTouchModeLocally(mAddedTouchMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800752 } else {
753 if (!mAttachInfo.mContentInsets.equals(mPendingContentInsets)) {
Dianne Hackborn0f761d62010-11-30 22:06:10 -0800754 if (mWidth > 0 && mHeight > 0 &&
755 mSurface != null && mSurface.isValid() &&
756 mAttachInfo.mHardwareRenderer != null &&
757 mAttachInfo.mHardwareRenderer.isEnabled() &&
758 lp != null && !PixelFormat.formatHasAlpha(lp.format)) {
759
760 disposeResizeBitmap();
761
762 boolean completed = false;
763 try {
764 mResizeBitmap = Bitmap.createBitmap(mWidth, mHeight,
765 Bitmap.Config.ARGB_8888);
766 mResizeBitmap.setHasAlpha(false);
767 Canvas canvas = new Canvas(mResizeBitmap);
768 int yoff;
769 final boolean scrolling = mScroller != null
770 && mScroller.computeScrollOffset();
771 if (scrolling) {
772 yoff = mScroller.getCurrY();
773 mScroller.abortAnimation();
774 } else {
775 yoff = mScrollY;
776 }
777 canvas.translate(0, -yoff);
778 if (mTranslator != null) {
779 mTranslator.translateCanvas(canvas);
780 }
781 canvas.setScreenDensity(mAttachInfo.mScalingRequired
782 ? DisplayMetrics.DENSITY_DEVICE : 0);
783 mView.draw(canvas);
784 mResizeBitmapStartTime = SystemClock.uptimeMillis();
785 mResizeBitmapDuration = mView.getResources().getInteger(
786 com.android.internal.R.integer.config_mediumAnimTime);
787 completed = true;
788 } catch (OutOfMemoryError e) {
789 Log.w(TAG, "Not enough memory for content change anim buffer", e);
790 } finally {
791 if (!completed) {
792 mResizeBitmap = null;
793 }
794 }
795 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800796 mAttachInfo.mContentInsets.set(mPendingContentInsets);
797 host.fitSystemWindows(mAttachInfo.mContentInsets);
798 insetsChanged = true;
799 if (DEBUG_LAYOUT) Log.v(TAG, "Content insets changing to: "
800 + mAttachInfo.mContentInsets);
801 }
802 if (!mAttachInfo.mVisibleInsets.equals(mPendingVisibleInsets)) {
803 mAttachInfo.mVisibleInsets.set(mPendingVisibleInsets);
804 if (DEBUG_LAYOUT) Log.v(TAG, "Visible insets changing to: "
805 + mAttachInfo.mVisibleInsets);
806 }
807 if (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT
808 || lp.height == ViewGroup.LayoutParams.WRAP_CONTENT) {
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800809 windowSizeMayChange = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800810
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800811 DisplayMetrics packageMetrics = res.getDisplayMetrics();
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700812 desiredWindowWidth = packageMetrics.widthPixels;
813 desiredWindowHeight = packageMetrics.heightPixels;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800814 }
815 }
816
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800817 // Ask host how big it wants to be
Jeff Brownc5ed5912010-07-14 18:48:53 -0700818 if (DEBUG_ORIENTATION || DEBUG_LAYOUT) Log.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800819 "Measuring " + host + " in display " + desiredWindowWidth
820 + "x" + desiredWindowHeight + "...");
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800821
822 boolean goodMeasure = false;
823 if (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT
824 || lp.height == ViewGroup.LayoutParams.WRAP_CONTENT) {
825 // On large screens, we don't want to allow dialogs to just
826 // stretch to fill the entire width of the screen to display
827 // one line of text. First try doing the layout at a smaller
828 // size to see if it will fit.
829 final DisplayMetrics packageMetrics = res.getDisplayMetrics();
830 res.getValue(com.android.internal.R.dimen.config_prefDialogWidth, mTmpValue, true);
831 int baseSize = 0;
832 if (mTmpValue.type == TypedValue.TYPE_DIMENSION) {
833 baseSize = (int)mTmpValue.getDimension(packageMetrics);
834 }
835 if (DEBUG_DIALOG) Log.v(TAG, "Window " + mView + ": baseSize=" + baseSize);
Dianne Hackborn7d3a5bc2010-11-29 22:52:12 -0800836 if (baseSize != 0 && desiredWindowWidth > baseSize) {
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800837 int maxHeight = (desiredWindowHeight*2)/3;
838 childWidthMeasureSpec = getRootMeasureSpec(baseSize, lp.width);
839 childHeightMeasureSpec = getRootMeasureSpec(desiredWindowHeight, lp.height);
840 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
841 if (DEBUG_DIALOG) Log.v(TAG, "Window " + mView + ": measured ("
842 + host.getWidth() + "," + host.getHeight() + ")");
843 // Note: for now we are not taking into account height, since we
844 // can't distinguish between places where it would be useful to
845 // increase the width (text) vs. where it would not (a list).
846 // Maybe we can just try the next size up, and see if that reduces
847 // the height?
848 if (host.getWidth() <= baseSize /*&& host.getHeight() <= maxHeight*/) {
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800849 goodMeasure = true;
850 } else {
851 // Didn't fit in that size... try expanding a bit.
852 baseSize = (baseSize+desiredWindowWidth)/2;
853 if (DEBUG_DIALOG) Log.v(TAG, "Window " + mView + ": next baseSize="
854 + baseSize);
855 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
856 if (DEBUG_DIALOG) Log.v(TAG, "Window " + mView + ": measured ("
857 + host.getWidth() + "," + host.getHeight() + ")");
858 if (host.getWidth() <= baseSize /*&& host.getHeight() <= maxHeight*/) {
859 if (DEBUG_DIALOG) Log.v(TAG, "Good!");
860 goodMeasure = true;
861 }
862 }
863 }
864 }
865
866 if (!goodMeasure) {
867 childWidthMeasureSpec = getRootMeasureSpec(desiredWindowWidth, lp.width);
868 childHeightMeasureSpec = getRootMeasureSpec(desiredWindowHeight, lp.height);
869 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
870 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800871
872 if (DBG) {
873 System.out.println("======================================");
874 System.out.println("performTraversals -- after measure");
875 host.debug();
876 }
877 }
878
879 if (attachInfo.mRecomputeGlobalAttributes) {
880 //Log.i(TAG, "Computing screen on!");
881 attachInfo.mRecomputeGlobalAttributes = false;
882 boolean oldVal = attachInfo.mKeepScreenOn;
883 attachInfo.mKeepScreenOn = false;
884 host.dispatchCollectViewAttributes(0);
885 if (attachInfo.mKeepScreenOn != oldVal) {
886 params = lp;
887 //Log.i(TAG, "Keep screen on changed: " + attachInfo.mKeepScreenOn);
888 }
889 }
890
891 if (mFirst || attachInfo.mViewVisibilityChanged) {
892 attachInfo.mViewVisibilityChanged = false;
893 int resizeMode = mSoftInputMode &
894 WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST;
895 // If we are in auto resize mode, then we need to determine
896 // what mode to use now.
897 if (resizeMode == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED) {
898 final int N = attachInfo.mScrollContainers.size();
899 for (int i=0; i<N; i++) {
900 if (attachInfo.mScrollContainers.get(i).isShown()) {
901 resizeMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE;
902 }
903 }
904 if (resizeMode == 0) {
905 resizeMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN;
906 }
907 if ((lp.softInputMode &
908 WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) != resizeMode) {
909 lp.softInputMode = (lp.softInputMode &
910 ~WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) |
911 resizeMode;
912 params = lp;
913 }
914 }
915 }
Romain Guy8506ab42009-06-11 17:35:47 -0700916
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800917 if (params != null && (host.mPrivateFlags & View.REQUEST_TRANSPARENT_REGIONS) != 0) {
918 if (!PixelFormat.formatHasAlpha(params.format)) {
919 params.format = PixelFormat.TRANSLUCENT;
920 }
921 }
922
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800923 boolean windowShouldResize = mLayoutRequested && windowSizeMayChange
Romain Guy2e4f4262010-04-06 11:07:52 -0700924 && ((mWidth != host.mMeasuredWidth || mHeight != host.mMeasuredHeight)
925 || (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT &&
926 frame.width() < desiredWindowWidth && frame.width() != mWidth)
927 || (lp.height == ViewGroup.LayoutParams.WRAP_CONTENT &&
928 frame.height() < desiredWindowHeight && frame.height() != mHeight));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800929
930 final boolean computesInternalInsets =
931 attachInfo.mTreeObserver.hasComputeInternalInsetsListeners();
Romain Guy812ccbe2010-06-01 14:07:24 -0700932
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800933 boolean insetsPending = false;
934 int relayoutResult = 0;
Romain Guy812ccbe2010-06-01 14:07:24 -0700935
936 if (mFirst || windowShouldResize || insetsChanged ||
937 viewVisibilityChanged || params != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800938
939 if (viewVisibility == View.VISIBLE) {
940 // If this window is giving internal insets to the window
941 // manager, and it is being added or changing its visibility,
942 // then we want to first give the window manager "fake"
943 // insets to cause it to effectively ignore the content of
944 // the window during layout. This avoids it briefly causing
945 // other windows to resize/move based on the raw frame of the
946 // window, waiting until we can finish laying out this window
947 // and get back to the window manager with the ultimately
948 // computed insets.
Romain Guy812ccbe2010-06-01 14:07:24 -0700949 insetsPending = computesInternalInsets && (mFirst || viewVisibilityChanged);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800950 }
951
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700952 if (mSurfaceHolder != null) {
953 mSurfaceHolder.mSurfaceLock.lock();
954 mDrawingAllowed = true;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700955 }
Romain Guy812ccbe2010-06-01 14:07:24 -0700956
Romain Guyc361da82010-10-25 15:29:10 -0700957 boolean hwInitialized = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800958 boolean contentInsetsChanged = false;
Romain Guy13922e02009-05-12 17:56:14 -0700959 boolean visibleInsetsChanged;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700960 boolean hadSurface = mSurface.isValid();
Romain Guy812ccbe2010-06-01 14:07:24 -0700961
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800962 try {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800963 int fl = 0;
964 if (params != null) {
965 fl = params.flags;
966 if (attachInfo.mKeepScreenOn) {
967 params.flags |= WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
968 }
969 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700970 if (DEBUG_LAYOUT) {
971 Log.i(TAG, "host=w:" + host.mMeasuredWidth + ", h:" +
972 host.mMeasuredHeight + ", params=" + params);
973 }
974 relayoutResult = relayoutWindow(params, viewVisibility, insetsPending);
975
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800976 if (params != null) {
977 params.flags = fl;
978 }
979
980 if (DEBUG_LAYOUT) Log.v(TAG, "relayout: frame=" + frame.toShortString()
981 + " content=" + mPendingContentInsets.toShortString()
982 + " visible=" + mPendingVisibleInsets.toShortString()
983 + " surface=" + mSurface);
Romain Guy8506ab42009-06-11 17:35:47 -0700984
Dianne Hackborn694f79b2010-03-17 19:44:59 -0700985 if (mPendingConfiguration.seq != 0) {
986 if (DEBUG_CONFIGURATION) Log.v(TAG, "Visible with new config: "
987 + mPendingConfiguration);
988 updateConfiguration(mPendingConfiguration, !mFirst);
989 mPendingConfiguration.seq = 0;
990 }
991
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800992 contentInsetsChanged = !mPendingContentInsets.equals(
993 mAttachInfo.mContentInsets);
994 visibleInsetsChanged = !mPendingVisibleInsets.equals(
995 mAttachInfo.mVisibleInsets);
996 if (contentInsetsChanged) {
997 mAttachInfo.mContentInsets.set(mPendingContentInsets);
998 host.fitSystemWindows(mAttachInfo.mContentInsets);
999 if (DEBUG_LAYOUT) Log.v(TAG, "Content insets changing to: "
1000 + mAttachInfo.mContentInsets);
1001 }
1002 if (visibleInsetsChanged) {
1003 mAttachInfo.mVisibleInsets.set(mPendingVisibleInsets);
1004 if (DEBUG_LAYOUT) Log.v(TAG, "Visible insets changing to: "
1005 + mAttachInfo.mVisibleInsets);
1006 }
1007
1008 if (!hadSurface) {
1009 if (mSurface.isValid()) {
1010 // If we are creating a new surface, then we need to
1011 // completely redraw it. Also, when we get to the
1012 // point of drawing it we will hold off and schedule
1013 // a new traversal instead. This is so we can tell the
1014 // window manager about all of the windows being displayed
1015 // before actually drawing them, so it can display then
1016 // all at once.
1017 newSurface = true;
1018 fullRedrawNeeded = true;
Jack Palevich61a6e682009-10-09 17:37:50 -07001019 mPreviousTransparentRegion.setEmpty();
Romain Guy8506ab42009-06-11 17:35:47 -07001020
Romain Guyb051e892010-09-28 19:09:36 -07001021 if (mAttachInfo.mHardwareRenderer != null) {
Romain Guyc361da82010-10-25 15:29:10 -07001022 hwInitialized = mAttachInfo.mHardwareRenderer.initialize(mHolder);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001023 }
1024 }
1025 } else if (!mSurface.isValid()) {
1026 // If the surface has been removed, then reset the scroll
1027 // positions.
1028 mLastScrolledFocus = null;
1029 mScrollY = mCurScrollY = 0;
1030 if (mScroller != null) {
1031 mScroller.abortAnimation();
1032 }
Dianne Hackborn0f761d62010-11-30 22:06:10 -08001033 disposeResizeBitmap();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001034 }
1035 } catch (RemoteException e) {
1036 }
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001037
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001038 if (DEBUG_ORIENTATION) Log.v(
Jeff Brownc5ed5912010-07-14 18:48:53 -07001039 TAG, "Relayout returned: frame=" + frame + ", surface=" + mSurface);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001040
1041 attachInfo.mWindowLeft = frame.left;
1042 attachInfo.mWindowTop = frame.top;
1043
1044 // !!FIXME!! This next section handles the case where we did not get the
1045 // window size we asked for. We should avoid this by getting a maximum size from
1046 // the window session beforehand.
1047 mWidth = frame.width();
1048 mHeight = frame.height();
1049
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001050 if (mSurfaceHolder != null) {
1051 // The app owns the surface; tell it about what is going on.
1052 if (mSurface.isValid()) {
1053 // XXX .copyFrom() doesn't work!
1054 //mSurfaceHolder.mSurface.copyFrom(mSurface);
1055 mSurfaceHolder.mSurface = mSurface;
1056 }
1057 mSurfaceHolder.mSurfaceLock.unlock();
1058 if (mSurface.isValid()) {
1059 if (!hadSurface) {
1060 mSurfaceHolder.ungetCallbacks();
1061
1062 mIsCreating = true;
1063 mSurfaceHolderCallback.surfaceCreated(mSurfaceHolder);
1064 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
1065 if (callbacks != null) {
1066 for (SurfaceHolder.Callback c : callbacks) {
1067 c.surfaceCreated(mSurfaceHolder);
1068 }
1069 }
1070 surfaceChanged = true;
Romain Guyc361da82010-10-25 15:29:10 -07001071
1072 if (mAttachInfo.mHardwareRenderer != null) {
1073 // This will bail out early if already initialized
1074 mAttachInfo.mHardwareRenderer.initialize(mHolder);
1075 }
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001076 }
1077 if (surfaceChanged) {
1078 mSurfaceHolderCallback.surfaceChanged(mSurfaceHolder,
1079 lp.format, mWidth, mHeight);
1080 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
1081 if (callbacks != null) {
1082 for (SurfaceHolder.Callback c : callbacks) {
1083 c.surfaceChanged(mSurfaceHolder, lp.format,
1084 mWidth, mHeight);
1085 }
1086 }
1087 }
1088 mIsCreating = false;
1089 } else if (hadSurface) {
1090 mSurfaceHolder.ungetCallbacks();
1091 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
1092 mSurfaceHolderCallback.surfaceDestroyed(mSurfaceHolder);
1093 if (callbacks != null) {
1094 for (SurfaceHolder.Callback c : callbacks) {
1095 c.surfaceDestroyed(mSurfaceHolder);
1096 }
1097 }
1098 mSurfaceHolder.mSurfaceLock.lock();
1099 // Make surface invalid.
1100 //mSurfaceHolder.mSurface.copyFrom(mSurface);
1101 mSurfaceHolder.mSurface = new Surface();
1102 mSurfaceHolder.mSurfaceLock.unlock();
1103 }
1104 }
Romain Guy53389bd2010-09-07 17:16:32 -07001105
Romain Guyc361da82010-10-25 15:29:10 -07001106 if (hwInitialized || (windowShouldResize && mAttachInfo.mHardwareRenderer != null)) {
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);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001112 if (focusChangedDueToTouchMode || mWidth != host.mMeasuredWidth
1113 || mHeight != host.mMeasuredHeight || contentInsetsChanged) {
1114 childWidthMeasureSpec = getRootMeasureSpec(mWidth, lp.width);
1115 childHeightMeasureSpec = getRootMeasureSpec(mHeight, lp.height);
1116
1117 if (DEBUG_LAYOUT) Log.v(TAG, "Ooops, something changed! mWidth="
1118 + mWidth + " measuredWidth=" + host.mMeasuredWidth
1119 + " mHeight=" + mHeight
1120 + " measuredHeight" + host.mMeasuredHeight
1121 + " 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
1129 int width = host.mMeasuredWidth;
1130 int height = host.mMeasuredHeight;
1131 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 (" +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001165 host.mMeasuredWidth + ", " + host.mMeasuredHeight + ")");
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 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001170 host.layout(0, 0, host.mMeasuredWidth, host.mMeasuredHeight);
1171
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();
2313 final int metastate = event.getMetaState();
2314 switch (action) {
2315 case MotionEvent.ACTION_DOWN:
2316 x.reset(2);
2317 y.reset(2);
2318 deliverKeyEvent(new KeyEvent(curTime, curTime,
2319 KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_CENTER,
2320 0, metastate), false);
2321 break;
2322 case MotionEvent.ACTION_UP:
2323 x.reset(2);
2324 y.reset(2);
2325 deliverKeyEvent(new KeyEvent(curTime, curTime,
2326 KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_CENTER,
2327 0, metastate), false);
2328 break;
2329 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002330
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002331 if (DEBUG_TRACKBALL) Log.v(TAG, "TB X=" + x.position + " step="
2332 + x.step + " dir=" + x.dir + " acc=" + x.acceleration
2333 + " move=" + event.getX()
2334 + " / Y=" + y.position + " step="
2335 + y.step + " dir=" + y.dir + " acc=" + y.acceleration
2336 + " move=" + event.getY());
2337 final float xOff = x.collect(event.getX(), event.getEventTime(), "X");
2338 final float yOff = y.collect(event.getY(), event.getEventTime(), "Y");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002339
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002340 // Generate DPAD events based on the trackball movement.
2341 // We pick the axis that has moved the most as the direction of
2342 // the DPAD. When we generate DPAD events for one axis, then the
2343 // other axis is reset -- we don't want to perform DPAD jumps due
2344 // to slight movements in the trackball when making major movements
2345 // along the other axis.
2346 int keycode = 0;
2347 int movement = 0;
2348 float accel = 1;
2349 if (xOff > yOff) {
2350 movement = x.generate((2/event.getXPrecision()));
2351 if (movement != 0) {
2352 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_RIGHT
2353 : KeyEvent.KEYCODE_DPAD_LEFT;
2354 accel = x.acceleration;
2355 y.reset(2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002356 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002357 } else if (yOff > 0) {
2358 movement = y.generate((2/event.getYPrecision()));
2359 if (movement != 0) {
2360 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_DOWN
2361 : KeyEvent.KEYCODE_DPAD_UP;
2362 accel = y.acceleration;
2363 x.reset(2);
2364 }
2365 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002366
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002367 if (keycode != 0) {
2368 if (movement < 0) movement = -movement;
2369 int accelMovement = (int)(movement * accel);
2370 if (DEBUG_TRACKBALL) Log.v(TAG, "Move: movement=" + movement
2371 + " accelMovement=" + accelMovement
2372 + " accel=" + accel);
2373 if (accelMovement > movement) {
2374 if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: "
2375 + keycode);
2376 movement--;
2377 deliverKeyEvent(new KeyEvent(curTime, curTime,
2378 KeyEvent.ACTION_MULTIPLE, keycode,
2379 accelMovement-movement, metastate), false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002380 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002381 while (movement > 0) {
2382 if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: "
2383 + keycode);
2384 movement--;
2385 curTime = SystemClock.uptimeMillis();
2386 deliverKeyEvent(new KeyEvent(curTime, curTime,
2387 KeyEvent.ACTION_DOWN, keycode, 0, event.getMetaState()), false);
2388 deliverKeyEvent(new KeyEvent(curTime, curTime,
2389 KeyEvent.ACTION_UP, keycode, 0, metastate), false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002390 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002391 mLastTrackballTime = curTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002392 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002393
2394 // Unfortunately we can't tell whether the application consumed the keys, so
2395 // we always consider the trackball event handled.
2396 finishTrackballEvent(event, sendDone, true);
2397 }
2398
2399 private void finishTrackballEvent(MotionEvent event, boolean sendDone, boolean handled) {
2400 event.recycle();
2401 if (sendDone) {
2402 finishInputEvent(handled);
2403 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002404 }
2405
2406 /**
2407 * @param keyCode The key code
2408 * @return True if the key is directional.
2409 */
2410 static boolean isDirectional(int keyCode) {
2411 switch (keyCode) {
2412 case KeyEvent.KEYCODE_DPAD_LEFT:
2413 case KeyEvent.KEYCODE_DPAD_RIGHT:
2414 case KeyEvent.KEYCODE_DPAD_UP:
2415 case KeyEvent.KEYCODE_DPAD_DOWN:
2416 return true;
2417 }
2418 return false;
2419 }
2420
2421 /**
2422 * Returns true if this key is a keyboard key.
2423 * @param keyEvent The key event.
2424 * @return whether this key is a keyboard key.
2425 */
2426 private static boolean isKeyboardKey(KeyEvent keyEvent) {
2427 final int convertedKey = keyEvent.getUnicodeChar();
2428 return convertedKey > 0;
2429 }
2430
2431
2432
2433 /**
2434 * See if the key event means we should leave touch mode (and leave touch
2435 * mode if so).
2436 * @param event The key event.
2437 * @return Whether this key event should be consumed (meaning the act of
2438 * leaving touch mode alone is considered the event).
2439 */
2440 private boolean checkForLeavingTouchModeAndConsume(KeyEvent event) {
Adam Powell51a6bee2010-03-15 14:07:28 -07002441 final int action = event.getAction();
2442 if (action != KeyEvent.ACTION_DOWN && action != KeyEvent.ACTION_MULTIPLE) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002443 return false;
2444 }
2445 if ((event.getFlags()&KeyEvent.FLAG_KEEP_TOUCH_MODE) != 0) {
2446 return false;
2447 }
2448
2449 // only relevant if we are in touch mode
2450 if (!mAttachInfo.mInTouchMode) {
2451 return false;
2452 }
2453
2454 // if something like an edit text has focus and the user is typing,
2455 // leave touch mode
2456 //
2457 // note: the condition of not being a keyboard key is kind of a hacky
2458 // approximation of whether we think the focused view will want the
2459 // key; if we knew for sure whether the focused view would consume
2460 // the event, that would be better.
2461 if (isKeyboardKey(event) && mView != null && mView.hasFocus()) {
2462 mFocusedView = mView.findFocus();
2463 if ((mFocusedView instanceof ViewGroup)
2464 && ((ViewGroup) mFocusedView).getDescendantFocusability() ==
2465 ViewGroup.FOCUS_AFTER_DESCENDANTS) {
2466 // something has focus, but is holding it weakly as a container
2467 return false;
2468 }
2469 if (ensureTouchMode(false)) {
2470 throw new IllegalStateException("should not have changed focus "
2471 + "when leaving touch mode while a view has focus.");
2472 }
2473 return false;
2474 }
2475
2476 if (isDirectional(event.getKeyCode())) {
2477 // no view has focus, so we leave touch mode (and find something
2478 // to give focus to). the event is consumed if we were able to
2479 // find something to give focus to.
2480 return ensureTouchMode(false);
2481 }
2482 return false;
2483 }
2484
2485 /**
Romain Guy8506ab42009-06-11 17:35:47 -07002486 * log motion events
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002487 */
2488 private static void captureMotionLog(String subTag, MotionEvent ev) {
Romain Guy8506ab42009-06-11 17:35:47 -07002489 //check dynamic switch
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002490 if (ev == null ||
2491 SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_EVENT, 0) == 0) {
2492 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002493 }
Romain Guy8506ab42009-06-11 17:35:47 -07002494
2495 StringBuilder sb = new StringBuilder(subTag + ": ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002496 sb.append(ev.getDownTime()).append(',');
2497 sb.append(ev.getEventTime()).append(',');
2498 sb.append(ev.getAction()).append(',');
Romain Guy8506ab42009-06-11 17:35:47 -07002499 sb.append(ev.getX()).append(',');
2500 sb.append(ev.getY()).append(',');
2501 sb.append(ev.getPressure()).append(',');
2502 sb.append(ev.getSize()).append(',');
2503 sb.append(ev.getMetaState()).append(',');
2504 sb.append(ev.getXPrecision()).append(',');
2505 sb.append(ev.getYPrecision()).append(',');
2506 sb.append(ev.getDeviceId()).append(',');
2507 sb.append(ev.getEdgeFlags());
2508 Log.d(TAG, sb.toString());
2509 }
2510 /**
2511 * log motion events
2512 */
2513 private static void captureKeyLog(String subTag, KeyEvent ev) {
2514 //check dynamic switch
2515 if (ev == null ||
2516 SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_EVENT, 0) == 0) {
2517 return;
2518 }
2519 StringBuilder sb = new StringBuilder(subTag + ": ");
2520 sb.append(ev.getDownTime()).append(',');
2521 sb.append(ev.getEventTime()).append(',');
2522 sb.append(ev.getAction()).append(',');
2523 sb.append(ev.getKeyCode()).append(',');
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002524 sb.append(ev.getRepeatCount()).append(',');
2525 sb.append(ev.getMetaState()).append(',');
2526 sb.append(ev.getDeviceId()).append(',');
2527 sb.append(ev.getScanCode());
Romain Guy8506ab42009-06-11 17:35:47 -07002528 Log.d(TAG, sb.toString());
2529 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002530
2531 int enqueuePendingEvent(Object event, boolean sendDone) {
2532 int seq = mPendingEventSeq+1;
2533 if (seq < 0) seq = 0;
2534 mPendingEventSeq = seq;
2535 mPendingEvents.put(seq, event);
2536 return sendDone ? seq : -seq;
2537 }
2538
2539 Object retrievePendingEvent(int seq) {
2540 if (seq < 0) seq = -seq;
2541 Object event = mPendingEvents.get(seq);
2542 if (event != null) {
2543 mPendingEvents.remove(seq);
2544 }
2545 return event;
2546 }
Romain Guy8506ab42009-06-11 17:35:47 -07002547
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002548 private void deliverKeyEvent(KeyEvent event, boolean sendDone) {
Jeff Brown3915bb82010-11-05 15:02:16 -07002549 // If there is no view, then the event will not be handled.
2550 if (mView == null || !mAdded) {
2551 finishKeyEvent(event, sendDone, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002552 return;
2553 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002554
2555 if (LOCAL_LOGV) Log.v(TAG, "Dispatching key " + event + " to " + mView);
2556
2557 // Perform predispatching before the IME.
2558 if (mView.dispatchKeyEventPreIme(event)) {
2559 finishKeyEvent(event, sendDone, true);
2560 return;
2561 }
2562
2563 // Dispatch to the IME before propagating down the view hierarchy.
2564 // The IME will eventually call back into handleFinishedEvent.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002565 if (mLastWasImTarget) {
2566 InputMethodManager imm = InputMethodManager.peekInstance();
Jeff Brown3915bb82010-11-05 15:02:16 -07002567 if (imm != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002568 int seq = enqueuePendingEvent(event, sendDone);
2569 if (DEBUG_IMF) Log.v(TAG, "Sending key event to IME: seq="
2570 + seq + " event=" + event);
Jeff Brown3915bb82010-11-05 15:02:16 -07002571 imm.dispatchKeyEvent(mView.getContext(), seq, event, mInputMethodCallback);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002572 return;
2573 }
2574 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002575
2576 // Not dispatching to IME, continue with post IME actions.
2577 deliverKeyEventPostIme(event, sendDone);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002578 }
2579
Jeff Brown3915bb82010-11-05 15:02:16 -07002580 private void handleFinishedEvent(int seq, boolean handled) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002581 final KeyEvent event = (KeyEvent)retrievePendingEvent(seq);
2582 if (DEBUG_IMF) Log.v(TAG, "IME finished event: seq=" + seq
2583 + " handled=" + handled + " event=" + event);
2584 if (event != null) {
2585 final boolean sendDone = seq >= 0;
Jeff Brown3915bb82010-11-05 15:02:16 -07002586 if (handled) {
2587 finishKeyEvent(event, sendDone, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002588 } else {
Jeff Brown3915bb82010-11-05 15:02:16 -07002589 deliverKeyEventPostIme(event, sendDone);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002590 }
2591 }
2592 }
Romain Guy8506ab42009-06-11 17:35:47 -07002593
Jeff Brown3915bb82010-11-05 15:02:16 -07002594 private void deliverKeyEventPostIme(KeyEvent event, boolean sendDone) {
2595 // If the view went away, then the event will not be handled.
2596 if (mView == null || !mAdded) {
2597 finishKeyEvent(event, sendDone, false);
2598 return;
2599 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002600
Jeff Brown3915bb82010-11-05 15:02:16 -07002601 // If the key's purpose is to exit touch mode then we consume it and consider it handled.
2602 if (checkForLeavingTouchModeAndConsume(event)) {
2603 finishKeyEvent(event, sendDone, true);
2604 return;
2605 }
Romain Guy8506ab42009-06-11 17:35:47 -07002606
Jeff Brown3915bb82010-11-05 15:02:16 -07002607 if (Config.LOGV) {
2608 captureKeyLog("captureDispatchKeyEvent", event);
2609 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002610
Jeff Brown3915bb82010-11-05 15:02:16 -07002611 // Deliver the key to the view hierarchy.
2612 if (mView.dispatchKeyEvent(event)) {
2613 finishKeyEvent(event, sendDone, true);
2614 return;
2615 }
Joe Onorato86f67862010-11-05 18:57:34 -07002616
Jeff Brown3915bb82010-11-05 15:02:16 -07002617 // Apply the fallback event policy.
2618 if (mFallbackEventHandler.dispatchKeyEvent(event)) {
2619 finishKeyEvent(event, sendDone, true);
2620 return;
2621 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002622
Jeff Brown3915bb82010-11-05 15:02:16 -07002623 // Handle automatic focus changes.
2624 if (event.getAction() == KeyEvent.ACTION_DOWN) {
2625 int direction = 0;
2626 switch (event.getKeyCode()) {
2627 case KeyEvent.KEYCODE_DPAD_LEFT:
2628 direction = View.FOCUS_LEFT;
2629 break;
2630 case KeyEvent.KEYCODE_DPAD_RIGHT:
2631 direction = View.FOCUS_RIGHT;
2632 break;
2633 case KeyEvent.KEYCODE_DPAD_UP:
2634 direction = View.FOCUS_UP;
2635 break;
2636 case KeyEvent.KEYCODE_DPAD_DOWN:
2637 direction = View.FOCUS_DOWN;
2638 break;
2639 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002640
Jeff Brown3915bb82010-11-05 15:02:16 -07002641 if (direction != 0) {
2642 View focused = mView != null ? mView.findFocus() : null;
2643 if (focused != null) {
2644 View v = focused.focusSearch(direction);
2645 if (v != null && v != focused) {
2646 // do the math the get the interesting rect
2647 // of previous focused into the coord system of
2648 // newly focused view
2649 focused.getFocusedRect(mTempRect);
2650 if (mView instanceof ViewGroup) {
2651 ((ViewGroup) mView).offsetDescendantRectToMyCoords(
2652 focused, mTempRect);
2653 ((ViewGroup) mView).offsetRectIntoDescendantCoords(
2654 v, mTempRect);
2655 }
2656 if (v.requestFocus(direction, mTempRect)) {
2657 playSoundEffect(
2658 SoundEffectConstants.getContantForFocusDirection(direction));
2659 finishKeyEvent(event, sendDone, true);
2660 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002661 }
2662 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002663
2664 // Give the focused view a last chance to handle the dpad key.
2665 if (mView.dispatchUnhandledMove(focused, direction)) {
2666 finishKeyEvent(event, sendDone, true);
2667 return;
2668 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002669 }
2670 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002671 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002672
Jeff Brown3915bb82010-11-05 15:02:16 -07002673 // Key was unhandled.
2674 finishKeyEvent(event, sendDone, false);
2675 }
2676
2677 private void finishKeyEvent(KeyEvent event, boolean sendDone, boolean handled) {
2678 if (sendDone) {
2679 finishInputEvent(handled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002680 }
2681 }
2682
Christopher Tatea53146c2010-09-07 11:57:52 -07002683 /* drag/drop */
Christopher Tate407b4e92010-11-30 17:14:08 -08002684 void setLocalDragState(Object obj) {
2685 mLocalDragState = obj;
2686 }
2687
Christopher Tatea53146c2010-09-07 11:57:52 -07002688 private void handleDragEvent(DragEvent event) {
2689 // From the root, only drag start/end/location are dispatched. entered/exited
2690 // are determined and dispatched by the viewgroup hierarchy, who then report
2691 // that back here for ultimate reporting back to the framework.
2692 if (mView != null && mAdded) {
2693 final int what = event.mAction;
2694
2695 if (what == DragEvent.ACTION_DRAG_EXITED) {
2696 // A direct EXITED event means that the window manager knows we've just crossed
2697 // a window boundary, so the current drag target within this one must have
2698 // just been exited. Send it the usual notifications and then we're done
2699 // for now.
Chris Tate9d1ab882010-11-02 15:55:39 -07002700 mView.dispatchDragEvent(event);
Christopher Tatea53146c2010-09-07 11:57:52 -07002701 } else {
2702 // Cache the drag description when the operation starts, then fill it in
2703 // on subsequent calls as a convenience
2704 if (what == DragEvent.ACTION_DRAG_STARTED) {
Chris Tate9d1ab882010-11-02 15:55:39 -07002705 mCurrentDragView = null; // Start the current-recipient tracking
Christopher Tatea53146c2010-09-07 11:57:52 -07002706 mDragDescription = event.mClipDescription;
2707 } else {
2708 event.mClipDescription = mDragDescription;
2709 }
2710
2711 // For events with a [screen] location, translate into window coordinates
2712 if ((what == DragEvent.ACTION_DRAG_LOCATION) || (what == DragEvent.ACTION_DROP)) {
2713 mDragPoint.set(event.mX, event.mY);
2714 if (mTranslator != null) {
2715 mTranslator.translatePointInScreenToAppWindow(mDragPoint);
2716 }
2717
2718 if (mCurScrollY != 0) {
2719 mDragPoint.offset(0, mCurScrollY);
2720 }
2721
2722 event.mX = mDragPoint.x;
2723 event.mY = mDragPoint.y;
2724 }
2725
2726 // Remember who the current drag target is pre-dispatch
2727 final View prevDragView = mCurrentDragView;
2728
2729 // Now dispatch the drag/drop event
Chris Tated4533f12010-10-19 15:15:08 -07002730 boolean result = mView.dispatchDragEvent(event);
Christopher Tatea53146c2010-09-07 11:57:52 -07002731
2732 // If we changed apparent drag target, tell the OS about it
2733 if (prevDragView != mCurrentDragView) {
2734 try {
2735 if (prevDragView != null) {
2736 sWindowSession.dragRecipientExited(mWindow);
2737 }
2738 if (mCurrentDragView != null) {
2739 sWindowSession.dragRecipientEntered(mWindow);
2740 }
2741 } catch (RemoteException e) {
2742 Slog.e(TAG, "Unable to note drag target change");
2743 }
Christopher Tatea53146c2010-09-07 11:57:52 -07002744 }
Chris Tated4533f12010-10-19 15:15:08 -07002745
Christopher Tate407b4e92010-11-30 17:14:08 -08002746 // Report the drop result when we're done
Chris Tated4533f12010-10-19 15:15:08 -07002747 if (what == DragEvent.ACTION_DROP) {
2748 try {
2749 Log.i(TAG, "Reporting drop result: " + result);
2750 sWindowSession.reportDropResult(mWindow, result);
2751 } catch (RemoteException e) {
2752 Log.e(TAG, "Unable to report drop result");
2753 }
2754 }
Christopher Tate407b4e92010-11-30 17:14:08 -08002755
2756 // When the drag operation ends, release any local state object
2757 // that may have been in use
2758 if (what == DragEvent.ACTION_DRAG_ENDED) {
2759 setLocalDragState(null);
2760 }
Christopher Tatea53146c2010-09-07 11:57:52 -07002761 }
2762 }
2763 event.recycle();
2764 }
2765
Christopher Tate2c095f32010-10-04 14:13:40 -07002766 public void getLastTouchPoint(Point outLocation) {
2767 outLocation.x = (int) mLastTouchPoint.x;
2768 outLocation.y = (int) mLastTouchPoint.y;
2769 }
2770
Chris Tate9d1ab882010-11-02 15:55:39 -07002771 public void setDragFocus(View newDragTarget) {
Christopher Tatea53146c2010-09-07 11:57:52 -07002772 if (mCurrentDragView != newDragTarget) {
Chris Tate048691c2010-10-12 17:39:18 -07002773 mCurrentDragView = newDragTarget;
Christopher Tatea53146c2010-09-07 11:57:52 -07002774 }
Christopher Tatea53146c2010-09-07 11:57:52 -07002775 }
2776
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002777 private AudioManager getAudioManager() {
2778 if (mView == null) {
2779 throw new IllegalStateException("getAudioManager called when there is no mView");
2780 }
2781 if (mAudioManager == null) {
2782 mAudioManager = (AudioManager) mView.getContext().getSystemService(Context.AUDIO_SERVICE);
2783 }
2784 return mAudioManager;
2785 }
2786
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002787 private int relayoutWindow(WindowManager.LayoutParams params, int viewVisibility,
2788 boolean insetsPending) throws RemoteException {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002789
2790 float appScale = mAttachInfo.mApplicationScale;
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002791 boolean restore = false;
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002792 if (params != null && mTranslator != null) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07002793 restore = true;
2794 params.backup();
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002795 mTranslator.translateWindowLayout(params);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002796 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002797 if (params != null) {
2798 if (DBG) Log.d(TAG, "WindowLayout in layoutWindow:" + params);
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002799 }
Dianne Hackborn694f79b2010-03-17 19:44:59 -07002800 mPendingConfiguration.seq = 0;
Dianne Hackbornf123e492010-09-24 11:16:23 -07002801 //Log.d(TAG, ">>>>>> CALLING relayout");
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002802 int relayoutResult = sWindowSession.relayout(
2803 mWindow, params,
Mitsuru Oshima61324e52009-07-21 15:40:36 -07002804 (int) (mView.mMeasuredWidth * appScale + 0.5f),
2805 (int) (mView.mMeasuredHeight * appScale + 0.5f),
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002806 viewVisibility, insetsPending, mWinFrame,
Dianne Hackborn694f79b2010-03-17 19:44:59 -07002807 mPendingContentInsets, mPendingVisibleInsets,
2808 mPendingConfiguration, mSurface);
Dianne Hackbornf123e492010-09-24 11:16:23 -07002809 //Log.d(TAG, "<<<<<< BACK FROM relayout");
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002810 if (restore) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07002811 params.restore();
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002812 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002813
2814 if (mTranslator != null) {
2815 mTranslator.translateRectInScreenToAppWinFrame(mWinFrame);
2816 mTranslator.translateRectInScreenToAppWindow(mPendingContentInsets);
2817 mTranslator.translateRectInScreenToAppWindow(mPendingVisibleInsets);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002818 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002819 return relayoutResult;
2820 }
Romain Guy8506ab42009-06-11 17:35:47 -07002821
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002822 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002823 * {@inheritDoc}
2824 */
2825 public void playSoundEffect(int effectId) {
2826 checkThread();
2827
Jean-Michel Trivi13b18fd2010-05-05 09:18:15 -07002828 try {
2829 final AudioManager audioManager = getAudioManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002830
Jean-Michel Trivi13b18fd2010-05-05 09:18:15 -07002831 switch (effectId) {
2832 case SoundEffectConstants.CLICK:
2833 audioManager.playSoundEffect(AudioManager.FX_KEY_CLICK);
2834 return;
2835 case SoundEffectConstants.NAVIGATION_DOWN:
2836 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_DOWN);
2837 return;
2838 case SoundEffectConstants.NAVIGATION_LEFT:
2839 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_LEFT);
2840 return;
2841 case SoundEffectConstants.NAVIGATION_RIGHT:
2842 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_RIGHT);
2843 return;
2844 case SoundEffectConstants.NAVIGATION_UP:
2845 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_UP);
2846 return;
2847 default:
2848 throw new IllegalArgumentException("unknown effect id " + effectId +
2849 " not defined in " + SoundEffectConstants.class.getCanonicalName());
2850 }
2851 } catch (IllegalStateException e) {
2852 // Exception thrown by getAudioManager() when mView is null
2853 Log.e(TAG, "FATAL EXCEPTION when attempting to play sound effect: " + e);
2854 e.printStackTrace();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002855 }
2856 }
2857
2858 /**
2859 * {@inheritDoc}
2860 */
2861 public boolean performHapticFeedback(int effectId, boolean always) {
2862 try {
2863 return sWindowSession.performHapticFeedback(mWindow, effectId, always);
2864 } catch (RemoteException e) {
2865 return false;
2866 }
2867 }
2868
2869 /**
2870 * {@inheritDoc}
2871 */
2872 public View focusSearch(View focused, int direction) {
2873 checkThread();
2874 if (!(mView instanceof ViewGroup)) {
2875 return null;
2876 }
2877 return FocusFinder.getInstance().findNextFocus((ViewGroup) mView, focused, direction);
2878 }
2879
2880 public void debug() {
2881 mView.debug();
2882 }
2883
2884 public void die(boolean immediate) {
Dianne Hackborn94d69142009-09-28 22:14:42 -07002885 if (immediate) {
2886 doDie();
2887 } else {
2888 sendEmptyMessage(DIE);
2889 }
2890 }
2891
2892 void doDie() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002893 checkThread();
Jeff Brownb75fa302010-07-15 23:47:29 -07002894 if (LOCAL_LOGV) Log.v(TAG, "DIE in " + this + " of " + mSurface);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002895 synchronized (this) {
2896 if (mAdded && !mFirst) {
Romain Guy29d89972010-09-22 16:10:57 -07002897 destroyHardwareRenderer();
2898
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002899 int viewVisibility = mView.getVisibility();
2900 boolean viewVisibilityChanged = mViewVisibility != viewVisibility;
2901 if (mWindowAttributesChanged || viewVisibilityChanged) {
2902 // If layout params have been changed, first give them
2903 // to the window manager to make sure it has the correct
2904 // animation info.
2905 try {
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002906 if ((relayoutWindow(mWindowAttributes, viewVisibility, false)
2907 & WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002908 sWindowSession.finishDrawing(mWindow);
2909 }
2910 } catch (RemoteException e) {
2911 }
2912 }
2913
Dianne Hackborn0586a1b2009-09-06 21:08:27 -07002914 mSurface.release();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002915 }
2916 if (mAdded) {
2917 mAdded = false;
Dianne Hackborn94d69142009-09-28 22:14:42 -07002918 dispatchDetachedFromWindow();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002919 }
2920 }
2921 }
2922
Romain Guy29d89972010-09-22 16:10:57 -07002923 private void destroyHardwareRenderer() {
Romain Guyb051e892010-09-28 19:09:36 -07002924 if (mAttachInfo.mHardwareRenderer != null) {
2925 mAttachInfo.mHardwareRenderer.destroy(true);
2926 mAttachInfo.mHardwareRenderer = null;
Romain Guy29d89972010-09-22 16:10:57 -07002927 mAttachInfo.mHardwareAccelerated = false;
2928 }
2929 }
2930
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002931 public void dispatchFinishedEvent(int seq, boolean handled) {
2932 Message msg = obtainMessage(FINISHED_EVENT);
2933 msg.arg1 = seq;
2934 msg.arg2 = handled ? 1 : 0;
2935 sendMessage(msg);
2936 }
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002937
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002938 public void dispatchResized(int w, int h, Rect coveredInsets,
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002939 Rect visibleInsets, boolean reportDraw, Configuration newConfig) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002940 if (DEBUG_LAYOUT) Log.v(TAG, "Resizing " + this + ": w=" + w
2941 + " h=" + h + " coveredInsets=" + coveredInsets.toShortString()
2942 + " visibleInsets=" + visibleInsets.toShortString()
2943 + " reportDraw=" + reportDraw);
2944 Message msg = obtainMessage(reportDraw ? RESIZED_REPORT :RESIZED);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002945 if (mTranslator != null) {
2946 mTranslator.translateRectInScreenToAppWindow(coveredInsets);
2947 mTranslator.translateRectInScreenToAppWindow(visibleInsets);
2948 w *= mTranslator.applicationInvertedScale;
2949 h *= mTranslator.applicationInvertedScale;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002950 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002951 msg.arg1 = w;
2952 msg.arg2 = h;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002953 ResizedInfo ri = new ResizedInfo();
2954 ri.coveredInsets = new Rect(coveredInsets);
2955 ri.visibleInsets = new Rect(visibleInsets);
2956 ri.newConfig = newConfig;
2957 msg.obj = ri;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002958 sendMessage(msg);
2959 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002960
Jeff Brown3915bb82010-11-05 15:02:16 -07002961 private InputQueue.FinishedCallback mFinishedCallback;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002962
2963 private final InputHandler mInputHandler = new InputHandler() {
Jeff Brown3915bb82010-11-05 15:02:16 -07002964 public void handleKey(KeyEvent event, InputQueue.FinishedCallback finishedCallback) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07002965 startInputEvent(finishedCallback);
Jeff Brown92ff1dd2010-08-11 16:16:06 -07002966 dispatchKey(event, true);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002967 }
2968
Jeff Brown3915bb82010-11-05 15:02:16 -07002969 public void handleMotion(MotionEvent event, InputQueue.FinishedCallback finishedCallback) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07002970 startInputEvent(finishedCallback);
2971 dispatchMotion(event, true);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002972 }
2973 };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002974
2975 public void dispatchKey(KeyEvent event) {
Jeff Brown92ff1dd2010-08-11 16:16:06 -07002976 dispatchKey(event, false);
2977 }
2978
2979 private void dispatchKey(KeyEvent event, boolean sendDone) {
2980 //noinspection ConstantConditions
2981 if (false && event.getAction() == KeyEvent.ACTION_DOWN) {
2982 if (event.getKeyCode() == KeyEvent.KEYCODE_CAMERA) {
Romain Guy812ccbe2010-06-01 14:07:24 -07002983 if (DBG) Log.d("keydisp", "===================================================");
2984 if (DBG) Log.d("keydisp", "Focused view Hierarchy is:");
2985
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002986 debug();
2987
Romain Guy812ccbe2010-06-01 14:07:24 -07002988 if (DBG) Log.d("keydisp", "===================================================");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002989 }
2990 }
2991
2992 Message msg = obtainMessage(DISPATCH_KEY);
2993 msg.obj = event;
Jeff Brown92ff1dd2010-08-11 16:16:06 -07002994 msg.arg1 = sendDone ? 1 : 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002995
2996 if (LOCAL_LOGV) Log.v(
Jeff Brownc5ed5912010-07-14 18:48:53 -07002997 TAG, "sending key " + event + " to " + mView);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002998
2999 sendMessageAtTime(msg, event.getEventTime());
3000 }
Jeff Brownc5ed5912010-07-14 18:48:53 -07003001
3002 public void dispatchMotion(MotionEvent event) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07003003 dispatchMotion(event, false);
3004 }
3005
3006 private void dispatchMotion(MotionEvent event, boolean sendDone) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07003007 int source = event.getSource();
3008 if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07003009 dispatchPointer(event, sendDone);
Jeff Brownc5ed5912010-07-14 18:48:53 -07003010 } else if ((source & InputDevice.SOURCE_CLASS_TRACKBALL) != 0) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07003011 dispatchTrackball(event, sendDone);
Jeff Brownc5ed5912010-07-14 18:48:53 -07003012 } else {
3013 // TODO
3014 Log.v(TAG, "Dropping unsupported motion event (unimplemented): " + event);
Jeff Brown93ed4e32010-09-23 13:51:48 -07003015 if (sendDone) {
Jeff Brown3915bb82010-11-05 15:02:16 -07003016 finishInputEvent(false);
Jeff Brown93ed4e32010-09-23 13:51:48 -07003017 }
Jeff Brownc5ed5912010-07-14 18:48:53 -07003018 }
3019 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003020
Jeff Brown00fa7bd2010-07-02 15:37:36 -07003021 public void dispatchPointer(MotionEvent event) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07003022 dispatchPointer(event, false);
3023 }
3024
3025 private void dispatchPointer(MotionEvent event, boolean sendDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003026 Message msg = obtainMessage(DISPATCH_POINTER);
3027 msg.obj = event;
Jeff Brown93ed4e32010-09-23 13:51:48 -07003028 msg.arg1 = sendDone ? 1 : 0;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07003029 sendMessageAtTime(msg, event.getEventTime());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003030 }
3031
Jeff Brown00fa7bd2010-07-02 15:37:36 -07003032 public void dispatchTrackball(MotionEvent event) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07003033 dispatchTrackball(event, false);
3034 }
3035
3036 private void dispatchTrackball(MotionEvent event, boolean sendDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003037 Message msg = obtainMessage(DISPATCH_TRACKBALL);
3038 msg.obj = event;
Jeff Brown93ed4e32010-09-23 13:51:48 -07003039 msg.arg1 = sendDone ? 1 : 0;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07003040 sendMessageAtTime(msg, event.getEventTime());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003041 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07003042
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003043 public void dispatchAppVisibility(boolean visible) {
3044 Message msg = obtainMessage(DISPATCH_APP_VISIBILITY);
3045 msg.arg1 = visible ? 1 : 0;
3046 sendMessage(msg);
3047 }
3048
3049 public void dispatchGetNewSurface() {
3050 Message msg = obtainMessage(DISPATCH_GET_NEW_SURFACE);
3051 sendMessage(msg);
3052 }
3053
3054 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
3055 Message msg = Message.obtain();
3056 msg.what = WINDOW_FOCUS_CHANGED;
3057 msg.arg1 = hasFocus ? 1 : 0;
3058 msg.arg2 = inTouchMode ? 1 : 0;
3059 sendMessage(msg);
3060 }
3061
Dianne Hackbornffa42482009-09-23 22:20:11 -07003062 public void dispatchCloseSystemDialogs(String reason) {
3063 Message msg = Message.obtain();
3064 msg.what = CLOSE_SYSTEM_DIALOGS;
3065 msg.obj = reason;
3066 sendMessage(msg);
3067 }
Christopher Tatea53146c2010-09-07 11:57:52 -07003068
3069 public void dispatchDragEvent(DragEvent event) {
Chris Tate91e9bb32010-10-12 12:58:43 -07003070 final int what;
3071 if (event.getAction() == DragEvent.ACTION_DRAG_LOCATION) {
3072 what = DISPATCH_DRAG_LOCATION_EVENT;
3073 removeMessages(what);
3074 } else {
3075 what = DISPATCH_DRAG_EVENT;
3076 }
Christopher Tate407b4e92010-11-30 17:14:08 -08003077 event.mLocalState = mLocalDragState; // only present when this app called startDrag()
Chris Tate91e9bb32010-10-12 12:58:43 -07003078 Message msg = obtainMessage(what, event);
Christopher Tatea53146c2010-09-07 11:57:52 -07003079 sendMessage(msg);
3080 }
3081
svetoslavganov75986cf2009-05-14 22:28:01 -07003082 /**
3083 * The window is getting focus so if there is anything focused/selected
3084 * send an {@link AccessibilityEvent} to announce that.
3085 */
3086 private void sendAccessibilityEvents() {
3087 if (!AccessibilityManager.getInstance(mView.getContext()).isEnabled()) {
3088 return;
3089 }
3090 mView.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
3091 View focusedView = mView.findFocus();
3092 if (focusedView != null && focusedView != mView) {
3093 focusedView.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
3094 }
3095 }
3096
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003097 public boolean showContextMenuForChild(View originalView) {
3098 return false;
3099 }
3100
Adam Powell6e346362010-07-23 10:18:23 -07003101 public ActionMode startActionModeForChild(View originalView, ActionMode.Callback callback) {
3102 return null;
3103 }
3104
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003105 public void createContextMenu(ContextMenu menu) {
3106 }
3107
3108 public void childDrawableStateChanged(View child) {
3109 }
3110
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003111 void checkThread() {
3112 if (mThread != Thread.currentThread()) {
3113 throw new CalledFromWrongThreadException(
3114 "Only the original thread that created a view hierarchy can touch its views.");
3115 }
3116 }
3117
3118 public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
3119 // ViewRoot never intercepts touch event, so this can be a no-op
3120 }
3121
3122 public boolean requestChildRectangleOnScreen(View child, Rect rectangle,
3123 boolean immediate) {
3124 return scrollToRectOrFocus(rectangle, immediate);
3125 }
Romain Guy8506ab42009-06-11 17:35:47 -07003126
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07003127 class TakenSurfaceHolder extends BaseSurfaceHolder {
3128 @Override
3129 public boolean onAllowLockCanvas() {
3130 return mDrawingAllowed;
3131 }
3132
3133 @Override
3134 public void onRelayoutContainer() {
3135 // Not currently interesting -- from changing between fixed and layout size.
3136 }
3137
3138 public void setFormat(int format) {
3139 ((RootViewSurfaceTaker)mView).setSurfaceFormat(format);
3140 }
3141
3142 public void setType(int type) {
3143 ((RootViewSurfaceTaker)mView).setSurfaceType(type);
3144 }
3145
3146 @Override
3147 public void onUpdateSurface() {
3148 // We take care of format and type changes on our own.
3149 throw new IllegalStateException("Shouldn't be here");
3150 }
3151
3152 public boolean isCreating() {
3153 return mIsCreating;
3154 }
3155
3156 @Override
3157 public void setFixedSize(int width, int height) {
3158 throw new UnsupportedOperationException(
3159 "Currently only support sizing from layout");
3160 }
3161
3162 public void setKeepScreenOn(boolean screenOn) {
3163 ((RootViewSurfaceTaker)mView).setSurfaceKeepScreenOn(screenOn);
3164 }
3165 }
3166
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003167 static class InputMethodCallback extends IInputMethodCallback.Stub {
3168 private WeakReference<ViewRoot> mViewRoot;
3169
3170 public InputMethodCallback(ViewRoot viewRoot) {
3171 mViewRoot = new WeakReference<ViewRoot>(viewRoot);
3172 }
Romain Guy8506ab42009-06-11 17:35:47 -07003173
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003174 public void finishedEvent(int seq, boolean handled) {
3175 final ViewRoot viewRoot = mViewRoot.get();
3176 if (viewRoot != null) {
3177 viewRoot.dispatchFinishedEvent(seq, handled);
3178 }
3179 }
3180
3181 public void sessionCreated(IInputMethodSession session) throws RemoteException {
3182 // Stub -- not for use in the client.
3183 }
3184 }
Romain Guy8506ab42009-06-11 17:35:47 -07003185
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003186 static class W extends IWindow.Stub {
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07003187 private final WeakReference<ViewRoot> mViewRoot;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003188
Romain Guyfb8b7632010-08-23 21:05:08 -07003189 W(ViewRoot viewRoot) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003190 mViewRoot = new WeakReference<ViewRoot>(viewRoot);
3191 }
3192
Romain Guyfb8b7632010-08-23 21:05:08 -07003193 public void resized(int w, int h, Rect coveredInsets, Rect visibleInsets,
3194 boolean reportDraw, Configuration newConfig) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003195 final ViewRoot viewRoot = mViewRoot.get();
3196 if (viewRoot != null) {
Romain Guyfb8b7632010-08-23 21:05:08 -07003197 viewRoot.dispatchResized(w, h, coveredInsets, visibleInsets, reportDraw, newConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003198 }
3199 }
3200
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003201 public void dispatchAppVisibility(boolean visible) {
3202 final ViewRoot viewRoot = mViewRoot.get();
3203 if (viewRoot != null) {
3204 viewRoot.dispatchAppVisibility(visible);
3205 }
3206 }
3207
3208 public void dispatchGetNewSurface() {
3209 final ViewRoot viewRoot = mViewRoot.get();
3210 if (viewRoot != null) {
3211 viewRoot.dispatchGetNewSurface();
3212 }
3213 }
3214
3215 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
3216 final ViewRoot viewRoot = mViewRoot.get();
3217 if (viewRoot != null) {
3218 viewRoot.windowFocusChanged(hasFocus, inTouchMode);
3219 }
3220 }
3221
3222 private static int checkCallingPermission(String permission) {
3223 if (!Process.supportsProcesses()) {
3224 return PackageManager.PERMISSION_GRANTED;
3225 }
3226
3227 try {
3228 return ActivityManagerNative.getDefault().checkPermission(
3229 permission, Binder.getCallingPid(), Binder.getCallingUid());
3230 } catch (RemoteException e) {
3231 return PackageManager.PERMISSION_DENIED;
3232 }
3233 }
3234
3235 public void executeCommand(String command, String parameters, ParcelFileDescriptor out) {
3236 final ViewRoot viewRoot = mViewRoot.get();
3237 if (viewRoot != null) {
3238 final View view = viewRoot.mView;
3239 if (view != null) {
3240 if (checkCallingPermission(Manifest.permission.DUMP) !=
3241 PackageManager.PERMISSION_GRANTED) {
3242 throw new SecurityException("Insufficient permissions to invoke"
3243 + " executeCommand() from pid=" + Binder.getCallingPid()
3244 + ", uid=" + Binder.getCallingUid());
3245 }
3246
3247 OutputStream clientStream = null;
3248 try {
3249 clientStream = new ParcelFileDescriptor.AutoCloseOutputStream(out);
3250 ViewDebug.dispatchCommand(view, command, parameters, clientStream);
3251 } catch (IOException e) {
3252 e.printStackTrace();
3253 } finally {
3254 if (clientStream != null) {
3255 try {
3256 clientStream.close();
3257 } catch (IOException e) {
3258 e.printStackTrace();
3259 }
3260 }
3261 }
3262 }
3263 }
3264 }
Dianne Hackborn72c82ab2009-08-11 21:13:54 -07003265
Dianne Hackbornffa42482009-09-23 22:20:11 -07003266 public void closeSystemDialogs(String reason) {
3267 final ViewRoot viewRoot = mViewRoot.get();
3268 if (viewRoot != null) {
3269 viewRoot.dispatchCloseSystemDialogs(reason);
3270 }
3271 }
3272
Marco Nelissenbf6956b2009-11-09 15:21:13 -08003273 public void dispatchWallpaperOffsets(float x, float y, float xStep, float yStep,
3274 boolean sync) {
Dianne Hackborn19382ac2009-09-11 21:13:37 -07003275 if (sync) {
3276 try {
3277 sWindowSession.wallpaperOffsetsComplete(asBinder());
3278 } catch (RemoteException e) {
3279 }
3280 }
Dianne Hackborn72c82ab2009-08-11 21:13:54 -07003281 }
Dianne Hackborn75804932009-10-20 20:15:20 -07003282
3283 public void dispatchWallpaperCommand(String action, int x, int y,
3284 int z, Bundle extras, boolean sync) {
3285 if (sync) {
3286 try {
3287 sWindowSession.wallpaperCommandComplete(asBinder(), null);
3288 } catch (RemoteException e) {
3289 }
3290 }
3291 }
Christopher Tatea53146c2010-09-07 11:57:52 -07003292
3293 /* Drag/drop */
3294 public void dispatchDragEvent(DragEvent event) {
3295 final ViewRoot viewRoot = mViewRoot.get();
3296 if (viewRoot != null) {
3297 viewRoot.dispatchDragEvent(event);
3298 }
3299 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003300 }
3301
3302 /**
3303 * Maintains state information for a single trackball axis, generating
3304 * discrete (DPAD) movements based on raw trackball motion.
3305 */
3306 static final class TrackballAxis {
3307 /**
3308 * The maximum amount of acceleration we will apply.
3309 */
3310 static final float MAX_ACCELERATION = 20;
Romain Guy8506ab42009-06-11 17:35:47 -07003311
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003312 /**
3313 * The maximum amount of time (in milliseconds) between events in order
3314 * for us to consider the user to be doing fast trackball movements,
3315 * and thus apply an acceleration.
3316 */
3317 static final long FAST_MOVE_TIME = 150;
Romain Guy8506ab42009-06-11 17:35:47 -07003318
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003319 /**
3320 * Scaling factor to the time (in milliseconds) between events to how
3321 * much to multiple/divide the current acceleration. When movement
3322 * is < FAST_MOVE_TIME this multiplies the acceleration; when >
3323 * FAST_MOVE_TIME it divides it.
3324 */
3325 static final float ACCEL_MOVE_SCALING_FACTOR = (1.0f/40);
Romain Guy8506ab42009-06-11 17:35:47 -07003326
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003327 float position;
3328 float absPosition;
3329 float acceleration = 1;
3330 long lastMoveTime = 0;
3331 int step;
3332 int dir;
3333 int nonAccelMovement;
3334
3335 void reset(int _step) {
3336 position = 0;
3337 acceleration = 1;
3338 lastMoveTime = 0;
3339 step = _step;
3340 dir = 0;
3341 }
3342
3343 /**
3344 * Add trackball movement into the state. If the direction of movement
3345 * has been reversed, the state is reset before adding the
3346 * movement (so that you don't have to compensate for any previously
3347 * collected movement before see the result of the movement in the
3348 * new direction).
3349 *
3350 * @return Returns the absolute value of the amount of movement
3351 * collected so far.
3352 */
3353 float collect(float off, long time, String axis) {
3354 long normTime;
3355 if (off > 0) {
3356 normTime = (long)(off * FAST_MOVE_TIME);
3357 if (dir < 0) {
3358 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to positive!");
3359 position = 0;
3360 step = 0;
3361 acceleration = 1;
3362 lastMoveTime = 0;
3363 }
3364 dir = 1;
3365 } else if (off < 0) {
3366 normTime = (long)((-off) * FAST_MOVE_TIME);
3367 if (dir > 0) {
3368 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to negative!");
3369 position = 0;
3370 step = 0;
3371 acceleration = 1;
3372 lastMoveTime = 0;
3373 }
3374 dir = -1;
3375 } else {
3376 normTime = 0;
3377 }
Romain Guy8506ab42009-06-11 17:35:47 -07003378
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003379 // The number of milliseconds between each movement that is
3380 // considered "normal" and will not result in any acceleration
3381 // or deceleration, scaled by the offset we have here.
3382 if (normTime > 0) {
3383 long delta = time - lastMoveTime;
3384 lastMoveTime = time;
3385 float acc = acceleration;
3386 if (delta < normTime) {
3387 // The user is scrolling rapidly, so increase acceleration.
3388 float scale = (normTime-delta) * ACCEL_MOVE_SCALING_FACTOR;
3389 if (scale > 1) acc *= scale;
3390 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " accelerate: off="
3391 + off + " normTime=" + normTime + " delta=" + delta
3392 + " scale=" + scale + " acc=" + acc);
3393 acceleration = acc < MAX_ACCELERATION ? acc : MAX_ACCELERATION;
3394 } else {
3395 // The user is scrolling slowly, so decrease acceleration.
3396 float scale = (delta-normTime) * ACCEL_MOVE_SCALING_FACTOR;
3397 if (scale > 1) acc /= scale;
3398 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " deccelerate: off="
3399 + off + " normTime=" + normTime + " delta=" + delta
3400 + " scale=" + scale + " acc=" + acc);
3401 acceleration = acc > 1 ? acc : 1;
3402 }
3403 }
3404 position += off;
3405 return (absPosition = Math.abs(position));
3406 }
3407
3408 /**
3409 * Generate the number of discrete movement events appropriate for
3410 * the currently collected trackball movement.
3411 *
3412 * @param precision The minimum movement required to generate the
3413 * first discrete movement.
3414 *
3415 * @return Returns the number of discrete movements, either positive
3416 * or negative, or 0 if there is not enough trackball movement yet
3417 * for a discrete movement.
3418 */
3419 int generate(float precision) {
3420 int movement = 0;
3421 nonAccelMovement = 0;
3422 do {
3423 final int dir = position >= 0 ? 1 : -1;
3424 switch (step) {
3425 // If we are going to execute the first step, then we want
3426 // to do this as soon as possible instead of waiting for
3427 // a full movement, in order to make things look responsive.
3428 case 0:
3429 if (absPosition < precision) {
3430 return movement;
3431 }
3432 movement += dir;
3433 nonAccelMovement += dir;
3434 step = 1;
3435 break;
3436 // If we have generated the first movement, then we need
3437 // to wait for the second complete trackball motion before
3438 // generating the second discrete movement.
3439 case 1:
3440 if (absPosition < 2) {
3441 return movement;
3442 }
3443 movement += dir;
3444 nonAccelMovement += dir;
3445 position += dir > 0 ? -2 : 2;
3446 absPosition = Math.abs(position);
3447 step = 2;
3448 break;
3449 // After the first two, we generate discrete movements
3450 // consistently with the trackball, applying an acceleration
3451 // if the trackball is moving quickly. This is a simple
3452 // acceleration on top of what we already compute based
3453 // on how quickly the wheel is being turned, to apply
3454 // a longer increasing acceleration to continuous movement
3455 // in one direction.
3456 default:
3457 if (absPosition < 1) {
3458 return movement;
3459 }
3460 movement += dir;
3461 position += dir >= 0 ? -1 : 1;
3462 absPosition = Math.abs(position);
3463 float acc = acceleration;
3464 acc *= 1.1f;
3465 acceleration = acc < MAX_ACCELERATION ? acc : acceleration;
3466 break;
3467 }
3468 } while (true);
3469 }
3470 }
3471
3472 public static final class CalledFromWrongThreadException extends AndroidRuntimeException {
3473 public CalledFromWrongThreadException(String msg) {
3474 super(msg);
3475 }
3476 }
3477
3478 private SurfaceHolder mHolder = new SurfaceHolder() {
3479 // we only need a SurfaceHolder for opengl. it would be nice
3480 // to implement everything else though, especially the callback
3481 // support (opengl doesn't make use of it right now, but eventually
3482 // will).
3483 public Surface getSurface() {
3484 return mSurface;
3485 }
3486
3487 public boolean isCreating() {
3488 return false;
3489 }
3490
3491 public void addCallback(Callback callback) {
3492 }
3493
3494 public void removeCallback(Callback callback) {
3495 }
3496
3497 public void setFixedSize(int width, int height) {
3498 }
3499
3500 public void setSizeFromLayout() {
3501 }
3502
3503 public void setFormat(int format) {
3504 }
3505
3506 public void setType(int type) {
3507 }
3508
3509 public void setKeepScreenOn(boolean screenOn) {
3510 }
3511
3512 public Canvas lockCanvas() {
3513 return null;
3514 }
3515
3516 public Canvas lockCanvas(Rect dirty) {
3517 return null;
3518 }
3519
3520 public void unlockCanvasAndPost(Canvas canvas) {
3521 }
3522 public Rect getSurfaceFrame() {
3523 return null;
3524 }
3525 };
3526
3527 static RunQueue getRunQueue() {
3528 RunQueue rq = sRunQueues.get();
3529 if (rq != null) {
3530 return rq;
3531 }
3532 rq = new RunQueue();
3533 sRunQueues.set(rq);
3534 return rq;
3535 }
Romain Guy8506ab42009-06-11 17:35:47 -07003536
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003537 /**
3538 * @hide
3539 */
3540 static final class RunQueue {
3541 private final ArrayList<HandlerAction> mActions = new ArrayList<HandlerAction>();
3542
3543 void post(Runnable action) {
3544 postDelayed(action, 0);
3545 }
3546
3547 void postDelayed(Runnable action, long delayMillis) {
3548 HandlerAction handlerAction = new HandlerAction();
3549 handlerAction.action = action;
3550 handlerAction.delay = delayMillis;
3551
3552 synchronized (mActions) {
3553 mActions.add(handlerAction);
3554 }
3555 }
3556
3557 void removeCallbacks(Runnable action) {
3558 final HandlerAction handlerAction = new HandlerAction();
3559 handlerAction.action = action;
3560
3561 synchronized (mActions) {
3562 final ArrayList<HandlerAction> actions = mActions;
3563
3564 while (actions.remove(handlerAction)) {
3565 // Keep going
3566 }
3567 }
3568 }
3569
3570 void executeActions(Handler handler) {
3571 synchronized (mActions) {
3572 final ArrayList<HandlerAction> actions = mActions;
3573 final int count = actions.size();
3574
3575 for (int i = 0; i < count; i++) {
3576 final HandlerAction handlerAction = actions.get(i);
3577 handler.postDelayed(handlerAction.action, handlerAction.delay);
3578 }
3579
Romain Guy15df6702009-08-17 20:17:30 -07003580 actions.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003581 }
3582 }
3583
3584 private static class HandlerAction {
3585 Runnable action;
3586 long delay;
3587
3588 @Override
3589 public boolean equals(Object o) {
3590 if (this == o) return true;
3591 if (o == null || getClass() != o.getClass()) return false;
3592
3593 HandlerAction that = (HandlerAction) o;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003594 return !(action != null ? !action.equals(that.action) : that.action != null);
3595
3596 }
3597
3598 @Override
3599 public int hashCode() {
3600 int result = action != null ? action.hashCode() : 0;
3601 result = 31 * result + (int) (delay ^ (delay >>> 32));
3602 return result;
3603 }
3604 }
3605 }
3606
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003607 private static native void nativeShowFPS(Canvas canvas, int durationMillis);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003608}