blob: 77083a902112560d9718080b5b49a600942d80fd [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;
231 final PointF mDragPoint = new PointF();
Christopher Tate2c095f32010-10-04 14:13:40 -0700232 final PointF mLastTouchPoint = new PointF();
Christopher Tatea53146c2010-09-07 11:57:52 -0700233
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800234 /**
235 * see {@link #playSoundEffect(int)}
236 */
237 AudioManager mAudioManager;
238
Dianne Hackborn11ea3342009-07-22 21:48:55 -0700239 private final int mDensity;
Adam Powellb08013c2010-09-16 16:28:11 -0700240
Dianne Hackborn4c62fc02009-08-08 20:40:27 -0700241 public static IWindowSession getWindowSession(Looper mainLooper) {
242 synchronized (mStaticInit) {
243 if (!mInitialized) {
244 try {
245 InputMethodManager imm = InputMethodManager.getInstance(mainLooper);
246 sWindowSession = IWindowManager.Stub.asInterface(
247 ServiceManager.getService("window"))
248 .openSession(imm.getClient(), imm.getInputContext());
249 mInitialized = true;
250 } catch (RemoteException e) {
251 }
252 }
253 return sWindowSession;
254 }
255 }
256
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800257 public ViewRoot(Context context) {
258 super();
259
Romain Guy812ccbe2010-06-01 14:07:24 -0700260 if (MEASURE_LATENCY) {
261 if (lt == null) {
262 lt = new LatencyTimer(100, 1000);
263 }
Michael Chan53071d62009-05-13 17:29:48 -0700264 }
265
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800266 // Initialize the statics when this class is first instantiated. This is
267 // done here instead of in the static block because Zygote does not
268 // allow the spawning of threads.
Dianne Hackborn4c62fc02009-08-08 20:40:27 -0700269 getWindowSession(context.getMainLooper());
270
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800271 mThread = Thread.currentThread();
272 mLocation = new WindowLeaked(null);
273 mLocation.fillInStackTrace();
274 mWidth = -1;
275 mHeight = -1;
276 mDirty = new Rect();
277 mTempRect = new Rect();
278 mVisRect = new Rect();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800279 mWinFrame = new Rect();
Romain Guyfb8b7632010-08-23 21:05:08 -0700280 mWindow = new W(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800281 mInputMethodCallback = new InputMethodCallback(this);
282 mViewVisibility = View.GONE;
283 mTransparentRegion = new Region();
284 mPreviousTransparentRegion = new Region();
285 mFirst = true; // true for the first time the view is added
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800286 mAdded = false;
287 mAttachInfo = new View.AttachInfo(sWindowSession, mWindow, this, this);
288 mViewConfiguration = ViewConfiguration.get(context);
Dianne Hackborn11ea3342009-07-22 21:48:55 -0700289 mDensity = context.getResources().getDisplayMetrics().densityDpi;
Joe Onorato86f67862010-11-05 18:57:34 -0700290 mFallbackEventHandler = PolicyManager.makeNewFallbackEventHandler(context);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800291 }
292
Dianne Hackborn2a9094d2010-02-03 19:20:09 -0800293 public static void addFirstDrawHandler(Runnable callback) {
294 synchronized (sFirstDrawHandlers) {
295 if (!sFirstDrawComplete) {
296 sFirstDrawHandlers.add(callback);
297 }
298 }
299 }
300
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800301 public static void addConfigCallback(ComponentCallbacks callback) {
302 synchronized (sConfigCallbacks) {
303 sConfigCallbacks.add(callback);
304 }
305 }
306
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800307 // FIXME for perf testing only
308 private boolean mProfile = false;
309
310 /**
311 * Call this to profile the next traversal call.
312 * FIXME for perf testing only. Remove eventually
313 */
314 public void profile() {
315 mProfile = true;
316 }
317
318 /**
319 * Indicates whether we are in touch mode. Calling this method triggers an IPC
320 * call and should be avoided whenever possible.
321 *
322 * @return True, if the device is in touch mode, false otherwise.
323 *
324 * @hide
325 */
326 static boolean isInTouchMode() {
327 if (mInitialized) {
328 try {
329 return sWindowSession.getInTouchMode();
330 } catch (RemoteException e) {
331 }
332 }
333 return false;
334 }
335
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800336 /**
337 * We have one child
338 */
Romain Guye4d01122010-06-16 18:44:05 -0700339 public void setView(View view, WindowManager.LayoutParams attrs, View panelParentView) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800340 synchronized (this) {
341 if (mView == null) {
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700342 mView = view;
Joe Onorato86f67862010-11-05 18:57:34 -0700343 mFallbackEventHandler.setView(view);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700344 mWindowAttributes.copyFrom(attrs);
Mitsuru Oshima1ecf5d22009-07-06 17:20:38 -0700345 attrs = mWindowAttributes;
Romain Guye4d01122010-06-16 18:44:05 -0700346
Romain Guy529b60a2010-08-03 18:05:47 -0700347 enableHardwareAcceleration(attrs);
Romain Guye4d01122010-06-16 18:44:05 -0700348
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700349 if (view instanceof RootViewSurfaceTaker) {
350 mSurfaceHolderCallback =
351 ((RootViewSurfaceTaker)view).willYouTakeTheSurface();
352 if (mSurfaceHolderCallback != null) {
353 mSurfaceHolder = new TakenSurfaceHolder();
Dianne Hackborn289b9b62010-07-09 11:44:11 -0700354 mSurfaceHolder.setFormat(PixelFormat.UNKNOWN);
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700355 }
356 }
Mitsuru Oshima38ed7d772009-07-21 14:39:34 -0700357 Resources resources = mView.getContext().getResources();
358 CompatibilityInfo compatibilityInfo = resources.getCompatibilityInfo();
Mitsuru Oshima589cebe2009-07-22 20:38:58 -0700359 mTranslator = compatibilityInfo.getTranslator();
Mitsuru Oshima38ed7d772009-07-21 14:39:34 -0700360
361 if (mTranslator != null || !compatibilityInfo.supportsScreen()) {
Mitsuru Oshima240f8a72009-07-22 20:39:14 -0700362 mSurface.setCompatibleDisplayMetrics(resources.getDisplayMetrics(),
363 mTranslator);
Mitsuru Oshima38ed7d772009-07-21 14:39:34 -0700364 }
365
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -0700366 boolean restore = false;
Romain Guy35b38ce2009-10-07 13:38:55 -0700367 if (mTranslator != null) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -0700368 restore = true;
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700369 attrs.backup();
370 mTranslator.translateWindowLayout(attrs);
Mitsuru Oshima3d914922009-05-13 22:29:15 -0700371 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700372 if (DEBUG_LAYOUT) Log.d(TAG, "WindowLayout in setView:" + attrs);
373
Mitsuru Oshima1ecf5d22009-07-06 17:20:38 -0700374 if (!compatibilityInfo.supportsScreen()) {
375 attrs.flags |= WindowManager.LayoutParams.FLAG_COMPATIBLE_WINDOW;
376 }
377
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800378 mSoftInputMode = attrs.softInputMode;
379 mWindowAttributesChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800380 mAttachInfo.mRootView = view;
Romain Guy35b38ce2009-10-07 13:38:55 -0700381 mAttachInfo.mScalingRequired = mTranslator != null;
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700382 mAttachInfo.mApplicationScale =
383 mTranslator == null ? 1.0f : mTranslator.applicationScale;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800384 if (panelParentView != null) {
385 mAttachInfo.mPanelParentWindowToken
386 = panelParentView.getApplicationWindowToken();
387 }
388 mAdded = true;
389 int res; /* = WindowManagerImpl.ADD_OKAY; */
Romain Guy8506ab42009-06-11 17:35:47 -0700390
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800391 // Schedule the first layout -before- adding to the window
392 // manager, to make sure we do the relayout before receiving
393 // any other events from the system.
394 requestLayout();
Jeff Brown46b9ac02010-04-22 18:58:52 -0700395 mInputChannel = new InputChannel();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800396 try {
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700397 res = sWindowSession.add(mWindow, mWindowAttributes,
Jeff Brown46b9ac02010-04-22 18:58:52 -0700398 getHostVisibility(), mAttachInfo.mContentInsets,
399 mInputChannel);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800400 } catch (RemoteException e) {
401 mAdded = false;
402 mView = null;
403 mAttachInfo.mRootView = null;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700404 mInputChannel = null;
Joe Onorato86f67862010-11-05 18:57:34 -0700405 mFallbackEventHandler.setView(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800406 unscheduleTraversals();
407 throw new RuntimeException("Adding window failed", e);
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700408 } finally {
409 if (restore) {
410 attrs.restore();
411 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800412 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700413
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700414 if (mTranslator != null) {
415 mTranslator.translateRectInScreenToAppWindow(mAttachInfo.mContentInsets);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700416 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800417 mPendingContentInsets.set(mAttachInfo.mContentInsets);
418 mPendingVisibleInsets.set(0, 0, 0, 0);
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800419 if (DEBUG_LAYOUT) Log.v(TAG, "Added window " + mWindow);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800420 if (res < WindowManagerImpl.ADD_OKAY) {
421 mView = null;
422 mAttachInfo.mRootView = null;
423 mAdded = false;
Joe Onorato86f67862010-11-05 18:57:34 -0700424 mFallbackEventHandler.setView(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800425 unscheduleTraversals();
426 switch (res) {
427 case WindowManagerImpl.ADD_BAD_APP_TOKEN:
428 case WindowManagerImpl.ADD_BAD_SUBWINDOW_TOKEN:
429 throw new WindowManagerImpl.BadTokenException(
430 "Unable to add window -- token " + attrs.token
431 + " is not valid; is your activity running?");
432 case WindowManagerImpl.ADD_NOT_APP_TOKEN:
433 throw new WindowManagerImpl.BadTokenException(
434 "Unable to add window -- token " + attrs.token
435 + " is not for an application");
436 case WindowManagerImpl.ADD_APP_EXITING:
437 throw new WindowManagerImpl.BadTokenException(
438 "Unable to add window -- app for token " + attrs.token
439 + " is exiting");
440 case WindowManagerImpl.ADD_DUPLICATE_ADD:
441 throw new WindowManagerImpl.BadTokenException(
442 "Unable to add window -- window " + mWindow
443 + " has already been added");
444 case WindowManagerImpl.ADD_STARTING_NOT_NEEDED:
445 // Silently ignore -- we would have just removed it
446 // right away, anyway.
447 return;
448 case WindowManagerImpl.ADD_MULTIPLE_SINGLETON:
449 throw new WindowManagerImpl.BadTokenException(
450 "Unable to add window " + mWindow +
451 " -- another window of this type already exists");
452 case WindowManagerImpl.ADD_PERMISSION_DENIED:
453 throw new WindowManagerImpl.BadTokenException(
454 "Unable to add window " + mWindow +
455 " -- permission denied for this window type");
456 }
457 throw new RuntimeException(
458 "Unable to add window -- unknown error code " + res);
459 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700460
Jeff Brown00fa7bd2010-07-02 15:37:36 -0700461 if (view instanceof RootViewSurfaceTaker) {
462 mInputQueueCallback =
463 ((RootViewSurfaceTaker)view).willYouTakeTheInputQueue();
464 }
465 if (mInputQueueCallback != null) {
466 mInputQueue = new InputQueue(mInputChannel);
467 mInputQueueCallback.onInputQueueCreated(mInputQueue);
468 } else {
469 InputQueue.registerInputChannel(mInputChannel, mInputHandler,
470 Looper.myQueue());
Jeff Brown46b9ac02010-04-22 18:58:52 -0700471 }
472
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800473 view.assignParent(this);
474 mAddedTouchMode = (res&WindowManagerImpl.ADD_FLAG_IN_TOUCH_MODE) != 0;
475 mAppVisible = (res&WindowManagerImpl.ADD_FLAG_APP_VISIBLE) != 0;
476 }
477 }
478 }
479
Romain Guy529b60a2010-08-03 18:05:47 -0700480 private void enableHardwareAcceleration(WindowManager.LayoutParams attrs) {
Dianne Hackborn7eec10e2010-11-12 18:03:47 -0800481 mAttachInfo.mHardwareAccelerated = false;
482 mAttachInfo.mHardwareAccelerationRequested = false;
483
484 // Try to enable hardware acceleration if requested
485 if (attrs != null &&
486 (attrs.flags & WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED) != 0) {
487 // Only enable hardware acceleration if we are not in the system process
488 // The window manager creates ViewRoots to display animated preview windows
489 // of launching apps and we don't want those to be hardware accelerated
490 if (!HardwareRenderer.sRendererDisabled) {
Romain Guye4d01122010-06-16 18:44:05 -0700491 final boolean translucent = attrs.format != PixelFormat.OPAQUE;
Romain Guyb051e892010-09-28 19:09:36 -0700492 if (mAttachInfo.mHardwareRenderer != null) {
493 mAttachInfo.mHardwareRenderer.destroy(true);
Romain Guy4caa4ed2010-08-25 14:46:24 -0700494 }
Romain Guyb051e892010-09-28 19:09:36 -0700495 mAttachInfo.mHardwareRenderer = HardwareRenderer.createGlRenderer(2, translucent);
Dianne Hackborn7eec10e2010-11-12 18:03:47 -0800496 mAttachInfo.mHardwareAccelerated = mAttachInfo.mHardwareAccelerationRequested
497 = mAttachInfo.mHardwareRenderer != null;
498 } else if (HardwareRenderer.isAvailable()) {
499 mAttachInfo.mHardwareAccelerationRequested = true;
Romain Guye4d01122010-06-16 18:44:05 -0700500 }
501 }
502 }
503
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800504 public View getView() {
505 return mView;
506 }
507
508 final WindowLeaked getLocation() {
509 return mLocation;
510 }
511
512 void setLayoutParams(WindowManager.LayoutParams attrs, boolean newView) {
513 synchronized (this) {
The Android Open Source Project10592532009-03-18 17:39:46 -0700514 int oldSoftInputMode = mWindowAttributes.softInputMode;
Mitsuru Oshima5a2b91d2009-07-16 16:30:02 -0700515 // preserve compatible window flag if exists.
516 int compatibleWindowFlag =
517 mWindowAttributes.flags & WindowManager.LayoutParams.FLAG_COMPATIBLE_WINDOW;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800518 mWindowAttributes.copyFrom(attrs);
Mitsuru Oshima5a2b91d2009-07-16 16:30:02 -0700519 mWindowAttributes.flags |= compatibleWindowFlag;
520
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800521 if (newView) {
522 mSoftInputMode = attrs.softInputMode;
523 requestLayout();
524 }
The Android Open Source Project10592532009-03-18 17:39:46 -0700525 // Don't lose the mode we last auto-computed.
526 if ((attrs.softInputMode&WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST)
527 == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED) {
528 mWindowAttributes.softInputMode = (mWindowAttributes.softInputMode
529 & ~WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST)
530 | (oldSoftInputMode
531 & WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST);
532 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800533 mWindowAttributesChanged = true;
534 scheduleTraversals();
535 }
536 }
537
538 void handleAppVisibility(boolean visible) {
539 if (mAppVisible != visible) {
540 mAppVisible = visible;
541 scheduleTraversals();
542 }
543 }
544
545 void handleGetNewSurface() {
546 mNewSurfaceNeeded = true;
547 mFullRedrawNeeded = true;
548 scheduleTraversals();
549 }
550
551 /**
552 * {@inheritDoc}
553 */
554 public void requestLayout() {
555 checkThread();
556 mLayoutRequested = true;
557 scheduleTraversals();
558 }
559
560 /**
561 * {@inheritDoc}
562 */
563 public boolean isLayoutRequested() {
564 return mLayoutRequested;
565 }
566
567 public void invalidateChild(View child, Rect dirty) {
568 checkThread();
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700569 if (DEBUG_DRAW) Log.v(TAG, "Invalidate child: " + dirty);
Chet Haase70d4ba12010-10-06 09:46:45 -0700570 if (dirty == null) {
571 // Fast invalidation for GL-enabled applications; GL must redraw everything
572 invalidate();
573 return;
574 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700575 if (mCurScrollY != 0 || mTranslator != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800576 mTempRect.set(dirty);
Romain Guy1e095972009-07-07 11:22:45 -0700577 dirty = mTempRect;
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700578 if (mCurScrollY != 0) {
Romain Guy1e095972009-07-07 11:22:45 -0700579 dirty.offset(0, -mCurScrollY);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700580 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700581 if (mTranslator != null) {
Romain Guy1e095972009-07-07 11:22:45 -0700582 mTranslator.translateRectInAppWindowToScreen(dirty);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700583 }
Romain Guy1e095972009-07-07 11:22:45 -0700584 if (mAttachInfo.mScalingRequired) {
585 dirty.inset(-1, -1);
586 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800587 }
588 mDirty.union(dirty);
589 if (!mWillDrawSoon) {
590 scheduleTraversals();
591 }
592 }
Romain Guy0d9275e2010-10-26 14:22:30 -0700593
594 void invalidate() {
595 mDirty.set(0, 0, mWidth, mHeight);
596 scheduleTraversals();
597 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800598
599 public ViewParent getParent() {
600 return null;
601 }
602
603 public ViewParent invalidateChildInParent(final int[] location, final Rect dirty) {
604 invalidateChild(null, dirty);
605 return null;
606 }
607
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700608 public boolean getChildVisibleRect(View child, Rect r, android.graphics.Point offset) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800609 if (child != mView) {
610 throw new RuntimeException("child is not mine, honest!");
611 }
612 // Note: don't apply scroll offset, because we want to know its
613 // visibility in the virtual canvas being given to the view hierarchy.
614 return r.intersect(0, 0, mWidth, mHeight);
615 }
616
617 public void bringChildToFront(View child) {
618 }
619
620 public void scheduleTraversals() {
621 if (!mTraversalScheduled) {
622 mTraversalScheduled = true;
623 sendEmptyMessage(DO_TRAVERSAL);
624 }
625 }
626
627 public void unscheduleTraversals() {
628 if (mTraversalScheduled) {
629 mTraversalScheduled = false;
630 removeMessages(DO_TRAVERSAL);
631 }
632 }
633
634 int getHostVisibility() {
635 return mAppVisible ? mView.getVisibility() : View.GONE;
636 }
Romain Guy8506ab42009-06-11 17:35:47 -0700637
Dianne Hackborn0f761d62010-11-30 22:06:10 -0800638 void disposeResizeBitmap() {
639 if (mResizeBitmap != null) {
640 mResizeBitmap.recycle();
641 mResizeBitmap = null;
642 }
643 }
644
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800645 private void performTraversals() {
646 // cache mView since it is used so much below...
647 final View host = mView;
648
649 if (DBG) {
650 System.out.println("======================================");
651 System.out.println("performTraversals");
652 host.debug();
653 }
654
655 if (host == null || !mAdded)
656 return;
657
658 mTraversalScheduled = false;
659 mWillDrawSoon = true;
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800660 boolean windowSizeMayChange = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800661 boolean fullRedrawNeeded = mFullRedrawNeeded;
662 boolean newSurface = false;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700663 boolean surfaceChanged = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800664 WindowManager.LayoutParams lp = mWindowAttributes;
665
666 int desiredWindowWidth;
667 int desiredWindowHeight;
668 int childWidthMeasureSpec;
669 int childHeightMeasureSpec;
670
671 final View.AttachInfo attachInfo = mAttachInfo;
672
673 final int viewVisibility = getHostVisibility();
674 boolean viewVisibilityChanged = mViewVisibility != viewVisibility
675 || mNewSurfaceNeeded;
676
677 WindowManager.LayoutParams params = null;
678 if (mWindowAttributesChanged) {
679 mWindowAttributesChanged = false;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700680 surfaceChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800681 params = lp;
682 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700683 Rect frame = mWinFrame;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800684 if (mFirst) {
685 fullRedrawNeeded = true;
686 mLayoutRequested = true;
687
Romain Guy8506ab42009-06-11 17:35:47 -0700688 DisplayMetrics packageMetrics =
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700689 mView.getContext().getResources().getDisplayMetrics();
690 desiredWindowWidth = packageMetrics.widthPixels;
691 desiredWindowHeight = packageMetrics.heightPixels;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800692
693 // For the very first time, tell the view hierarchy that it
694 // is attached to the window. Note that at this point the surface
695 // object is not initialized to its backing store, but soon it
696 // will be (assuming the window is visible).
697 attachInfo.mSurface = mSurface;
Adam Powell26153a32010-11-08 15:22:27 -0800698 attachInfo.mUse32BitDrawingCache = PixelFormat.formatHasAlpha(lp.format) ||
699 lp.format == PixelFormat.RGBX_8888;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800700 attachInfo.mHasWindowFocus = false;
701 attachInfo.mWindowVisibility = viewVisibility;
702 attachInfo.mRecomputeGlobalAttributes = false;
703 attachInfo.mKeepScreenOn = false;
704 viewVisibilityChanged = false;
Dianne Hackborn694f79b2010-03-17 19:44:59 -0700705 mLastConfiguration.setTo(host.getResources().getConfiguration());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800706 host.dispatchAttachedToWindow(attachInfo, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800707 //Log.i(TAG, "Screen on initialized: " + attachInfo.mKeepScreenOn);
svetoslavganov75986cf2009-05-14 22:28:01 -0700708
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800709 } else {
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700710 desiredWindowWidth = frame.width();
711 desiredWindowHeight = frame.height();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800712 if (desiredWindowWidth != mWidth || desiredWindowHeight != mHeight) {
Jeff Brownc5ed5912010-07-14 18:48:53 -0700713 if (DEBUG_ORIENTATION) Log.v(TAG,
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700714 "View " + host + " resized to: " + frame);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800715 fullRedrawNeeded = true;
716 mLayoutRequested = true;
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800717 windowSizeMayChange = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800718 }
719 }
720
721 if (viewVisibilityChanged) {
722 attachInfo.mWindowVisibility = viewVisibility;
723 host.dispatchWindowVisibilityChanged(viewVisibility);
724 if (viewVisibility != View.VISIBLE || mNewSurfaceNeeded) {
Romain Guyb051e892010-09-28 19:09:36 -0700725 if (mAttachInfo.mHardwareRenderer != null) {
726 mAttachInfo.mHardwareRenderer.destroy(false);
Romain Guy4caa4ed2010-08-25 14:46:24 -0700727 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800728 }
729 if (viewVisibility == View.GONE) {
730 // After making a window gone, we will count it as being
731 // shown for the first time the next time it gets focus.
732 mHasHadWindowFocus = false;
733 }
734 }
735
736 boolean insetsChanged = false;
Romain Guy8506ab42009-06-11 17:35:47 -0700737
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800738 if (mLayoutRequested) {
Romain Guy15df6702009-08-17 20:17:30 -0700739 // Execute enqueued actions on every layout in case a view that was detached
740 // enqueued an action after being detached
741 getRunQueue().executeActions(attachInfo.mHandler);
742
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800743 final Resources res = mView.getContext().getResources();
744
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800745 if (mFirst) {
746 host.fitSystemWindows(mAttachInfo.mContentInsets);
747 // make sure touch mode code executes by setting cached value
748 // to opposite of the added touch mode.
749 mAttachInfo.mInTouchMode = !mAddedTouchMode;
Romain Guy2d4cff62010-04-09 15:39:00 -0700750 ensureTouchModeLocally(mAddedTouchMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800751 } else {
752 if (!mAttachInfo.mContentInsets.equals(mPendingContentInsets)) {
Dianne Hackborn0f761d62010-11-30 22:06:10 -0800753 if (mWidth > 0 && mHeight > 0 &&
754 mSurface != null && mSurface.isValid() &&
755 mAttachInfo.mHardwareRenderer != null &&
756 mAttachInfo.mHardwareRenderer.isEnabled() &&
757 lp != null && !PixelFormat.formatHasAlpha(lp.format)) {
758
759 disposeResizeBitmap();
760
761 boolean completed = false;
762 try {
763 mResizeBitmap = Bitmap.createBitmap(mWidth, mHeight,
764 Bitmap.Config.ARGB_8888);
765 mResizeBitmap.setHasAlpha(false);
766 Canvas canvas = new Canvas(mResizeBitmap);
767 int yoff;
768 final boolean scrolling = mScroller != null
769 && mScroller.computeScrollOffset();
770 if (scrolling) {
771 yoff = mScroller.getCurrY();
772 mScroller.abortAnimation();
773 } else {
774 yoff = mScrollY;
775 }
776 canvas.translate(0, -yoff);
777 if (mTranslator != null) {
778 mTranslator.translateCanvas(canvas);
779 }
780 canvas.setScreenDensity(mAttachInfo.mScalingRequired
781 ? DisplayMetrics.DENSITY_DEVICE : 0);
782 mView.draw(canvas);
783 mResizeBitmapStartTime = SystemClock.uptimeMillis();
784 mResizeBitmapDuration = mView.getResources().getInteger(
785 com.android.internal.R.integer.config_mediumAnimTime);
786 completed = true;
787 } catch (OutOfMemoryError e) {
788 Log.w(TAG, "Not enough memory for content change anim buffer", e);
789 } finally {
790 if (!completed) {
791 mResizeBitmap = null;
792 }
793 }
794 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800795 mAttachInfo.mContentInsets.set(mPendingContentInsets);
796 host.fitSystemWindows(mAttachInfo.mContentInsets);
797 insetsChanged = true;
798 if (DEBUG_LAYOUT) Log.v(TAG, "Content insets changing to: "
799 + mAttachInfo.mContentInsets);
800 }
801 if (!mAttachInfo.mVisibleInsets.equals(mPendingVisibleInsets)) {
802 mAttachInfo.mVisibleInsets.set(mPendingVisibleInsets);
803 if (DEBUG_LAYOUT) Log.v(TAG, "Visible insets changing to: "
804 + mAttachInfo.mVisibleInsets);
805 }
806 if (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT
807 || lp.height == ViewGroup.LayoutParams.WRAP_CONTENT) {
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800808 windowSizeMayChange = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800809
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800810 DisplayMetrics packageMetrics = res.getDisplayMetrics();
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700811 desiredWindowWidth = packageMetrics.widthPixels;
812 desiredWindowHeight = packageMetrics.heightPixels;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800813 }
814 }
815
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800816 // Ask host how big it wants to be
Jeff Brownc5ed5912010-07-14 18:48:53 -0700817 if (DEBUG_ORIENTATION || DEBUG_LAYOUT) Log.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800818 "Measuring " + host + " in display " + desiredWindowWidth
819 + "x" + desiredWindowHeight + "...");
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800820
821 boolean goodMeasure = false;
822 if (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT
823 || lp.height == ViewGroup.LayoutParams.WRAP_CONTENT) {
824 // On large screens, we don't want to allow dialogs to just
825 // stretch to fill the entire width of the screen to display
826 // one line of text. First try doing the layout at a smaller
827 // size to see if it will fit.
828 final DisplayMetrics packageMetrics = res.getDisplayMetrics();
829 res.getValue(com.android.internal.R.dimen.config_prefDialogWidth, mTmpValue, true);
830 int baseSize = 0;
831 if (mTmpValue.type == TypedValue.TYPE_DIMENSION) {
832 baseSize = (int)mTmpValue.getDimension(packageMetrics);
833 }
834 if (DEBUG_DIALOG) Log.v(TAG, "Window " + mView + ": baseSize=" + baseSize);
Dianne Hackborn7d3a5bc2010-11-29 22:52:12 -0800835 if (baseSize != 0 && desiredWindowWidth > baseSize) {
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800836 int maxHeight = (desiredWindowHeight*2)/3;
837 childWidthMeasureSpec = getRootMeasureSpec(baseSize, lp.width);
838 childHeightMeasureSpec = getRootMeasureSpec(desiredWindowHeight, lp.height);
839 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
840 if (DEBUG_DIALOG) Log.v(TAG, "Window " + mView + ": measured ("
841 + host.getWidth() + "," + host.getHeight() + ")");
842 // Note: for now we are not taking into account height, since we
843 // can't distinguish between places where it would be useful to
844 // increase the width (text) vs. where it would not (a list).
845 // Maybe we can just try the next size up, and see if that reduces
846 // the height?
847 if (host.getWidth() <= baseSize /*&& host.getHeight() <= maxHeight*/) {
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800848 goodMeasure = true;
849 } else {
850 // Didn't fit in that size... try expanding a bit.
851 baseSize = (baseSize+desiredWindowWidth)/2;
852 if (DEBUG_DIALOG) Log.v(TAG, "Window " + mView + ": next baseSize="
853 + baseSize);
854 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
855 if (DEBUG_DIALOG) Log.v(TAG, "Window " + mView + ": measured ("
856 + host.getWidth() + "," + host.getHeight() + ")");
857 if (host.getWidth() <= baseSize /*&& host.getHeight() <= maxHeight*/) {
858 if (DEBUG_DIALOG) Log.v(TAG, "Good!");
859 goodMeasure = true;
860 }
861 }
862 }
863 }
864
865 if (!goodMeasure) {
866 childWidthMeasureSpec = getRootMeasureSpec(desiredWindowWidth, lp.width);
867 childHeightMeasureSpec = getRootMeasureSpec(desiredWindowHeight, lp.height);
868 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
869 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800870
871 if (DBG) {
872 System.out.println("======================================");
873 System.out.println("performTraversals -- after measure");
874 host.debug();
875 }
876 }
877
878 if (attachInfo.mRecomputeGlobalAttributes) {
879 //Log.i(TAG, "Computing screen on!");
880 attachInfo.mRecomputeGlobalAttributes = false;
881 boolean oldVal = attachInfo.mKeepScreenOn;
882 attachInfo.mKeepScreenOn = false;
883 host.dispatchCollectViewAttributes(0);
884 if (attachInfo.mKeepScreenOn != oldVal) {
885 params = lp;
886 //Log.i(TAG, "Keep screen on changed: " + attachInfo.mKeepScreenOn);
887 }
888 }
889
890 if (mFirst || attachInfo.mViewVisibilityChanged) {
891 attachInfo.mViewVisibilityChanged = false;
892 int resizeMode = mSoftInputMode &
893 WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST;
894 // If we are in auto resize mode, then we need to determine
895 // what mode to use now.
896 if (resizeMode == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED) {
897 final int N = attachInfo.mScrollContainers.size();
898 for (int i=0; i<N; i++) {
899 if (attachInfo.mScrollContainers.get(i).isShown()) {
900 resizeMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE;
901 }
902 }
903 if (resizeMode == 0) {
904 resizeMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN;
905 }
906 if ((lp.softInputMode &
907 WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) != resizeMode) {
908 lp.softInputMode = (lp.softInputMode &
909 ~WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) |
910 resizeMode;
911 params = lp;
912 }
913 }
914 }
Romain Guy8506ab42009-06-11 17:35:47 -0700915
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800916 if (params != null && (host.mPrivateFlags & View.REQUEST_TRANSPARENT_REGIONS) != 0) {
917 if (!PixelFormat.formatHasAlpha(params.format)) {
918 params.format = PixelFormat.TRANSLUCENT;
919 }
920 }
921
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800922 boolean windowShouldResize = mLayoutRequested && windowSizeMayChange
Romain Guy2e4f4262010-04-06 11:07:52 -0700923 && ((mWidth != host.mMeasuredWidth || mHeight != host.mMeasuredHeight)
924 || (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT &&
925 frame.width() < desiredWindowWidth && frame.width() != mWidth)
926 || (lp.height == ViewGroup.LayoutParams.WRAP_CONTENT &&
927 frame.height() < desiredWindowHeight && frame.height() != mHeight));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800928
929 final boolean computesInternalInsets =
930 attachInfo.mTreeObserver.hasComputeInternalInsetsListeners();
Romain Guy812ccbe2010-06-01 14:07:24 -0700931
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800932 boolean insetsPending = false;
933 int relayoutResult = 0;
Romain Guy812ccbe2010-06-01 14:07:24 -0700934
935 if (mFirst || windowShouldResize || insetsChanged ||
936 viewVisibilityChanged || params != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800937
938 if (viewVisibility == View.VISIBLE) {
939 // If this window is giving internal insets to the window
940 // manager, and it is being added or changing its visibility,
941 // then we want to first give the window manager "fake"
942 // insets to cause it to effectively ignore the content of
943 // the window during layout. This avoids it briefly causing
944 // other windows to resize/move based on the raw frame of the
945 // window, waiting until we can finish laying out this window
946 // and get back to the window manager with the ultimately
947 // computed insets.
Romain Guy812ccbe2010-06-01 14:07:24 -0700948 insetsPending = computesInternalInsets && (mFirst || viewVisibilityChanged);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800949 }
950
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700951 if (mSurfaceHolder != null) {
952 mSurfaceHolder.mSurfaceLock.lock();
953 mDrawingAllowed = true;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700954 }
Romain Guy812ccbe2010-06-01 14:07:24 -0700955
Romain Guyc361da82010-10-25 15:29:10 -0700956 boolean hwInitialized = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800957 boolean contentInsetsChanged = false;
Romain Guy13922e02009-05-12 17:56:14 -0700958 boolean visibleInsetsChanged;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700959 boolean hadSurface = mSurface.isValid();
Romain Guy812ccbe2010-06-01 14:07:24 -0700960
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800961 try {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800962 int fl = 0;
963 if (params != null) {
964 fl = params.flags;
965 if (attachInfo.mKeepScreenOn) {
966 params.flags |= WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
967 }
968 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700969 if (DEBUG_LAYOUT) {
970 Log.i(TAG, "host=w:" + host.mMeasuredWidth + ", h:" +
971 host.mMeasuredHeight + ", params=" + params);
972 }
973 relayoutResult = relayoutWindow(params, viewVisibility, insetsPending);
974
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800975 if (params != null) {
976 params.flags = fl;
977 }
978
979 if (DEBUG_LAYOUT) Log.v(TAG, "relayout: frame=" + frame.toShortString()
980 + " content=" + mPendingContentInsets.toShortString()
981 + " visible=" + mPendingVisibleInsets.toShortString()
982 + " surface=" + mSurface);
Romain Guy8506ab42009-06-11 17:35:47 -0700983
Dianne Hackborn694f79b2010-03-17 19:44:59 -0700984 if (mPendingConfiguration.seq != 0) {
985 if (DEBUG_CONFIGURATION) Log.v(TAG, "Visible with new config: "
986 + mPendingConfiguration);
987 updateConfiguration(mPendingConfiguration, !mFirst);
988 mPendingConfiguration.seq = 0;
989 }
990
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800991 contentInsetsChanged = !mPendingContentInsets.equals(
992 mAttachInfo.mContentInsets);
993 visibleInsetsChanged = !mPendingVisibleInsets.equals(
994 mAttachInfo.mVisibleInsets);
995 if (contentInsetsChanged) {
996 mAttachInfo.mContentInsets.set(mPendingContentInsets);
997 host.fitSystemWindows(mAttachInfo.mContentInsets);
998 if (DEBUG_LAYOUT) Log.v(TAG, "Content insets changing to: "
999 + mAttachInfo.mContentInsets);
1000 }
1001 if (visibleInsetsChanged) {
1002 mAttachInfo.mVisibleInsets.set(mPendingVisibleInsets);
1003 if (DEBUG_LAYOUT) Log.v(TAG, "Visible insets changing to: "
1004 + mAttachInfo.mVisibleInsets);
1005 }
1006
1007 if (!hadSurface) {
1008 if (mSurface.isValid()) {
1009 // If we are creating a new surface, then we need to
1010 // completely redraw it. Also, when we get to the
1011 // point of drawing it we will hold off and schedule
1012 // a new traversal instead. This is so we can tell the
1013 // window manager about all of the windows being displayed
1014 // before actually drawing them, so it can display then
1015 // all at once.
1016 newSurface = true;
1017 fullRedrawNeeded = true;
Jack Palevich61a6e682009-10-09 17:37:50 -07001018 mPreviousTransparentRegion.setEmpty();
Romain Guy8506ab42009-06-11 17:35:47 -07001019
Romain Guyb051e892010-09-28 19:09:36 -07001020 if (mAttachInfo.mHardwareRenderer != null) {
Romain Guyc361da82010-10-25 15:29:10 -07001021 hwInitialized = mAttachInfo.mHardwareRenderer.initialize(mHolder);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001022 }
1023 }
1024 } else if (!mSurface.isValid()) {
1025 // If the surface has been removed, then reset the scroll
1026 // positions.
1027 mLastScrolledFocus = null;
1028 mScrollY = mCurScrollY = 0;
1029 if (mScroller != null) {
1030 mScroller.abortAnimation();
1031 }
Dianne Hackborn0f761d62010-11-30 22:06:10 -08001032 disposeResizeBitmap();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001033 }
1034 } catch (RemoteException e) {
1035 }
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001036
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001037 if (DEBUG_ORIENTATION) Log.v(
Jeff Brownc5ed5912010-07-14 18:48:53 -07001038 TAG, "Relayout returned: frame=" + frame + ", surface=" + mSurface);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001039
1040 attachInfo.mWindowLeft = frame.left;
1041 attachInfo.mWindowTop = frame.top;
1042
1043 // !!FIXME!! This next section handles the case where we did not get the
1044 // window size we asked for. We should avoid this by getting a maximum size from
1045 // the window session beforehand.
1046 mWidth = frame.width();
1047 mHeight = frame.height();
1048
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001049 if (mSurfaceHolder != null) {
1050 // The app owns the surface; tell it about what is going on.
1051 if (mSurface.isValid()) {
1052 // XXX .copyFrom() doesn't work!
1053 //mSurfaceHolder.mSurface.copyFrom(mSurface);
1054 mSurfaceHolder.mSurface = mSurface;
1055 }
1056 mSurfaceHolder.mSurfaceLock.unlock();
1057 if (mSurface.isValid()) {
1058 if (!hadSurface) {
1059 mSurfaceHolder.ungetCallbacks();
1060
1061 mIsCreating = true;
1062 mSurfaceHolderCallback.surfaceCreated(mSurfaceHolder);
1063 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
1064 if (callbacks != null) {
1065 for (SurfaceHolder.Callback c : callbacks) {
1066 c.surfaceCreated(mSurfaceHolder);
1067 }
1068 }
1069 surfaceChanged = true;
Romain Guyc361da82010-10-25 15:29:10 -07001070
1071 if (mAttachInfo.mHardwareRenderer != null) {
1072 // This will bail out early if already initialized
1073 mAttachInfo.mHardwareRenderer.initialize(mHolder);
1074 }
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001075 }
1076 if (surfaceChanged) {
1077 mSurfaceHolderCallback.surfaceChanged(mSurfaceHolder,
1078 lp.format, mWidth, mHeight);
1079 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
1080 if (callbacks != null) {
1081 for (SurfaceHolder.Callback c : callbacks) {
1082 c.surfaceChanged(mSurfaceHolder, lp.format,
1083 mWidth, mHeight);
1084 }
1085 }
1086 }
1087 mIsCreating = false;
1088 } else if (hadSurface) {
1089 mSurfaceHolder.ungetCallbacks();
1090 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
1091 mSurfaceHolderCallback.surfaceDestroyed(mSurfaceHolder);
1092 if (callbacks != null) {
1093 for (SurfaceHolder.Callback c : callbacks) {
1094 c.surfaceDestroyed(mSurfaceHolder);
1095 }
1096 }
1097 mSurfaceHolder.mSurfaceLock.lock();
1098 // Make surface invalid.
1099 //mSurfaceHolder.mSurface.copyFrom(mSurface);
1100 mSurfaceHolder.mSurface = new Surface();
1101 mSurfaceHolder.mSurfaceLock.unlock();
1102 }
1103 }
Romain Guy53389bd2010-09-07 17:16:32 -07001104
Romain Guyc361da82010-10-25 15:29:10 -07001105 if (hwInitialized || (windowShouldResize && mAttachInfo.mHardwareRenderer != null)) {
Romain Guyb051e892010-09-28 19:09:36 -07001106 mAttachInfo.mHardwareRenderer.setup(mWidth, mHeight);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001107 }
1108
1109 boolean focusChangedDueToTouchMode = ensureTouchModeLocally(
Romain Guy2d4cff62010-04-09 15:39:00 -07001110 (relayoutResult&WindowManagerImpl.RELAYOUT_IN_TOUCH_MODE) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001111 if (focusChangedDueToTouchMode || mWidth != host.mMeasuredWidth
1112 || mHeight != host.mMeasuredHeight || contentInsetsChanged) {
1113 childWidthMeasureSpec = getRootMeasureSpec(mWidth, lp.width);
1114 childHeightMeasureSpec = getRootMeasureSpec(mHeight, lp.height);
1115
1116 if (DEBUG_LAYOUT) Log.v(TAG, "Ooops, something changed! mWidth="
1117 + mWidth + " measuredWidth=" + host.mMeasuredWidth
1118 + " mHeight=" + mHeight
1119 + " measuredHeight" + host.mMeasuredHeight
1120 + " coveredInsetsChanged=" + contentInsetsChanged);
Romain Guy8506ab42009-06-11 17:35:47 -07001121
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001122 // Ask host how big it wants to be
1123 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
1124
1125 // Implementation of weights from WindowManager.LayoutParams
1126 // We just grow the dimensions as needed and re-measure if
1127 // needs be
1128 int width = host.mMeasuredWidth;
1129 int height = host.mMeasuredHeight;
1130 boolean measureAgain = false;
1131
1132 if (lp.horizontalWeight > 0.0f) {
1133 width += (int) ((mWidth - width) * lp.horizontalWeight);
1134 childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(width,
1135 MeasureSpec.EXACTLY);
1136 measureAgain = true;
1137 }
1138 if (lp.verticalWeight > 0.0f) {
1139 height += (int) ((mHeight - height) * lp.verticalWeight);
1140 childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(height,
1141 MeasureSpec.EXACTLY);
1142 measureAgain = true;
1143 }
1144
1145 if (measureAgain) {
1146 if (DEBUG_LAYOUT) Log.v(TAG,
1147 "And hey let's measure once more: width=" + width
1148 + " height=" + height);
1149 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
1150 }
1151
1152 mLayoutRequested = true;
1153 }
1154 }
1155
1156 final boolean didLayout = mLayoutRequested;
1157 boolean triggerGlobalLayoutListener = didLayout
1158 || attachInfo.mRecomputeGlobalAttributes;
1159 if (didLayout) {
1160 mLayoutRequested = false;
1161 mScrollMayChange = true;
1162 if (DEBUG_ORIENTATION || DEBUG_LAYOUT) Log.v(
Jeff Brownc5ed5912010-07-14 18:48:53 -07001163 TAG, "Laying out " + host + " to (" +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001164 host.mMeasuredWidth + ", " + host.mMeasuredHeight + ")");
Romain Guy13922e02009-05-12 17:56:14 -07001165 long startTime = 0L;
Romain Guy5429e1d2010-09-07 12:38:00 -07001166 if (ViewDebug.DEBUG_PROFILE_LAYOUT) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001167 startTime = SystemClock.elapsedRealtime();
1168 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001169 host.layout(0, 0, host.mMeasuredWidth, host.mMeasuredHeight);
1170
Romain Guy13922e02009-05-12 17:56:14 -07001171 if (Config.DEBUG && ViewDebug.consistencyCheckEnabled) {
1172 if (!host.dispatchConsistencyCheck(ViewDebug.CONSISTENCY_LAYOUT)) {
1173 throw new IllegalStateException("The view hierarchy is an inconsistent state,"
1174 + "please refer to the logs with the tag "
1175 + ViewDebug.CONSISTENCY_LOG_TAG + " for more infomation.");
1176 }
1177 }
1178
Romain Guy5429e1d2010-09-07 12:38:00 -07001179 if (ViewDebug.DEBUG_PROFILE_LAYOUT) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001180 EventLog.writeEvent(60001, SystemClock.elapsedRealtime() - startTime);
1181 }
1182
1183 // By this point all views have been sized and positionned
1184 // We can compute the transparent area
1185
1186 if ((host.mPrivateFlags & View.REQUEST_TRANSPARENT_REGIONS) != 0) {
1187 // start out transparent
1188 // TODO: AVOID THAT CALL BY CACHING THE RESULT?
1189 host.getLocationInWindow(mTmpLocation);
1190 mTransparentRegion.set(mTmpLocation[0], mTmpLocation[1],
1191 mTmpLocation[0] + host.mRight - host.mLeft,
1192 mTmpLocation[1] + host.mBottom - host.mTop);
1193
1194 host.gatherTransparentRegion(mTransparentRegion);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001195 if (mTranslator != null) {
1196 mTranslator.translateRegionInWindowToScreen(mTransparentRegion);
1197 }
1198
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001199 if (!mTransparentRegion.equals(mPreviousTransparentRegion)) {
1200 mPreviousTransparentRegion.set(mTransparentRegion);
1201 // reconfigure window manager
1202 try {
1203 sWindowSession.setTransparentRegion(mWindow, mTransparentRegion);
1204 } catch (RemoteException e) {
1205 }
1206 }
1207 }
1208
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001209 if (DBG) {
1210 System.out.println("======================================");
1211 System.out.println("performTraversals -- after setFrame");
1212 host.debug();
1213 }
1214 }
1215
1216 if (triggerGlobalLayoutListener) {
1217 attachInfo.mRecomputeGlobalAttributes = false;
1218 attachInfo.mTreeObserver.dispatchOnGlobalLayout();
1219 }
1220
1221 if (computesInternalInsets) {
1222 ViewTreeObserver.InternalInsetsInfo insets = attachInfo.mGivenInternalInsets;
1223 final Rect givenContent = attachInfo.mGivenInternalInsets.contentInsets;
1224 final Rect givenVisible = attachInfo.mGivenInternalInsets.visibleInsets;
1225 givenContent.left = givenContent.top = givenContent.right
1226 = givenContent.bottom = givenVisible.left = givenVisible.top
1227 = givenVisible.right = givenVisible.bottom = 0;
1228 attachInfo.mTreeObserver.dispatchOnComputeInternalInsets(insets);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001229 Rect contentInsets = insets.contentInsets;
1230 Rect visibleInsets = insets.visibleInsets;
1231 if (mTranslator != null) {
1232 contentInsets = mTranslator.getTranslatedContentInsets(contentInsets);
1233 visibleInsets = mTranslator.getTranslatedVisbileInsets(visibleInsets);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001234 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001235 if (insetsPending || !mLastGivenInsets.equals(insets)) {
1236 mLastGivenInsets.set(insets);
1237 try {
1238 sWindowSession.setInsets(mWindow, insets.mTouchableInsets,
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001239 contentInsets, visibleInsets);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001240 } catch (RemoteException e) {
1241 }
1242 }
1243 }
Romain Guy8506ab42009-06-11 17:35:47 -07001244
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001245 if (mFirst) {
1246 // handle first focus request
1247 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: mView.hasFocus()="
1248 + mView.hasFocus());
1249 if (mView != null) {
1250 if (!mView.hasFocus()) {
1251 mView.requestFocus(View.FOCUS_FORWARD);
1252 mFocusedView = mRealFocusedView = mView.findFocus();
1253 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: requested focused view="
1254 + mFocusedView);
1255 } else {
1256 mRealFocusedView = mView.findFocus();
1257 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: existing focused view="
1258 + mRealFocusedView);
1259 }
1260 }
1261 }
1262
1263 mFirst = false;
1264 mWillDrawSoon = false;
1265 mNewSurfaceNeeded = false;
1266 mViewVisibility = viewVisibility;
1267
1268 if (mAttachInfo.mHasWindowFocus) {
1269 final boolean imTarget = WindowManager.LayoutParams
1270 .mayUseInputMethod(mWindowAttributes.flags);
1271 if (imTarget != mLastWasImTarget) {
1272 mLastWasImTarget = imTarget;
1273 InputMethodManager imm = InputMethodManager.peekInstance();
1274 if (imm != null && imTarget) {
1275 imm.startGettingWindowFocus(mView);
1276 imm.onWindowFocus(mView, mView.findFocus(),
1277 mWindowAttributes.softInputMode,
1278 !mHasHadWindowFocus, mWindowAttributes.flags);
1279 }
1280 }
1281 }
Romain Guy8506ab42009-06-11 17:35:47 -07001282
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001283 boolean cancelDraw = attachInfo.mTreeObserver.dispatchOnPreDraw();
1284
1285 if (!cancelDraw && !newSurface) {
1286 mFullRedrawNeeded = false;
1287 draw(fullRedrawNeeded);
1288
1289 if ((relayoutResult&WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0
1290 || mReportNextDraw) {
1291 if (LOCAL_LOGV) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001292 Log.v(TAG, "FINISHED DRAWING: " + mWindowAttributes.getTitle());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001293 }
1294 mReportNextDraw = false;
Dianne Hackbornd76b67c2010-07-13 17:48:30 -07001295 if (mSurfaceHolder != null && mSurface.isValid()) {
1296 mSurfaceHolderCallback.surfaceRedrawNeeded(mSurfaceHolder);
1297 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
1298 if (callbacks != null) {
1299 for (SurfaceHolder.Callback c : callbacks) {
1300 if (c instanceof SurfaceHolder.Callback2) {
1301 ((SurfaceHolder.Callback2)c).surfaceRedrawNeeded(
1302 mSurfaceHolder);
1303 }
1304 }
1305 }
1306 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001307 try {
1308 sWindowSession.finishDrawing(mWindow);
1309 } catch (RemoteException e) {
1310 }
1311 }
1312 } else {
1313 // We were supposed to report when we are done drawing. Since we canceled the
1314 // draw, remember it here.
1315 if ((relayoutResult&WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0) {
1316 mReportNextDraw = true;
1317 }
1318 if (fullRedrawNeeded) {
1319 mFullRedrawNeeded = true;
1320 }
1321 // Try again
1322 scheduleTraversals();
1323 }
1324 }
1325
1326 public void requestTransparentRegion(View child) {
1327 // the test below should not fail unless someone is messing with us
1328 checkThread();
1329 if (mView == child) {
1330 mView.mPrivateFlags |= View.REQUEST_TRANSPARENT_REGIONS;
1331 // Need to make sure we re-evaluate the window attributes next
1332 // time around, to ensure the window has the correct format.
1333 mWindowAttributesChanged = true;
Mathias Agopian1bd80ad2010-11-04 17:13:39 -07001334 requestLayout();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001335 }
1336 }
1337
1338 /**
1339 * Figures out the measure spec for the root view in a window based on it's
1340 * layout params.
1341 *
1342 * @param windowSize
1343 * The available width or height of the window
1344 *
1345 * @param rootDimension
1346 * The layout params for one dimension (width or height) of the
1347 * window.
1348 *
1349 * @return The measure spec to use to measure the root view.
1350 */
1351 private int getRootMeasureSpec(int windowSize, int rootDimension) {
1352 int measureSpec;
1353 switch (rootDimension) {
1354
Romain Guy980a9382010-01-08 15:06:28 -08001355 case ViewGroup.LayoutParams.MATCH_PARENT:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001356 // Window can't resize. Force root view to be windowSize.
1357 measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.EXACTLY);
1358 break;
1359 case ViewGroup.LayoutParams.WRAP_CONTENT:
1360 // Window can resize. Set max size for root view.
1361 measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.AT_MOST);
1362 break;
1363 default:
1364 // Window wants to be an exact size. Force root view to be that size.
1365 measureSpec = MeasureSpec.makeMeasureSpec(rootDimension, MeasureSpec.EXACTLY);
1366 break;
1367 }
1368 return measureSpec;
1369 }
1370
Dianne Hackborn0f761d62010-11-30 22:06:10 -08001371 int mHardwareYOffset;
1372 int mResizeAlpha;
1373 final Paint mResizePaint = new Paint();
1374
1375 public void onHardwarePreDraw(Canvas canvas) {
1376 canvas.translate(0, -mHardwareYOffset);
1377 }
1378
1379 public void onHardwarePostDraw(Canvas canvas) {
1380 if (mResizeBitmap != null) {
1381 canvas.translate(0, mHardwareYOffset);
1382 mResizePaint.setAlpha(mResizeAlpha);
1383 canvas.drawBitmap(mResizeBitmap, 0, 0, mResizePaint);
1384 }
1385 }
1386
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001387 private void draw(boolean fullRedrawNeeded) {
1388 Surface surface = mSurface;
1389 if (surface == null || !surface.isValid()) {
1390 return;
1391 }
1392
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001393 if (!sFirstDrawComplete) {
1394 synchronized (sFirstDrawHandlers) {
1395 sFirstDrawComplete = true;
Romain Guy812ccbe2010-06-01 14:07:24 -07001396 final int count = sFirstDrawHandlers.size();
1397 for (int i = 0; i< count; i++) {
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001398 post(sFirstDrawHandlers.get(i));
1399 }
1400 }
1401 }
1402
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001403 scrollToRectOrFocus(null, false);
1404
1405 if (mAttachInfo.mViewScrollChanged) {
1406 mAttachInfo.mViewScrollChanged = false;
1407 mAttachInfo.mTreeObserver.dispatchOnScrollChanged();
1408 }
Romain Guy8506ab42009-06-11 17:35:47 -07001409
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001410 int yoff;
Dianne Hackborn0f761d62010-11-30 22:06:10 -08001411 boolean animating = mScroller != null && mScroller.computeScrollOffset();
1412 if (animating) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001413 yoff = mScroller.getCurrY();
1414 } else {
1415 yoff = mScrollY;
1416 }
1417 if (mCurScrollY != yoff) {
1418 mCurScrollY = yoff;
1419 fullRedrawNeeded = true;
1420 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001421 float appScale = mAttachInfo.mApplicationScale;
1422 boolean scalingRequired = mAttachInfo.mScalingRequired;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001423
Dianne Hackborn0f761d62010-11-30 22:06:10 -08001424 int resizeAlpha = 0;
1425 if (mResizeBitmap != null) {
1426 long deltaTime = SystemClock.uptimeMillis() - mResizeBitmapStartTime;
1427 if (deltaTime < mResizeBitmapDuration) {
1428 float amt = deltaTime/(float)mResizeBitmapDuration;
1429 amt = mResizeInterpolator.getInterpolation(amt);
1430 animating = true;
1431 resizeAlpha = 255 - (int)(amt*255);
1432 } else {
1433 disposeResizeBitmap();
1434 }
1435 }
1436
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001437 Rect dirty = mDirty;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001438 if (mSurfaceHolder != null) {
1439 // The app owns the surface, we won't draw.
1440 dirty.setEmpty();
Dianne Hackborn0f761d62010-11-30 22:06:10 -08001441 if (animating) {
1442 if (mScroller != null) {
1443 mScroller.abortAnimation();
1444 }
1445 disposeResizeBitmap();
1446 }
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001447 return;
1448 }
Romain Guy58ef7fb2010-09-13 12:52:37 -07001449
1450 if (fullRedrawNeeded) {
1451 mAttachInfo.mIgnoreDirtyState = true;
1452 dirty.union(0, 0, (int) (mWidth * appScale + 0.5f), (int) (mHeight * appScale + 0.5f));
1453 }
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001454
Romain Guyb051e892010-09-28 19:09:36 -07001455 if (mAttachInfo.mHardwareRenderer != null && mAttachInfo.mHardwareRenderer.isEnabled()) {
Romain Guyfd507262010-10-10 15:42:49 -07001456 if (!dirty.isEmpty() || mIsAnimating) {
Romain Guy101e2ae2010-10-11 12:41:21 -07001457 mIsAnimating = false;
Romain Guyfd507262010-10-10 15:42:49 -07001458 dirty.setEmpty();
Dianne Hackborn0f761d62010-11-30 22:06:10 -08001459 mHardwareYOffset = yoff;
1460 mResizeAlpha = resizeAlpha;
1461 mAttachInfo.mHardwareRenderer.draw(mView, mAttachInfo, this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001462 }
Romain Guy812ccbe2010-06-01 14:07:24 -07001463
Dianne Hackborn0f761d62010-11-30 22:06:10 -08001464 if (animating) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001465 mFullRedrawNeeded = true;
1466 scheduleTraversals();
1467 }
Romain Guy812ccbe2010-06-01 14:07:24 -07001468
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001469 return;
1470 }
1471
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001472 if (DEBUG_ORIENTATION || DEBUG_DRAW) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001473 Log.v(TAG, "Draw " + mView + "/"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001474 + mWindowAttributes.getTitle()
1475 + ": dirty={" + dirty.left + "," + dirty.top
1476 + "," + dirty.right + "," + dirty.bottom + "} surface="
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001477 + surface + " surface.isValid()=" + surface.isValid() + ", appScale:" +
1478 appScale + ", width=" + mWidth + ", height=" + mHeight);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001479 }
1480
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001481 if (!dirty.isEmpty() || mIsAnimating) {
1482 Canvas canvas;
1483 try {
1484 int left = dirty.left;
1485 int top = dirty.top;
1486 int right = dirty.right;
1487 int bottom = dirty.bottom;
1488 canvas = surface.lockCanvas(dirty);
Romain Guy5bcdff42009-05-14 21:27:18 -07001489
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001490 if (left != dirty.left || top != dirty.top || right != dirty.right ||
1491 bottom != dirty.bottom) {
1492 mAttachInfo.mIgnoreDirtyState = true;
1493 }
1494
1495 // TODO: Do this in native
1496 canvas.setDensity(mDensity);
1497 } catch (Surface.OutOfResourcesException e) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001498 Log.e(TAG, "OutOfResourcesException locking surface", e);
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001499 // TODO: we should ask the window manager to do something!
1500 // for now we just do nothing
1501 return;
1502 } catch (IllegalArgumentException e) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001503 Log.e(TAG, "IllegalArgumentException locking surface", e);
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001504 // TODO: we should ask the window manager to do something!
1505 // for now we just do nothing
1506 return;
Romain Guy5bcdff42009-05-14 21:27:18 -07001507 }
1508
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001509 try {
1510 if (!dirty.isEmpty() || mIsAnimating) {
1511 long startTime = 0L;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001512
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001513 if (DEBUG_ORIENTATION || DEBUG_DRAW) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001514 Log.v(TAG, "Surface " + surface + " drawing to bitmap w="
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001515 + canvas.getWidth() + ", h=" + canvas.getHeight());
1516 //canvas.drawARGB(255, 255, 0, 0);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001517 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001518
Romain Guy5429e1d2010-09-07 12:38:00 -07001519 if (ViewDebug.DEBUG_PROFILE_DRAWING) {
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001520 startTime = SystemClock.elapsedRealtime();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001521 }
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001522
1523 // If this bitmap's format includes an alpha channel, we
1524 // need to clear it before drawing so that the child will
1525 // properly re-composite its drawing on a transparent
1526 // background. This automatically respects the clip/dirty region
1527 // or
1528 // If we are applying an offset, we need to clear the area
1529 // where the offset doesn't appear to avoid having garbage
1530 // left in the blank areas.
1531 if (!canvas.isOpaque() || yoff != 0) {
1532 canvas.drawColor(0, PorterDuff.Mode.CLEAR);
1533 }
1534
1535 dirty.setEmpty();
1536 mIsAnimating = false;
1537 mAttachInfo.mDrawingTime = SystemClock.uptimeMillis();
1538 mView.mPrivateFlags |= View.DRAWN;
1539
1540 if (DEBUG_DRAW) {
1541 Context cxt = mView.getContext();
1542 Log.i(TAG, "Drawing: package:" + cxt.getPackageName() +
1543 ", metrics=" + cxt.getResources().getDisplayMetrics() +
1544 ", compatibilityInfo=" + cxt.getResources().getCompatibilityInfo());
1545 }
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001546 try {
1547 canvas.translate(0, -yoff);
1548 if (mTranslator != null) {
1549 mTranslator.translateCanvas(canvas);
1550 }
1551 canvas.setScreenDensity(scalingRequired
1552 ? DisplayMetrics.DENSITY_DEVICE : 0);
1553 mView.draw(canvas);
1554 } finally {
1555 mAttachInfo.mIgnoreDirtyState = false;
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001556 }
1557
1558 if (Config.DEBUG && ViewDebug.consistencyCheckEnabled) {
1559 mView.dispatchConsistencyCheck(ViewDebug.CONSISTENCY_DRAWING);
1560 }
1561
Romain Guy5429e1d2010-09-07 12:38:00 -07001562 if (SHOW_FPS || ViewDebug.DEBUG_SHOW_FPS) {
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001563 int now = (int)SystemClock.elapsedRealtime();
1564 if (sDrawTime != 0) {
1565 nativeShowFPS(canvas, now - sDrawTime);
1566 }
1567 sDrawTime = now;
1568 }
1569
Romain Guy5429e1d2010-09-07 12:38:00 -07001570 if (ViewDebug.DEBUG_PROFILE_DRAWING) {
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001571 EventLog.writeEvent(60000, SystemClock.elapsedRealtime() - startTime);
1572 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001573 }
1574
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001575 } finally {
1576 surface.unlockCanvasAndPost(canvas);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001577 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001578 }
1579
1580 if (LOCAL_LOGV) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001581 Log.v(TAG, "Surface " + surface + " unlockCanvasAndPost");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001582 }
Romain Guy8506ab42009-06-11 17:35:47 -07001583
Dianne Hackborn0f761d62010-11-30 22:06:10 -08001584 if (animating) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001585 mFullRedrawNeeded = true;
1586 scheduleTraversals();
1587 }
1588 }
1589
1590 boolean scrollToRectOrFocus(Rect rectangle, boolean immediate) {
1591 final View.AttachInfo attachInfo = mAttachInfo;
1592 final Rect ci = attachInfo.mContentInsets;
1593 final Rect vi = attachInfo.mVisibleInsets;
1594 int scrollY = 0;
1595 boolean handled = false;
Romain Guy8506ab42009-06-11 17:35:47 -07001596
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001597 if (vi.left > ci.left || vi.top > ci.top
1598 || vi.right > ci.right || vi.bottom > ci.bottom) {
1599 // We'll assume that we aren't going to change the scroll
1600 // offset, since we want to avoid that unless it is actually
1601 // going to make the focus visible... otherwise we scroll
1602 // all over the place.
1603 scrollY = mScrollY;
1604 // We can be called for two different situations: during a draw,
1605 // to update the scroll position if the focus has changed (in which
1606 // case 'rectangle' is null), or in response to a
1607 // requestChildRectangleOnScreen() call (in which case 'rectangle'
1608 // is non-null and we just want to scroll to whatever that
1609 // rectangle is).
1610 View focus = mRealFocusedView;
Romain Guye8b16522009-07-14 13:06:42 -07001611
1612 // When in touch mode, focus points to the previously focused view,
1613 // which may have been removed from the view hierarchy. The following
Joe Onoratob71193b2009-11-24 18:34:42 -05001614 // line checks whether the view is still in our hierarchy.
1615 if (focus == null || focus.mAttachInfo != mAttachInfo) {
Romain Guye8b16522009-07-14 13:06:42 -07001616 mRealFocusedView = null;
1617 return false;
1618 }
1619
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001620 if (focus != mLastScrolledFocus) {
1621 // If the focus has changed, then ignore any requests to scroll
1622 // to a rectangle; first we want to make sure the entire focus
1623 // view is visible.
1624 rectangle = null;
1625 }
1626 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Eval scroll: focus=" + focus
1627 + " rectangle=" + rectangle + " ci=" + ci
1628 + " vi=" + vi);
1629 if (focus == mLastScrolledFocus && !mScrollMayChange
1630 && rectangle == null) {
1631 // Optimization: if the focus hasn't changed since last
1632 // time, and no layout has happened, then just leave things
1633 // as they are.
1634 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Keeping scroll y="
1635 + mScrollY + " vi=" + vi.toShortString());
1636 } else if (focus != null) {
1637 // We need to determine if the currently focused view is
1638 // within the visible part of the window and, if not, apply
1639 // a pan so it can be seen.
1640 mLastScrolledFocus = focus;
1641 mScrollMayChange = false;
1642 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Need to scroll?");
1643 // Try to find the rectangle from the focus view.
1644 if (focus.getGlobalVisibleRect(mVisRect, null)) {
1645 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Root w="
1646 + mView.getWidth() + " h=" + mView.getHeight()
1647 + " ci=" + ci.toShortString()
1648 + " vi=" + vi.toShortString());
1649 if (rectangle == null) {
1650 focus.getFocusedRect(mTempRect);
1651 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Focus " + focus
1652 + ": focusRect=" + mTempRect.toShortString());
Dianne Hackborn1c6a8942010-03-23 16:34:20 -07001653 if (mView instanceof ViewGroup) {
1654 ((ViewGroup) mView).offsetDescendantRectToMyCoords(
1655 focus, mTempRect);
1656 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001657 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1658 "Focus in window: focusRect="
1659 + mTempRect.toShortString()
1660 + " visRect=" + mVisRect.toShortString());
1661 } else {
1662 mTempRect.set(rectangle);
1663 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1664 "Request scroll to rect: "
1665 + mTempRect.toShortString()
1666 + " visRect=" + mVisRect.toShortString());
1667 }
1668 if (mTempRect.intersect(mVisRect)) {
1669 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1670 "Focus window visible rect: "
1671 + mTempRect.toShortString());
1672 if (mTempRect.height() >
1673 (mView.getHeight()-vi.top-vi.bottom)) {
1674 // If the focus simply is not going to fit, then
1675 // best is probably just to leave things as-is.
1676 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1677 "Too tall; leaving scrollY=" + scrollY);
1678 } else if ((mTempRect.top-scrollY) < vi.top) {
1679 scrollY -= vi.top - (mTempRect.top-scrollY);
1680 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1681 "Top covered; scrollY=" + scrollY);
1682 } else if ((mTempRect.bottom-scrollY)
1683 > (mView.getHeight()-vi.bottom)) {
1684 scrollY += (mTempRect.bottom-scrollY)
1685 - (mView.getHeight()-vi.bottom);
1686 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1687 "Bottom covered; scrollY=" + scrollY);
1688 }
1689 handled = true;
1690 }
1691 }
1692 }
1693 }
Romain Guy8506ab42009-06-11 17:35:47 -07001694
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001695 if (scrollY != mScrollY) {
1696 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Pan scroll changed: old="
1697 + mScrollY + " , new=" + scrollY);
Dianne Hackborn0f761d62010-11-30 22:06:10 -08001698 if (!immediate && mResizeBitmap == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001699 if (mScroller == null) {
1700 mScroller = new Scroller(mView.getContext());
1701 }
1702 mScroller.startScroll(0, mScrollY, 0, scrollY-mScrollY);
1703 } else if (mScroller != null) {
1704 mScroller.abortAnimation();
1705 }
1706 mScrollY = scrollY;
1707 }
Romain Guy8506ab42009-06-11 17:35:47 -07001708
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001709 return handled;
1710 }
Romain Guy8506ab42009-06-11 17:35:47 -07001711
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001712 public void requestChildFocus(View child, View focused) {
1713 checkThread();
1714 if (mFocusedView != focused) {
1715 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(mFocusedView, focused);
1716 scheduleTraversals();
1717 }
1718 mFocusedView = mRealFocusedView = focused;
1719 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Request child focus: focus now "
1720 + mFocusedView);
1721 }
1722
1723 public void clearChildFocus(View child) {
1724 checkThread();
1725
1726 View oldFocus = mFocusedView;
1727
1728 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Clearing child focus");
1729 mFocusedView = mRealFocusedView = null;
1730 if (mView != null && !mView.hasFocus()) {
1731 // If a view gets the focus, the listener will be invoked from requestChildFocus()
1732 if (!mView.requestFocus(View.FOCUS_FORWARD)) {
1733 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
1734 }
1735 } else if (oldFocus != null) {
1736 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
1737 }
1738 }
1739
1740
1741 public void focusableViewAvailable(View v) {
1742 checkThread();
1743
1744 if (mView != null && !mView.hasFocus()) {
1745 v.requestFocus();
1746 } else {
1747 // the one case where will transfer focus away from the current one
1748 // is if the current view is a view group that prefers to give focus
1749 // to its children first AND the view is a descendant of it.
1750 mFocusedView = mView.findFocus();
1751 boolean descendantsHaveDibsOnFocus =
1752 (mFocusedView instanceof ViewGroup) &&
1753 (((ViewGroup) mFocusedView).getDescendantFocusability() ==
1754 ViewGroup.FOCUS_AFTER_DESCENDANTS);
1755 if (descendantsHaveDibsOnFocus && isViewDescendantOf(v, mFocusedView)) {
1756 // If a view gets the focus, the listener will be invoked from requestChildFocus()
1757 v.requestFocus();
1758 }
1759 }
1760 }
1761
1762 public void recomputeViewAttributes(View child) {
1763 checkThread();
1764 if (mView == child) {
1765 mAttachInfo.mRecomputeGlobalAttributes = true;
1766 if (!mWillDrawSoon) {
1767 scheduleTraversals();
1768 }
1769 }
1770 }
1771
1772 void dispatchDetachedFromWindow() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001773 if (mView != null) {
1774 mView.dispatchDetachedFromWindow();
1775 }
1776
1777 mView = null;
1778 mAttachInfo.mRootView = null;
Mathias Agopian5583dc62009-07-09 16:28:11 -07001779 mAttachInfo.mSurface = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001780
Romain Guy29d89972010-09-22 16:10:57 -07001781 destroyHardwareRenderer();
Romain Guy4caa4ed2010-08-25 14:46:24 -07001782
Dianne Hackborn0586a1b2009-09-06 21:08:27 -07001783 mSurface.release();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001784
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001785 if (mInputChannel != null) {
1786 if (mInputQueueCallback != null) {
1787 mInputQueueCallback.onInputQueueDestroyed(mInputQueue);
1788 mInputQueueCallback = null;
1789 } else {
1790 InputQueue.unregisterInputChannel(mInputChannel);
Jeff Brown46b9ac02010-04-22 18:58:52 -07001791 }
1792 }
1793
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001794 try {
1795 sWindowSession.remove(mWindow);
1796 } catch (RemoteException e) {
1797 }
Jeff Brown349703e2010-06-22 01:27:15 -07001798
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001799 // Dispose the input channel after removing the window so the Window Manager
1800 // doesn't interpret the input channel being closed as an abnormal termination.
1801 if (mInputChannel != null) {
1802 mInputChannel.dispose();
1803 mInputChannel = null;
Jeff Brown349703e2010-06-22 01:27:15 -07001804 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001805 }
Romain Guy8506ab42009-06-11 17:35:47 -07001806
Dianne Hackborn694f79b2010-03-17 19:44:59 -07001807 void updateConfiguration(Configuration config, boolean force) {
1808 if (DEBUG_CONFIGURATION) Log.v(TAG,
1809 "Applying new config to window "
1810 + mWindowAttributes.getTitle()
1811 + ": " + config);
1812 synchronized (sConfigCallbacks) {
1813 for (int i=sConfigCallbacks.size()-1; i>=0; i--) {
1814 sConfigCallbacks.get(i).onConfigurationChanged(config);
1815 }
1816 }
1817 if (mView != null) {
1818 // At this point the resources have been updated to
1819 // have the most recent config, whatever that is. Use
1820 // the on in them which may be newer.
1821 if (mView != null) {
1822 config = mView.getResources().getConfiguration();
1823 }
1824 if (force || mLastConfiguration.diff(config) != 0) {
1825 mLastConfiguration.setTo(config);
1826 mView.dispatchConfigurationChanged(config);
1827 }
1828 }
1829 }
1830
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001831 /**
1832 * Return true if child is an ancestor of parent, (or equal to the parent).
1833 */
1834 private static boolean isViewDescendantOf(View child, View parent) {
1835 if (child == parent) {
1836 return true;
1837 }
1838
1839 final ViewParent theParent = child.getParent();
1840 return (theParent instanceof ViewGroup) && isViewDescendantOf((View) theParent, parent);
1841 }
1842
Romain Guycdb86672010-03-18 18:54:50 -07001843 private static void forceLayout(View view) {
1844 view.forceLayout();
1845 if (view instanceof ViewGroup) {
1846 ViewGroup group = (ViewGroup) view;
1847 final int count = group.getChildCount();
1848 for (int i = 0; i < count; i++) {
1849 forceLayout(group.getChildAt(i));
1850 }
1851 }
1852 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001853
1854 public final static int DO_TRAVERSAL = 1000;
1855 public final static int DIE = 1001;
1856 public final static int RESIZED = 1002;
1857 public final static int RESIZED_REPORT = 1003;
1858 public final static int WINDOW_FOCUS_CHANGED = 1004;
1859 public final static int DISPATCH_KEY = 1005;
1860 public final static int DISPATCH_POINTER = 1006;
1861 public final static int DISPATCH_TRACKBALL = 1007;
1862 public final static int DISPATCH_APP_VISIBILITY = 1008;
1863 public final static int DISPATCH_GET_NEW_SURFACE = 1009;
1864 public final static int FINISHED_EVENT = 1010;
1865 public final static int DISPATCH_KEY_FROM_IME = 1011;
1866 public final static int FINISH_INPUT_CONNECTION = 1012;
1867 public final static int CHECK_FOCUS = 1013;
Dianne Hackbornffa42482009-09-23 22:20:11 -07001868 public final static int CLOSE_SYSTEM_DIALOGS = 1014;
Christopher Tatea53146c2010-09-07 11:57:52 -07001869 public final static int DISPATCH_DRAG_EVENT = 1015;
Chris Tate91e9bb32010-10-12 12:58:43 -07001870 public final static int DISPATCH_DRAG_LOCATION_EVENT = 1016;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001871
1872 @Override
1873 public void handleMessage(Message msg) {
1874 switch (msg.what) {
1875 case View.AttachInfo.INVALIDATE_MSG:
1876 ((View) msg.obj).invalidate();
1877 break;
1878 case View.AttachInfo.INVALIDATE_RECT_MSG:
1879 final View.AttachInfo.InvalidateInfo info = (View.AttachInfo.InvalidateInfo) msg.obj;
1880 info.target.invalidate(info.left, info.top, info.right, info.bottom);
1881 info.release();
1882 break;
1883 case DO_TRAVERSAL:
1884 if (mProfile) {
1885 Debug.startMethodTracing("ViewRoot");
1886 }
1887
1888 performTraversals();
1889
1890 if (mProfile) {
1891 Debug.stopMethodTracing();
1892 mProfile = false;
1893 }
1894 break;
1895 case FINISHED_EVENT:
1896 handleFinishedEvent(msg.arg1, msg.arg2 != 0);
1897 break;
1898 case DISPATCH_KEY:
Jeff Brown92ff1dd2010-08-11 16:16:06 -07001899 deliverKeyEvent((KeyEvent)msg.obj, msg.arg1 != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001900 break;
Jeff Brown3915bb82010-11-05 15:02:16 -07001901 case DISPATCH_POINTER:
1902 deliverPointerEvent((MotionEvent) msg.obj, msg.arg1 != 0);
1903 break;
1904 case DISPATCH_TRACKBALL:
1905 deliverTrackballEvent((MotionEvent) msg.obj, msg.arg1 != 0);
1906 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001907 case DISPATCH_APP_VISIBILITY:
1908 handleAppVisibility(msg.arg1 != 0);
1909 break;
1910 case DISPATCH_GET_NEW_SURFACE:
1911 handleGetNewSurface();
1912 break;
1913 case RESIZED:
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001914 ResizedInfo ri = (ResizedInfo)msg.obj;
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001915
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001916 if (mWinFrame.width() == msg.arg1 && mWinFrame.height() == msg.arg2
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001917 && mPendingContentInsets.equals(ri.coveredInsets)
Dianne Hackbornd49258f2010-03-26 00:44:29 -07001918 && mPendingVisibleInsets.equals(ri.visibleInsets)
1919 && ((ResizedInfo)msg.obj).newConfig == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001920 break;
1921 }
1922 // fall through...
1923 case RESIZED_REPORT:
1924 if (mAdded) {
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001925 Configuration config = ((ResizedInfo)msg.obj).newConfig;
1926 if (config != null) {
Dianne Hackborn694f79b2010-03-17 19:44:59 -07001927 updateConfiguration(config, false);
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001928 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001929 mWinFrame.left = 0;
1930 mWinFrame.right = msg.arg1;
1931 mWinFrame.top = 0;
1932 mWinFrame.bottom = msg.arg2;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001933 mPendingContentInsets.set(((ResizedInfo)msg.obj).coveredInsets);
1934 mPendingVisibleInsets.set(((ResizedInfo)msg.obj).visibleInsets);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001935 if (msg.what == RESIZED_REPORT) {
1936 mReportNextDraw = true;
1937 }
Romain Guycdb86672010-03-18 18:54:50 -07001938
1939 if (mView != null) {
1940 forceLayout(mView);
1941 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001942 requestLayout();
1943 }
1944 break;
1945 case WINDOW_FOCUS_CHANGED: {
1946 if (mAdded) {
1947 boolean hasWindowFocus = msg.arg1 != 0;
1948 mAttachInfo.mHasWindowFocus = hasWindowFocus;
1949 if (hasWindowFocus) {
1950 boolean inTouchMode = msg.arg2 != 0;
Romain Guy2d4cff62010-04-09 15:39:00 -07001951 ensureTouchModeLocally(inTouchMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001952
Romain Guyc361da82010-10-25 15:29:10 -07001953 if (mAttachInfo.mHardwareRenderer != null &&
1954 mSurface != null && mSurface.isValid()) {
Romain Guyb051e892010-09-28 19:09:36 -07001955 mAttachInfo.mHardwareRenderer.initializeIfNeeded(mWidth, mHeight,
1956 mAttachInfo, mHolder);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001957 }
1958 }
Romain Guy8506ab42009-06-11 17:35:47 -07001959
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001960 mLastWasImTarget = WindowManager.LayoutParams
1961 .mayUseInputMethod(mWindowAttributes.flags);
Romain Guy8506ab42009-06-11 17:35:47 -07001962
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001963 InputMethodManager imm = InputMethodManager.peekInstance();
1964 if (mView != null) {
1965 if (hasWindowFocus && imm != null && mLastWasImTarget) {
1966 imm.startGettingWindowFocus(mView);
1967 }
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07001968 mAttachInfo.mKeyDispatchState.reset();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001969 mView.dispatchWindowFocusChanged(hasWindowFocus);
1970 }
svetoslavganov75986cf2009-05-14 22:28:01 -07001971
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001972 // Note: must be done after the focus change callbacks,
1973 // so all of the view state is set up correctly.
1974 if (hasWindowFocus) {
1975 if (imm != null && mLastWasImTarget) {
1976 imm.onWindowFocus(mView, mView.findFocus(),
1977 mWindowAttributes.softInputMode,
1978 !mHasHadWindowFocus, mWindowAttributes.flags);
1979 }
1980 // Clear the forward bit. We can just do this directly, since
1981 // the window manager doesn't care about it.
1982 mWindowAttributes.softInputMode &=
1983 ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
1984 ((WindowManager.LayoutParams)mView.getLayoutParams())
1985 .softInputMode &=
1986 ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
1987 mHasHadWindowFocus = true;
1988 }
svetoslavganov75986cf2009-05-14 22:28:01 -07001989
1990 if (hasWindowFocus && mView != null) {
1991 sendAccessibilityEvents();
1992 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001993 }
1994 } break;
1995 case DIE:
Dianne Hackborn94d69142009-09-28 22:14:42 -07001996 doDie();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001997 break;
The Android Open Source Project10592532009-03-18 17:39:46 -07001998 case DISPATCH_KEY_FROM_IME: {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001999 if (LOCAL_LOGV) Log.v(
Jeff Brownc5ed5912010-07-14 18:48:53 -07002000 TAG, "Dispatching key "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002001 + msg.obj + " from IME to " + mView);
The Android Open Source Project10592532009-03-18 17:39:46 -07002002 KeyEvent event = (KeyEvent)msg.obj;
2003 if ((event.getFlags()&KeyEvent.FLAG_FROM_SYSTEM) != 0) {
2004 // The IME is trying to say this event is from the
2005 // system! Bad bad bad!
Romain Guy812ccbe2010-06-01 14:07:24 -07002006 event = KeyEvent.changeFlags(event, event.getFlags() & ~KeyEvent.FLAG_FROM_SYSTEM);
The Android Open Source Project10592532009-03-18 17:39:46 -07002007 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002008 deliverKeyEventPostIme((KeyEvent)msg.obj, false);
The Android Open Source Project10592532009-03-18 17:39:46 -07002009 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002010 case FINISH_INPUT_CONNECTION: {
2011 InputMethodManager imm = InputMethodManager.peekInstance();
2012 if (imm != null) {
2013 imm.reportFinishInputConnection((InputConnection)msg.obj);
2014 }
2015 } break;
2016 case CHECK_FOCUS: {
2017 InputMethodManager imm = InputMethodManager.peekInstance();
2018 if (imm != null) {
2019 imm.checkFocus();
2020 }
2021 } break;
Dianne Hackbornffa42482009-09-23 22:20:11 -07002022 case CLOSE_SYSTEM_DIALOGS: {
2023 if (mView != null) {
2024 mView.onCloseSystemDialogs((String)msg.obj);
2025 }
2026 } break;
Chris Tate91e9bb32010-10-12 12:58:43 -07002027 case DISPATCH_DRAG_EVENT:
2028 case DISPATCH_DRAG_LOCATION_EVENT: {
Christopher Tatea53146c2010-09-07 11:57:52 -07002029 handleDragEvent((DragEvent)msg.obj);
2030 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002031 }
2032 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002033
Jeff Brown3915bb82010-11-05 15:02:16 -07002034 private void startInputEvent(InputQueue.FinishedCallback finishedCallback) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07002035 if (mFinishedCallback != null) {
2036 Slog.w(TAG, "Received a new input event from the input queue but there is "
2037 + "already an unfinished input event in progress.");
2038 }
2039
2040 mFinishedCallback = finishedCallback;
2041 }
2042
Jeff Brown3915bb82010-11-05 15:02:16 -07002043 private void finishInputEvent(boolean handled) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07002044 if (LOCAL_LOGV) Log.v(TAG, "Telling window manager input event is finished");
Jeff Brown92ff1dd2010-08-11 16:16:06 -07002045
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002046 if (mFinishedCallback != null) {
Jeff Brown3915bb82010-11-05 15:02:16 -07002047 mFinishedCallback.finished(handled);
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002048 mFinishedCallback = null;
Jeff Brown92ff1dd2010-08-11 16:16:06 -07002049 } else {
Jeff Brown93ed4e32010-09-23 13:51:48 -07002050 Slog.w(TAG, "Attempted to tell the input queue that the current input event "
2051 + "is finished but there is no input event actually in progress.");
Jeff Brown46b9ac02010-04-22 18:58:52 -07002052 }
2053 }
2054
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002055 /**
2056 * Something in the current window tells us we need to change the touch mode. For
2057 * example, we are not in touch mode, and the user touches the screen.
2058 *
2059 * If the touch mode has changed, tell the window manager, and handle it locally.
2060 *
2061 * @param inTouchMode Whether we want to be in touch mode.
2062 * @return True if the touch mode changed and focus changed was changed as a result
2063 */
2064 boolean ensureTouchMode(boolean inTouchMode) {
2065 if (DBG) Log.d("touchmode", "ensureTouchMode(" + inTouchMode + "), current "
2066 + "touch mode is " + mAttachInfo.mInTouchMode);
2067 if (mAttachInfo.mInTouchMode == inTouchMode) return false;
2068
2069 // tell the window manager
2070 try {
2071 sWindowSession.setInTouchMode(inTouchMode);
2072 } catch (RemoteException e) {
2073 throw new RuntimeException(e);
2074 }
2075
2076 // handle the change
Romain Guy2d4cff62010-04-09 15:39:00 -07002077 return ensureTouchModeLocally(inTouchMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002078 }
2079
2080 /**
2081 * Ensure that the touch mode for this window is set, and if it is changing,
2082 * take the appropriate action.
2083 * @param inTouchMode Whether we want to be in touch mode.
2084 * @return True if the touch mode changed and focus changed was changed as a result
2085 */
Romain Guy2d4cff62010-04-09 15:39:00 -07002086 private boolean ensureTouchModeLocally(boolean inTouchMode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002087 if (DBG) Log.d("touchmode", "ensureTouchModeLocally(" + inTouchMode + "), current "
2088 + "touch mode is " + mAttachInfo.mInTouchMode);
2089
2090 if (mAttachInfo.mInTouchMode == inTouchMode) return false;
2091
2092 mAttachInfo.mInTouchMode = inTouchMode;
2093 mAttachInfo.mTreeObserver.dispatchOnTouchModeChanged(inTouchMode);
2094
Romain Guy2d4cff62010-04-09 15:39:00 -07002095 return (inTouchMode) ? enterTouchMode() : leaveTouchMode();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002096 }
2097
2098 private boolean enterTouchMode() {
2099 if (mView != null) {
2100 if (mView.hasFocus()) {
2101 // note: not relying on mFocusedView here because this could
2102 // be when the window is first being added, and mFocused isn't
2103 // set yet.
2104 final View focused = mView.findFocus();
2105 if (focused != null && !focused.isFocusableInTouchMode()) {
2106
2107 final ViewGroup ancestorToTakeFocus =
2108 findAncestorToTakeFocusInTouchMode(focused);
2109 if (ancestorToTakeFocus != null) {
2110 // there is an ancestor that wants focus after its descendants that
2111 // is focusable in touch mode.. give it focus
2112 return ancestorToTakeFocus.requestFocus();
2113 } else {
2114 // nothing appropriate to have focus in touch mode, clear it out
2115 mView.unFocus();
2116 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(focused, null);
2117 mFocusedView = null;
2118 return true;
2119 }
2120 }
2121 }
2122 }
2123 return false;
2124 }
2125
2126
2127 /**
2128 * Find an ancestor of focused that wants focus after its descendants and is
2129 * focusable in touch mode.
2130 * @param focused The currently focused view.
2131 * @return An appropriate view, or null if no such view exists.
2132 */
2133 private ViewGroup findAncestorToTakeFocusInTouchMode(View focused) {
2134 ViewParent parent = focused.getParent();
2135 while (parent instanceof ViewGroup) {
2136 final ViewGroup vgParent = (ViewGroup) parent;
2137 if (vgParent.getDescendantFocusability() == ViewGroup.FOCUS_AFTER_DESCENDANTS
2138 && vgParent.isFocusableInTouchMode()) {
2139 return vgParent;
2140 }
2141 if (vgParent.isRootNamespace()) {
2142 return null;
2143 } else {
2144 parent = vgParent.getParent();
2145 }
2146 }
2147 return null;
2148 }
2149
2150 private boolean leaveTouchMode() {
2151 if (mView != null) {
2152 if (mView.hasFocus()) {
2153 // i learned the hard way to not trust mFocusedView :)
2154 mFocusedView = mView.findFocus();
2155 if (!(mFocusedView instanceof ViewGroup)) {
2156 // some view has focus, let it keep it
2157 return false;
2158 } else if (((ViewGroup)mFocusedView).getDescendantFocusability() !=
2159 ViewGroup.FOCUS_AFTER_DESCENDANTS) {
2160 // some view group has focus, and doesn't prefer its children
2161 // over itself for focus, so let them keep it.
2162 return false;
2163 }
2164 }
2165
2166 // find the best view to give focus to in this brave new non-touch-mode
2167 // world
2168 final View focused = focusSearch(null, View.FOCUS_DOWN);
2169 if (focused != null) {
2170 return focused.requestFocus(View.FOCUS_DOWN);
2171 }
2172 }
2173 return false;
2174 }
2175
Jeff Brown3915bb82010-11-05 15:02:16 -07002176 private void deliverPointerEvent(MotionEvent event, boolean sendDone) {
2177 // If there is no view, then the event will not be handled.
2178 if (mView == null || !mAdded) {
2179 finishPointerEvent(event, sendDone, false);
2180 return;
2181 }
2182
2183 // Translate the pointer event for compatibility, if needed.
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002184 if (mTranslator != null) {
2185 mTranslator.translateEventInScreenToAppWindow(event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002186 }
2187
Jeff Brown3915bb82010-11-05 15:02:16 -07002188 // Enter touch mode on the down.
2189 boolean isDown = event.getAction() == MotionEvent.ACTION_DOWN;
2190 if (isDown) {
2191 ensureTouchMode(true);
2192 }
2193 if(Config.LOGV) {
2194 captureMotionLog("captureDispatchPointer", event);
2195 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002196
Jeff Brown3915bb82010-11-05 15:02:16 -07002197 // Offset the scroll position.
2198 if (mCurScrollY != 0) {
2199 event.offsetLocation(0, mCurScrollY);
2200 }
2201 if (MEASURE_LATENCY) {
2202 lt.sample("A Dispatching TouchEvents", System.nanoTime() - event.getEventTimeNano());
2203 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002204
Jeff Brown3915bb82010-11-05 15:02:16 -07002205 // Remember the touch position for possible drag-initiation.
2206 mLastTouchPoint.x = event.getRawX();
2207 mLastTouchPoint.y = event.getRawY();
2208
2209 // Dispatch touch to view hierarchy.
2210 boolean handled = mView.dispatchTouchEvent(event);
2211 if (MEASURE_LATENCY) {
2212 lt.sample("B Dispatched TouchEvents ", System.nanoTime() - event.getEventTimeNano());
2213 }
2214 if (handled) {
2215 finishPointerEvent(event, sendDone, true);
2216 return;
2217 }
2218
2219 // Apply edge slop and try again, if appropriate.
2220 final int edgeFlags = event.getEdgeFlags();
2221 if (edgeFlags != 0 && mView instanceof ViewGroup) {
2222 final int edgeSlop = mViewConfiguration.getScaledEdgeSlop();
2223 int direction = View.FOCUS_UP;
2224 int x = (int)event.getX();
2225 int y = (int)event.getY();
2226 final int[] deltas = new int[2];
2227
2228 if ((edgeFlags & MotionEvent.EDGE_TOP) != 0) {
2229 direction = View.FOCUS_DOWN;
2230 if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
2231 deltas[0] = edgeSlop;
2232 x += edgeSlop;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002233 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
Jeff Brown3915bb82010-11-05 15:02:16 -07002234 deltas[0] = -edgeSlop;
2235 x -= edgeSlop;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002236 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002237 } else if ((edgeFlags & MotionEvent.EDGE_BOTTOM) != 0) {
2238 direction = View.FOCUS_UP;
2239 if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
2240 deltas[0] = edgeSlop;
2241 x += edgeSlop;
2242 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
2243 deltas[0] = -edgeSlop;
2244 x -= edgeSlop;
2245 }
2246 } else if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
2247 direction = View.FOCUS_RIGHT;
2248 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
2249 direction = View.FOCUS_LEFT;
2250 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002251
Jeff Brown3915bb82010-11-05 15:02:16 -07002252 View nearest = FocusFinder.getInstance().findNearestTouchable(
2253 ((ViewGroup) mView), x, y, direction, deltas);
2254 if (nearest != null) {
2255 event.offsetLocation(deltas[0], deltas[1]);
2256 event.setEdgeFlags(0);
2257 if (mView.dispatchTouchEvent(event)) {
2258 finishPointerEvent(event, sendDone, true);
2259 return;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002260 }
2261 }
2262 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002263
2264 // Pointer event was unhandled.
2265 finishPointerEvent(event, sendDone, false);
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002266 }
2267
Jeff Brown3915bb82010-11-05 15:02:16 -07002268 private void finishPointerEvent(MotionEvent event, boolean sendDone, boolean handled) {
2269 event.recycle();
2270 if (sendDone) {
2271 finishInputEvent(handled);
2272 }
2273 if (LOCAL_LOGV || WATCH_POINTER) Log.i(TAG, "Done dispatching!");
2274 }
2275
2276 private void deliverTrackballEvent(MotionEvent event, boolean sendDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002277 if (DEBUG_TRACKBALL) Log.v(TAG, "Motion event:" + event);
2278
Jeff Brown3915bb82010-11-05 15:02:16 -07002279 // If there is no view, then the event will not be handled.
2280 if (mView == null || !mAdded) {
2281 finishTrackballEvent(event, sendDone, false);
2282 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002283 }
2284
Jeff Brown3915bb82010-11-05 15:02:16 -07002285 // Deliver the trackball event to the view.
2286 if (mView.dispatchTrackballEvent(event)) {
2287 // If we reach this, we delivered a trackball event to mView and
2288 // mView consumed it. Because we will not translate the trackball
2289 // event into a key event, touch mode will not exit, so we exit
2290 // touch mode here.
2291 ensureTouchMode(false);
2292
2293 finishTrackballEvent(event, sendDone, true);
2294 mLastTrackballTime = Integer.MIN_VALUE;
2295 return;
2296 }
2297
2298 // Translate the trackball event into DPAD keys and try to deliver those.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002299 final TrackballAxis x = mTrackballAxisX;
2300 final TrackballAxis y = mTrackballAxisY;
2301
2302 long curTime = SystemClock.uptimeMillis();
Jeff Brown3915bb82010-11-05 15:02:16 -07002303 if ((mLastTrackballTime + MAX_TRACKBALL_DELAY) < curTime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002304 // It has been too long since the last movement,
2305 // so restart at the beginning.
2306 x.reset(0);
2307 y.reset(0);
2308 mLastTrackballTime = curTime;
2309 }
2310
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002311 final int action = event.getAction();
2312 final int metastate = event.getMetaState();
2313 switch (action) {
2314 case MotionEvent.ACTION_DOWN:
2315 x.reset(2);
2316 y.reset(2);
2317 deliverKeyEvent(new KeyEvent(curTime, curTime,
2318 KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_CENTER,
2319 0, metastate), false);
2320 break;
2321 case MotionEvent.ACTION_UP:
2322 x.reset(2);
2323 y.reset(2);
2324 deliverKeyEvent(new KeyEvent(curTime, curTime,
2325 KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_CENTER,
2326 0, metastate), false);
2327 break;
2328 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002329
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002330 if (DEBUG_TRACKBALL) Log.v(TAG, "TB X=" + x.position + " step="
2331 + x.step + " dir=" + x.dir + " acc=" + x.acceleration
2332 + " move=" + event.getX()
2333 + " / Y=" + y.position + " step="
2334 + y.step + " dir=" + y.dir + " acc=" + y.acceleration
2335 + " move=" + event.getY());
2336 final float xOff = x.collect(event.getX(), event.getEventTime(), "X");
2337 final float yOff = y.collect(event.getY(), event.getEventTime(), "Y");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002338
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002339 // Generate DPAD events based on the trackball movement.
2340 // We pick the axis that has moved the most as the direction of
2341 // the DPAD. When we generate DPAD events for one axis, then the
2342 // other axis is reset -- we don't want to perform DPAD jumps due
2343 // to slight movements in the trackball when making major movements
2344 // along the other axis.
2345 int keycode = 0;
2346 int movement = 0;
2347 float accel = 1;
2348 if (xOff > yOff) {
2349 movement = x.generate((2/event.getXPrecision()));
2350 if (movement != 0) {
2351 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_RIGHT
2352 : KeyEvent.KEYCODE_DPAD_LEFT;
2353 accel = x.acceleration;
2354 y.reset(2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002355 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002356 } else if (yOff > 0) {
2357 movement = y.generate((2/event.getYPrecision()));
2358 if (movement != 0) {
2359 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_DOWN
2360 : KeyEvent.KEYCODE_DPAD_UP;
2361 accel = y.acceleration;
2362 x.reset(2);
2363 }
2364 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002365
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002366 if (keycode != 0) {
2367 if (movement < 0) movement = -movement;
2368 int accelMovement = (int)(movement * accel);
2369 if (DEBUG_TRACKBALL) Log.v(TAG, "Move: movement=" + movement
2370 + " accelMovement=" + accelMovement
2371 + " accel=" + accel);
2372 if (accelMovement > movement) {
2373 if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: "
2374 + keycode);
2375 movement--;
2376 deliverKeyEvent(new KeyEvent(curTime, curTime,
2377 KeyEvent.ACTION_MULTIPLE, keycode,
2378 accelMovement-movement, metastate), false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002379 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002380 while (movement > 0) {
2381 if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: "
2382 + keycode);
2383 movement--;
2384 curTime = SystemClock.uptimeMillis();
2385 deliverKeyEvent(new KeyEvent(curTime, curTime,
2386 KeyEvent.ACTION_DOWN, keycode, 0, event.getMetaState()), false);
2387 deliverKeyEvent(new KeyEvent(curTime, curTime,
2388 KeyEvent.ACTION_UP, keycode, 0, metastate), false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002389 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002390 mLastTrackballTime = curTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002391 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002392
2393 // Unfortunately we can't tell whether the application consumed the keys, so
2394 // we always consider the trackball event handled.
2395 finishTrackballEvent(event, sendDone, true);
2396 }
2397
2398 private void finishTrackballEvent(MotionEvent event, boolean sendDone, boolean handled) {
2399 event.recycle();
2400 if (sendDone) {
2401 finishInputEvent(handled);
2402 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002403 }
2404
2405 /**
2406 * @param keyCode The key code
2407 * @return True if the key is directional.
2408 */
2409 static boolean isDirectional(int keyCode) {
2410 switch (keyCode) {
2411 case KeyEvent.KEYCODE_DPAD_LEFT:
2412 case KeyEvent.KEYCODE_DPAD_RIGHT:
2413 case KeyEvent.KEYCODE_DPAD_UP:
2414 case KeyEvent.KEYCODE_DPAD_DOWN:
2415 return true;
2416 }
2417 return false;
2418 }
2419
2420 /**
2421 * Returns true if this key is a keyboard key.
2422 * @param keyEvent The key event.
2423 * @return whether this key is a keyboard key.
2424 */
2425 private static boolean isKeyboardKey(KeyEvent keyEvent) {
2426 final int convertedKey = keyEvent.getUnicodeChar();
2427 return convertedKey > 0;
2428 }
2429
2430
2431
2432 /**
2433 * See if the key event means we should leave touch mode (and leave touch
2434 * mode if so).
2435 * @param event The key event.
2436 * @return Whether this key event should be consumed (meaning the act of
2437 * leaving touch mode alone is considered the event).
2438 */
2439 private boolean checkForLeavingTouchModeAndConsume(KeyEvent event) {
Adam Powell51a6bee2010-03-15 14:07:28 -07002440 final int action = event.getAction();
2441 if (action != KeyEvent.ACTION_DOWN && action != KeyEvent.ACTION_MULTIPLE) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002442 return false;
2443 }
2444 if ((event.getFlags()&KeyEvent.FLAG_KEEP_TOUCH_MODE) != 0) {
2445 return false;
2446 }
2447
2448 // only relevant if we are in touch mode
2449 if (!mAttachInfo.mInTouchMode) {
2450 return false;
2451 }
2452
2453 // if something like an edit text has focus and the user is typing,
2454 // leave touch mode
2455 //
2456 // note: the condition of not being a keyboard key is kind of a hacky
2457 // approximation of whether we think the focused view will want the
2458 // key; if we knew for sure whether the focused view would consume
2459 // the event, that would be better.
2460 if (isKeyboardKey(event) && mView != null && mView.hasFocus()) {
2461 mFocusedView = mView.findFocus();
2462 if ((mFocusedView instanceof ViewGroup)
2463 && ((ViewGroup) mFocusedView).getDescendantFocusability() ==
2464 ViewGroup.FOCUS_AFTER_DESCENDANTS) {
2465 // something has focus, but is holding it weakly as a container
2466 return false;
2467 }
2468 if (ensureTouchMode(false)) {
2469 throw new IllegalStateException("should not have changed focus "
2470 + "when leaving touch mode while a view has focus.");
2471 }
2472 return false;
2473 }
2474
2475 if (isDirectional(event.getKeyCode())) {
2476 // no view has focus, so we leave touch mode (and find something
2477 // to give focus to). the event is consumed if we were able to
2478 // find something to give focus to.
2479 return ensureTouchMode(false);
2480 }
2481 return false;
2482 }
2483
2484 /**
Romain Guy8506ab42009-06-11 17:35:47 -07002485 * log motion events
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002486 */
2487 private static void captureMotionLog(String subTag, MotionEvent ev) {
Romain Guy8506ab42009-06-11 17:35:47 -07002488 //check dynamic switch
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002489 if (ev == null ||
2490 SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_EVENT, 0) == 0) {
2491 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002492 }
Romain Guy8506ab42009-06-11 17:35:47 -07002493
2494 StringBuilder sb = new StringBuilder(subTag + ": ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002495 sb.append(ev.getDownTime()).append(',');
2496 sb.append(ev.getEventTime()).append(',');
2497 sb.append(ev.getAction()).append(',');
Romain Guy8506ab42009-06-11 17:35:47 -07002498 sb.append(ev.getX()).append(',');
2499 sb.append(ev.getY()).append(',');
2500 sb.append(ev.getPressure()).append(',');
2501 sb.append(ev.getSize()).append(',');
2502 sb.append(ev.getMetaState()).append(',');
2503 sb.append(ev.getXPrecision()).append(',');
2504 sb.append(ev.getYPrecision()).append(',');
2505 sb.append(ev.getDeviceId()).append(',');
2506 sb.append(ev.getEdgeFlags());
2507 Log.d(TAG, sb.toString());
2508 }
2509 /**
2510 * log motion events
2511 */
2512 private static void captureKeyLog(String subTag, KeyEvent ev) {
2513 //check dynamic switch
2514 if (ev == null ||
2515 SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_EVENT, 0) == 0) {
2516 return;
2517 }
2518 StringBuilder sb = new StringBuilder(subTag + ": ");
2519 sb.append(ev.getDownTime()).append(',');
2520 sb.append(ev.getEventTime()).append(',');
2521 sb.append(ev.getAction()).append(',');
2522 sb.append(ev.getKeyCode()).append(',');
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002523 sb.append(ev.getRepeatCount()).append(',');
2524 sb.append(ev.getMetaState()).append(',');
2525 sb.append(ev.getDeviceId()).append(',');
2526 sb.append(ev.getScanCode());
Romain Guy8506ab42009-06-11 17:35:47 -07002527 Log.d(TAG, sb.toString());
2528 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002529
2530 int enqueuePendingEvent(Object event, boolean sendDone) {
2531 int seq = mPendingEventSeq+1;
2532 if (seq < 0) seq = 0;
2533 mPendingEventSeq = seq;
2534 mPendingEvents.put(seq, event);
2535 return sendDone ? seq : -seq;
2536 }
2537
2538 Object retrievePendingEvent(int seq) {
2539 if (seq < 0) seq = -seq;
2540 Object event = mPendingEvents.get(seq);
2541 if (event != null) {
2542 mPendingEvents.remove(seq);
2543 }
2544 return event;
2545 }
Romain Guy8506ab42009-06-11 17:35:47 -07002546
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002547 private void deliverKeyEvent(KeyEvent event, boolean sendDone) {
Jeff Brown3915bb82010-11-05 15:02:16 -07002548 // If there is no view, then the event will not be handled.
2549 if (mView == null || !mAdded) {
2550 finishKeyEvent(event, sendDone, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002551 return;
2552 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002553
2554 if (LOCAL_LOGV) Log.v(TAG, "Dispatching key " + event + " to " + mView);
2555
2556 // Perform predispatching before the IME.
2557 if (mView.dispatchKeyEventPreIme(event)) {
2558 finishKeyEvent(event, sendDone, true);
2559 return;
2560 }
2561
2562 // Dispatch to the IME before propagating down the view hierarchy.
2563 // The IME will eventually call back into handleFinishedEvent.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002564 if (mLastWasImTarget) {
2565 InputMethodManager imm = InputMethodManager.peekInstance();
Jeff Brown3915bb82010-11-05 15:02:16 -07002566 if (imm != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002567 int seq = enqueuePendingEvent(event, sendDone);
2568 if (DEBUG_IMF) Log.v(TAG, "Sending key event to IME: seq="
2569 + seq + " event=" + event);
Jeff Brown3915bb82010-11-05 15:02:16 -07002570 imm.dispatchKeyEvent(mView.getContext(), seq, event, mInputMethodCallback);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002571 return;
2572 }
2573 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002574
2575 // Not dispatching to IME, continue with post IME actions.
2576 deliverKeyEventPostIme(event, sendDone);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002577 }
2578
Jeff Brown3915bb82010-11-05 15:02:16 -07002579 private void handleFinishedEvent(int seq, boolean handled) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002580 final KeyEvent event = (KeyEvent)retrievePendingEvent(seq);
2581 if (DEBUG_IMF) Log.v(TAG, "IME finished event: seq=" + seq
2582 + " handled=" + handled + " event=" + event);
2583 if (event != null) {
2584 final boolean sendDone = seq >= 0;
Jeff Brown3915bb82010-11-05 15:02:16 -07002585 if (handled) {
2586 finishKeyEvent(event, sendDone, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002587 } else {
Jeff Brown3915bb82010-11-05 15:02:16 -07002588 deliverKeyEventPostIme(event, sendDone);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002589 }
2590 }
2591 }
Romain Guy8506ab42009-06-11 17:35:47 -07002592
Jeff Brown3915bb82010-11-05 15:02:16 -07002593 private void deliverKeyEventPostIme(KeyEvent event, boolean sendDone) {
2594 // If the view went away, then the event will not be handled.
2595 if (mView == null || !mAdded) {
2596 finishKeyEvent(event, sendDone, false);
2597 return;
2598 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002599
Jeff Brown3915bb82010-11-05 15:02:16 -07002600 // If the key's purpose is to exit touch mode then we consume it and consider it handled.
2601 if (checkForLeavingTouchModeAndConsume(event)) {
2602 finishKeyEvent(event, sendDone, true);
2603 return;
2604 }
Romain Guy8506ab42009-06-11 17:35:47 -07002605
Jeff Brown3915bb82010-11-05 15:02:16 -07002606 if (Config.LOGV) {
2607 captureKeyLog("captureDispatchKeyEvent", event);
2608 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002609
Jeff Brown3915bb82010-11-05 15:02:16 -07002610 // Deliver the key to the view hierarchy.
2611 if (mView.dispatchKeyEvent(event)) {
2612 finishKeyEvent(event, sendDone, true);
2613 return;
2614 }
Joe Onorato86f67862010-11-05 18:57:34 -07002615
Jeff Brown3915bb82010-11-05 15:02:16 -07002616 // Apply the fallback event policy.
2617 if (mFallbackEventHandler.dispatchKeyEvent(event)) {
2618 finishKeyEvent(event, sendDone, true);
2619 return;
2620 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002621
Jeff Brown3915bb82010-11-05 15:02:16 -07002622 // Handle automatic focus changes.
2623 if (event.getAction() == KeyEvent.ACTION_DOWN) {
2624 int direction = 0;
2625 switch (event.getKeyCode()) {
2626 case KeyEvent.KEYCODE_DPAD_LEFT:
2627 direction = View.FOCUS_LEFT;
2628 break;
2629 case KeyEvent.KEYCODE_DPAD_RIGHT:
2630 direction = View.FOCUS_RIGHT;
2631 break;
2632 case KeyEvent.KEYCODE_DPAD_UP:
2633 direction = View.FOCUS_UP;
2634 break;
2635 case KeyEvent.KEYCODE_DPAD_DOWN:
2636 direction = View.FOCUS_DOWN;
2637 break;
2638 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002639
Jeff Brown3915bb82010-11-05 15:02:16 -07002640 if (direction != 0) {
2641 View focused = mView != null ? mView.findFocus() : null;
2642 if (focused != null) {
2643 View v = focused.focusSearch(direction);
2644 if (v != null && v != focused) {
2645 // do the math the get the interesting rect
2646 // of previous focused into the coord system of
2647 // newly focused view
2648 focused.getFocusedRect(mTempRect);
2649 if (mView instanceof ViewGroup) {
2650 ((ViewGroup) mView).offsetDescendantRectToMyCoords(
2651 focused, mTempRect);
2652 ((ViewGroup) mView).offsetRectIntoDescendantCoords(
2653 v, mTempRect);
2654 }
2655 if (v.requestFocus(direction, mTempRect)) {
2656 playSoundEffect(
2657 SoundEffectConstants.getContantForFocusDirection(direction));
2658 finishKeyEvent(event, sendDone, true);
2659 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002660 }
2661 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002662
2663 // Give the focused view a last chance to handle the dpad key.
2664 if (mView.dispatchUnhandledMove(focused, direction)) {
2665 finishKeyEvent(event, sendDone, true);
2666 return;
2667 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002668 }
2669 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002670 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002671
Jeff Brown3915bb82010-11-05 15:02:16 -07002672 // Key was unhandled.
2673 finishKeyEvent(event, sendDone, false);
2674 }
2675
2676 private void finishKeyEvent(KeyEvent event, boolean sendDone, boolean handled) {
2677 if (sendDone) {
2678 finishInputEvent(handled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002679 }
2680 }
2681
Christopher Tatea53146c2010-09-07 11:57:52 -07002682 /* drag/drop */
2683 private void handleDragEvent(DragEvent event) {
2684 // From the root, only drag start/end/location are dispatched. entered/exited
2685 // are determined and dispatched by the viewgroup hierarchy, who then report
2686 // that back here for ultimate reporting back to the framework.
2687 if (mView != null && mAdded) {
2688 final int what = event.mAction;
2689
2690 if (what == DragEvent.ACTION_DRAG_EXITED) {
2691 // A direct EXITED event means that the window manager knows we've just crossed
2692 // a window boundary, so the current drag target within this one must have
2693 // just been exited. Send it the usual notifications and then we're done
2694 // for now.
Chris Tate9d1ab882010-11-02 15:55:39 -07002695 mView.dispatchDragEvent(event);
Christopher Tatea53146c2010-09-07 11:57:52 -07002696 } else {
2697 // Cache the drag description when the operation starts, then fill it in
2698 // on subsequent calls as a convenience
2699 if (what == DragEvent.ACTION_DRAG_STARTED) {
Chris Tate9d1ab882010-11-02 15:55:39 -07002700 mCurrentDragView = null; // Start the current-recipient tracking
Christopher Tatea53146c2010-09-07 11:57:52 -07002701 mDragDescription = event.mClipDescription;
2702 } else {
2703 event.mClipDescription = mDragDescription;
2704 }
2705
2706 // For events with a [screen] location, translate into window coordinates
2707 if ((what == DragEvent.ACTION_DRAG_LOCATION) || (what == DragEvent.ACTION_DROP)) {
2708 mDragPoint.set(event.mX, event.mY);
2709 if (mTranslator != null) {
2710 mTranslator.translatePointInScreenToAppWindow(mDragPoint);
2711 }
2712
2713 if (mCurScrollY != 0) {
2714 mDragPoint.offset(0, mCurScrollY);
2715 }
2716
2717 event.mX = mDragPoint.x;
2718 event.mY = mDragPoint.y;
2719 }
2720
2721 // Remember who the current drag target is pre-dispatch
2722 final View prevDragView = mCurrentDragView;
2723
2724 // Now dispatch the drag/drop event
Chris Tated4533f12010-10-19 15:15:08 -07002725 boolean result = mView.dispatchDragEvent(event);
Christopher Tatea53146c2010-09-07 11:57:52 -07002726
2727 // If we changed apparent drag target, tell the OS about it
2728 if (prevDragView != mCurrentDragView) {
2729 try {
2730 if (prevDragView != null) {
2731 sWindowSession.dragRecipientExited(mWindow);
2732 }
2733 if (mCurrentDragView != null) {
2734 sWindowSession.dragRecipientEntered(mWindow);
2735 }
2736 } catch (RemoteException e) {
2737 Slog.e(TAG, "Unable to note drag target change");
2738 }
Christopher Tatea53146c2010-09-07 11:57:52 -07002739 }
Chris Tated4533f12010-10-19 15:15:08 -07002740
2741 // Report the drop result if necessary
2742 if (what == DragEvent.ACTION_DROP) {
2743 try {
2744 Log.i(TAG, "Reporting drop result: " + result);
2745 sWindowSession.reportDropResult(mWindow, result);
2746 } catch (RemoteException e) {
2747 Log.e(TAG, "Unable to report drop result");
2748 }
2749 }
Christopher Tatea53146c2010-09-07 11:57:52 -07002750 }
2751 }
2752 event.recycle();
2753 }
2754
Christopher Tate2c095f32010-10-04 14:13:40 -07002755 public void getLastTouchPoint(Point outLocation) {
2756 outLocation.x = (int) mLastTouchPoint.x;
2757 outLocation.y = (int) mLastTouchPoint.y;
2758 }
2759
Chris Tate9d1ab882010-11-02 15:55:39 -07002760 public void setDragFocus(View newDragTarget) {
Christopher Tatea53146c2010-09-07 11:57:52 -07002761 if (mCurrentDragView != newDragTarget) {
Chris Tate048691c2010-10-12 17:39:18 -07002762 mCurrentDragView = newDragTarget;
Christopher Tatea53146c2010-09-07 11:57:52 -07002763 }
Christopher Tatea53146c2010-09-07 11:57:52 -07002764 }
2765
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002766 private AudioManager getAudioManager() {
2767 if (mView == null) {
2768 throw new IllegalStateException("getAudioManager called when there is no mView");
2769 }
2770 if (mAudioManager == null) {
2771 mAudioManager = (AudioManager) mView.getContext().getSystemService(Context.AUDIO_SERVICE);
2772 }
2773 return mAudioManager;
2774 }
2775
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002776 private int relayoutWindow(WindowManager.LayoutParams params, int viewVisibility,
2777 boolean insetsPending) throws RemoteException {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002778
2779 float appScale = mAttachInfo.mApplicationScale;
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002780 boolean restore = false;
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002781 if (params != null && mTranslator != null) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07002782 restore = true;
2783 params.backup();
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002784 mTranslator.translateWindowLayout(params);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002785 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002786 if (params != null) {
2787 if (DBG) Log.d(TAG, "WindowLayout in layoutWindow:" + params);
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002788 }
Dianne Hackborn694f79b2010-03-17 19:44:59 -07002789 mPendingConfiguration.seq = 0;
Dianne Hackbornf123e492010-09-24 11:16:23 -07002790 //Log.d(TAG, ">>>>>> CALLING relayout");
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002791 int relayoutResult = sWindowSession.relayout(
2792 mWindow, params,
Mitsuru Oshima61324e52009-07-21 15:40:36 -07002793 (int) (mView.mMeasuredWidth * appScale + 0.5f),
2794 (int) (mView.mMeasuredHeight * appScale + 0.5f),
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002795 viewVisibility, insetsPending, mWinFrame,
Dianne Hackborn694f79b2010-03-17 19:44:59 -07002796 mPendingContentInsets, mPendingVisibleInsets,
2797 mPendingConfiguration, mSurface);
Dianne Hackbornf123e492010-09-24 11:16:23 -07002798 //Log.d(TAG, "<<<<<< BACK FROM relayout");
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002799 if (restore) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07002800 params.restore();
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002801 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002802
2803 if (mTranslator != null) {
2804 mTranslator.translateRectInScreenToAppWinFrame(mWinFrame);
2805 mTranslator.translateRectInScreenToAppWindow(mPendingContentInsets);
2806 mTranslator.translateRectInScreenToAppWindow(mPendingVisibleInsets);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002807 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002808 return relayoutResult;
2809 }
Romain Guy8506ab42009-06-11 17:35:47 -07002810
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002811 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002812 * {@inheritDoc}
2813 */
2814 public void playSoundEffect(int effectId) {
2815 checkThread();
2816
Jean-Michel Trivi13b18fd2010-05-05 09:18:15 -07002817 try {
2818 final AudioManager audioManager = getAudioManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002819
Jean-Michel Trivi13b18fd2010-05-05 09:18:15 -07002820 switch (effectId) {
2821 case SoundEffectConstants.CLICK:
2822 audioManager.playSoundEffect(AudioManager.FX_KEY_CLICK);
2823 return;
2824 case SoundEffectConstants.NAVIGATION_DOWN:
2825 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_DOWN);
2826 return;
2827 case SoundEffectConstants.NAVIGATION_LEFT:
2828 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_LEFT);
2829 return;
2830 case SoundEffectConstants.NAVIGATION_RIGHT:
2831 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_RIGHT);
2832 return;
2833 case SoundEffectConstants.NAVIGATION_UP:
2834 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_UP);
2835 return;
2836 default:
2837 throw new IllegalArgumentException("unknown effect id " + effectId +
2838 " not defined in " + SoundEffectConstants.class.getCanonicalName());
2839 }
2840 } catch (IllegalStateException e) {
2841 // Exception thrown by getAudioManager() when mView is null
2842 Log.e(TAG, "FATAL EXCEPTION when attempting to play sound effect: " + e);
2843 e.printStackTrace();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002844 }
2845 }
2846
2847 /**
2848 * {@inheritDoc}
2849 */
2850 public boolean performHapticFeedback(int effectId, boolean always) {
2851 try {
2852 return sWindowSession.performHapticFeedback(mWindow, effectId, always);
2853 } catch (RemoteException e) {
2854 return false;
2855 }
2856 }
2857
2858 /**
2859 * {@inheritDoc}
2860 */
2861 public View focusSearch(View focused, int direction) {
2862 checkThread();
2863 if (!(mView instanceof ViewGroup)) {
2864 return null;
2865 }
2866 return FocusFinder.getInstance().findNextFocus((ViewGroup) mView, focused, direction);
2867 }
2868
2869 public void debug() {
2870 mView.debug();
2871 }
2872
2873 public void die(boolean immediate) {
Dianne Hackborn94d69142009-09-28 22:14:42 -07002874 if (immediate) {
2875 doDie();
2876 } else {
2877 sendEmptyMessage(DIE);
2878 }
2879 }
2880
2881 void doDie() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002882 checkThread();
Jeff Brownb75fa302010-07-15 23:47:29 -07002883 if (LOCAL_LOGV) Log.v(TAG, "DIE in " + this + " of " + mSurface);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002884 synchronized (this) {
2885 if (mAdded && !mFirst) {
Romain Guy29d89972010-09-22 16:10:57 -07002886 destroyHardwareRenderer();
2887
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002888 int viewVisibility = mView.getVisibility();
2889 boolean viewVisibilityChanged = mViewVisibility != viewVisibility;
2890 if (mWindowAttributesChanged || viewVisibilityChanged) {
2891 // If layout params have been changed, first give them
2892 // to the window manager to make sure it has the correct
2893 // animation info.
2894 try {
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002895 if ((relayoutWindow(mWindowAttributes, viewVisibility, false)
2896 & WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002897 sWindowSession.finishDrawing(mWindow);
2898 }
2899 } catch (RemoteException e) {
2900 }
2901 }
2902
Dianne Hackborn0586a1b2009-09-06 21:08:27 -07002903 mSurface.release();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002904 }
2905 if (mAdded) {
2906 mAdded = false;
Dianne Hackborn94d69142009-09-28 22:14:42 -07002907 dispatchDetachedFromWindow();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002908 }
2909 }
2910 }
2911
Romain Guy29d89972010-09-22 16:10:57 -07002912 private void destroyHardwareRenderer() {
Romain Guyb051e892010-09-28 19:09:36 -07002913 if (mAttachInfo.mHardwareRenderer != null) {
2914 mAttachInfo.mHardwareRenderer.destroy(true);
2915 mAttachInfo.mHardwareRenderer = null;
Romain Guy29d89972010-09-22 16:10:57 -07002916 mAttachInfo.mHardwareAccelerated = false;
2917 }
2918 }
2919
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002920 public void dispatchFinishedEvent(int seq, boolean handled) {
2921 Message msg = obtainMessage(FINISHED_EVENT);
2922 msg.arg1 = seq;
2923 msg.arg2 = handled ? 1 : 0;
2924 sendMessage(msg);
2925 }
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002926
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002927 public void dispatchResized(int w, int h, Rect coveredInsets,
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002928 Rect visibleInsets, boolean reportDraw, Configuration newConfig) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002929 if (DEBUG_LAYOUT) Log.v(TAG, "Resizing " + this + ": w=" + w
2930 + " h=" + h + " coveredInsets=" + coveredInsets.toShortString()
2931 + " visibleInsets=" + visibleInsets.toShortString()
2932 + " reportDraw=" + reportDraw);
2933 Message msg = obtainMessage(reportDraw ? RESIZED_REPORT :RESIZED);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002934 if (mTranslator != null) {
2935 mTranslator.translateRectInScreenToAppWindow(coveredInsets);
2936 mTranslator.translateRectInScreenToAppWindow(visibleInsets);
2937 w *= mTranslator.applicationInvertedScale;
2938 h *= mTranslator.applicationInvertedScale;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002939 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002940 msg.arg1 = w;
2941 msg.arg2 = h;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002942 ResizedInfo ri = new ResizedInfo();
2943 ri.coveredInsets = new Rect(coveredInsets);
2944 ri.visibleInsets = new Rect(visibleInsets);
2945 ri.newConfig = newConfig;
2946 msg.obj = ri;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002947 sendMessage(msg);
2948 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002949
Jeff Brown3915bb82010-11-05 15:02:16 -07002950 private InputQueue.FinishedCallback mFinishedCallback;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002951
2952 private final InputHandler mInputHandler = new InputHandler() {
Jeff Brown3915bb82010-11-05 15:02:16 -07002953 public void handleKey(KeyEvent event, InputQueue.FinishedCallback finishedCallback) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07002954 startInputEvent(finishedCallback);
Jeff Brown92ff1dd2010-08-11 16:16:06 -07002955 dispatchKey(event, true);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002956 }
2957
Jeff Brown3915bb82010-11-05 15:02:16 -07002958 public void handleMotion(MotionEvent event, InputQueue.FinishedCallback finishedCallback) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07002959 startInputEvent(finishedCallback);
2960 dispatchMotion(event, true);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002961 }
2962 };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002963
2964 public void dispatchKey(KeyEvent event) {
Jeff Brown92ff1dd2010-08-11 16:16:06 -07002965 dispatchKey(event, false);
2966 }
2967
2968 private void dispatchKey(KeyEvent event, boolean sendDone) {
2969 //noinspection ConstantConditions
2970 if (false && event.getAction() == KeyEvent.ACTION_DOWN) {
2971 if (event.getKeyCode() == KeyEvent.KEYCODE_CAMERA) {
Romain Guy812ccbe2010-06-01 14:07:24 -07002972 if (DBG) Log.d("keydisp", "===================================================");
2973 if (DBG) Log.d("keydisp", "Focused view Hierarchy is:");
2974
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002975 debug();
2976
Romain Guy812ccbe2010-06-01 14:07:24 -07002977 if (DBG) Log.d("keydisp", "===================================================");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002978 }
2979 }
2980
2981 Message msg = obtainMessage(DISPATCH_KEY);
2982 msg.obj = event;
Jeff Brown92ff1dd2010-08-11 16:16:06 -07002983 msg.arg1 = sendDone ? 1 : 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002984
2985 if (LOCAL_LOGV) Log.v(
Jeff Brownc5ed5912010-07-14 18:48:53 -07002986 TAG, "sending key " + event + " to " + mView);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002987
2988 sendMessageAtTime(msg, event.getEventTime());
2989 }
Jeff Brownc5ed5912010-07-14 18:48:53 -07002990
2991 public void dispatchMotion(MotionEvent event) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07002992 dispatchMotion(event, false);
2993 }
2994
2995 private void dispatchMotion(MotionEvent event, boolean sendDone) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07002996 int source = event.getSource();
2997 if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07002998 dispatchPointer(event, sendDone);
Jeff Brownc5ed5912010-07-14 18:48:53 -07002999 } else if ((source & InputDevice.SOURCE_CLASS_TRACKBALL) != 0) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07003000 dispatchTrackball(event, sendDone);
Jeff Brownc5ed5912010-07-14 18:48:53 -07003001 } else {
3002 // TODO
3003 Log.v(TAG, "Dropping unsupported motion event (unimplemented): " + event);
Jeff Brown93ed4e32010-09-23 13:51:48 -07003004 if (sendDone) {
Jeff Brown3915bb82010-11-05 15:02:16 -07003005 finishInputEvent(false);
Jeff Brown93ed4e32010-09-23 13:51:48 -07003006 }
Jeff Brownc5ed5912010-07-14 18:48:53 -07003007 }
3008 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003009
Jeff Brown00fa7bd2010-07-02 15:37:36 -07003010 public void dispatchPointer(MotionEvent event) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07003011 dispatchPointer(event, false);
3012 }
3013
3014 private void dispatchPointer(MotionEvent event, boolean sendDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003015 Message msg = obtainMessage(DISPATCH_POINTER);
3016 msg.obj = event;
Jeff Brown93ed4e32010-09-23 13:51:48 -07003017 msg.arg1 = sendDone ? 1 : 0;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07003018 sendMessageAtTime(msg, event.getEventTime());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003019 }
3020
Jeff Brown00fa7bd2010-07-02 15:37:36 -07003021 public void dispatchTrackball(MotionEvent event) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07003022 dispatchTrackball(event, false);
3023 }
3024
3025 private void dispatchTrackball(MotionEvent event, boolean sendDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003026 Message msg = obtainMessage(DISPATCH_TRACKBALL);
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 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07003031
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003032 public void dispatchAppVisibility(boolean visible) {
3033 Message msg = obtainMessage(DISPATCH_APP_VISIBILITY);
3034 msg.arg1 = visible ? 1 : 0;
3035 sendMessage(msg);
3036 }
3037
3038 public void dispatchGetNewSurface() {
3039 Message msg = obtainMessage(DISPATCH_GET_NEW_SURFACE);
3040 sendMessage(msg);
3041 }
3042
3043 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
3044 Message msg = Message.obtain();
3045 msg.what = WINDOW_FOCUS_CHANGED;
3046 msg.arg1 = hasFocus ? 1 : 0;
3047 msg.arg2 = inTouchMode ? 1 : 0;
3048 sendMessage(msg);
3049 }
3050
Dianne Hackbornffa42482009-09-23 22:20:11 -07003051 public void dispatchCloseSystemDialogs(String reason) {
3052 Message msg = Message.obtain();
3053 msg.what = CLOSE_SYSTEM_DIALOGS;
3054 msg.obj = reason;
3055 sendMessage(msg);
3056 }
Christopher Tatea53146c2010-09-07 11:57:52 -07003057
3058 public void dispatchDragEvent(DragEvent event) {
Chris Tate91e9bb32010-10-12 12:58:43 -07003059 final int what;
3060 if (event.getAction() == DragEvent.ACTION_DRAG_LOCATION) {
3061 what = DISPATCH_DRAG_LOCATION_EVENT;
3062 removeMessages(what);
3063 } else {
3064 what = DISPATCH_DRAG_EVENT;
3065 }
3066 Message msg = obtainMessage(what, event);
Christopher Tatea53146c2010-09-07 11:57:52 -07003067 sendMessage(msg);
3068 }
3069
svetoslavganov75986cf2009-05-14 22:28:01 -07003070 /**
3071 * The window is getting focus so if there is anything focused/selected
3072 * send an {@link AccessibilityEvent} to announce that.
3073 */
3074 private void sendAccessibilityEvents() {
3075 if (!AccessibilityManager.getInstance(mView.getContext()).isEnabled()) {
3076 return;
3077 }
3078 mView.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
3079 View focusedView = mView.findFocus();
3080 if (focusedView != null && focusedView != mView) {
3081 focusedView.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
3082 }
3083 }
3084
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003085 public boolean showContextMenuForChild(View originalView) {
3086 return false;
3087 }
3088
Adam Powell6e346362010-07-23 10:18:23 -07003089 public ActionMode startActionModeForChild(View originalView, ActionMode.Callback callback) {
3090 return null;
3091 }
3092
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003093 public void createContextMenu(ContextMenu menu) {
3094 }
3095
3096 public void childDrawableStateChanged(View child) {
3097 }
3098
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003099 void checkThread() {
3100 if (mThread != Thread.currentThread()) {
3101 throw new CalledFromWrongThreadException(
3102 "Only the original thread that created a view hierarchy can touch its views.");
3103 }
3104 }
3105
3106 public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
3107 // ViewRoot never intercepts touch event, so this can be a no-op
3108 }
3109
3110 public boolean requestChildRectangleOnScreen(View child, Rect rectangle,
3111 boolean immediate) {
3112 return scrollToRectOrFocus(rectangle, immediate);
3113 }
Romain Guy8506ab42009-06-11 17:35:47 -07003114
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07003115 class TakenSurfaceHolder extends BaseSurfaceHolder {
3116 @Override
3117 public boolean onAllowLockCanvas() {
3118 return mDrawingAllowed;
3119 }
3120
3121 @Override
3122 public void onRelayoutContainer() {
3123 // Not currently interesting -- from changing between fixed and layout size.
3124 }
3125
3126 public void setFormat(int format) {
3127 ((RootViewSurfaceTaker)mView).setSurfaceFormat(format);
3128 }
3129
3130 public void setType(int type) {
3131 ((RootViewSurfaceTaker)mView).setSurfaceType(type);
3132 }
3133
3134 @Override
3135 public void onUpdateSurface() {
3136 // We take care of format and type changes on our own.
3137 throw new IllegalStateException("Shouldn't be here");
3138 }
3139
3140 public boolean isCreating() {
3141 return mIsCreating;
3142 }
3143
3144 @Override
3145 public void setFixedSize(int width, int height) {
3146 throw new UnsupportedOperationException(
3147 "Currently only support sizing from layout");
3148 }
3149
3150 public void setKeepScreenOn(boolean screenOn) {
3151 ((RootViewSurfaceTaker)mView).setSurfaceKeepScreenOn(screenOn);
3152 }
3153 }
3154
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003155 static class InputMethodCallback extends IInputMethodCallback.Stub {
3156 private WeakReference<ViewRoot> mViewRoot;
3157
3158 public InputMethodCallback(ViewRoot viewRoot) {
3159 mViewRoot = new WeakReference<ViewRoot>(viewRoot);
3160 }
Romain Guy8506ab42009-06-11 17:35:47 -07003161
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003162 public void finishedEvent(int seq, boolean handled) {
3163 final ViewRoot viewRoot = mViewRoot.get();
3164 if (viewRoot != null) {
3165 viewRoot.dispatchFinishedEvent(seq, handled);
3166 }
3167 }
3168
3169 public void sessionCreated(IInputMethodSession session) throws RemoteException {
3170 // Stub -- not for use in the client.
3171 }
3172 }
Romain Guy8506ab42009-06-11 17:35:47 -07003173
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003174 static class W extends IWindow.Stub {
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07003175 private final WeakReference<ViewRoot> mViewRoot;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003176
Romain Guyfb8b7632010-08-23 21:05:08 -07003177 W(ViewRoot viewRoot) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003178 mViewRoot = new WeakReference<ViewRoot>(viewRoot);
3179 }
3180
Romain Guyfb8b7632010-08-23 21:05:08 -07003181 public void resized(int w, int h, Rect coveredInsets, Rect visibleInsets,
3182 boolean reportDraw, Configuration newConfig) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003183 final ViewRoot viewRoot = mViewRoot.get();
3184 if (viewRoot != null) {
Romain Guyfb8b7632010-08-23 21:05:08 -07003185 viewRoot.dispatchResized(w, h, coveredInsets, visibleInsets, reportDraw, newConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003186 }
3187 }
3188
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003189 public void dispatchAppVisibility(boolean visible) {
3190 final ViewRoot viewRoot = mViewRoot.get();
3191 if (viewRoot != null) {
3192 viewRoot.dispatchAppVisibility(visible);
3193 }
3194 }
3195
3196 public void dispatchGetNewSurface() {
3197 final ViewRoot viewRoot = mViewRoot.get();
3198 if (viewRoot != null) {
3199 viewRoot.dispatchGetNewSurface();
3200 }
3201 }
3202
3203 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
3204 final ViewRoot viewRoot = mViewRoot.get();
3205 if (viewRoot != null) {
3206 viewRoot.windowFocusChanged(hasFocus, inTouchMode);
3207 }
3208 }
3209
3210 private static int checkCallingPermission(String permission) {
3211 if (!Process.supportsProcesses()) {
3212 return PackageManager.PERMISSION_GRANTED;
3213 }
3214
3215 try {
3216 return ActivityManagerNative.getDefault().checkPermission(
3217 permission, Binder.getCallingPid(), Binder.getCallingUid());
3218 } catch (RemoteException e) {
3219 return PackageManager.PERMISSION_DENIED;
3220 }
3221 }
3222
3223 public void executeCommand(String command, String parameters, ParcelFileDescriptor out) {
3224 final ViewRoot viewRoot = mViewRoot.get();
3225 if (viewRoot != null) {
3226 final View view = viewRoot.mView;
3227 if (view != null) {
3228 if (checkCallingPermission(Manifest.permission.DUMP) !=
3229 PackageManager.PERMISSION_GRANTED) {
3230 throw new SecurityException("Insufficient permissions to invoke"
3231 + " executeCommand() from pid=" + Binder.getCallingPid()
3232 + ", uid=" + Binder.getCallingUid());
3233 }
3234
3235 OutputStream clientStream = null;
3236 try {
3237 clientStream = new ParcelFileDescriptor.AutoCloseOutputStream(out);
3238 ViewDebug.dispatchCommand(view, command, parameters, clientStream);
3239 } catch (IOException e) {
3240 e.printStackTrace();
3241 } finally {
3242 if (clientStream != null) {
3243 try {
3244 clientStream.close();
3245 } catch (IOException e) {
3246 e.printStackTrace();
3247 }
3248 }
3249 }
3250 }
3251 }
3252 }
Dianne Hackborn72c82ab2009-08-11 21:13:54 -07003253
Dianne Hackbornffa42482009-09-23 22:20:11 -07003254 public void closeSystemDialogs(String reason) {
3255 final ViewRoot viewRoot = mViewRoot.get();
3256 if (viewRoot != null) {
3257 viewRoot.dispatchCloseSystemDialogs(reason);
3258 }
3259 }
3260
Marco Nelissenbf6956b2009-11-09 15:21:13 -08003261 public void dispatchWallpaperOffsets(float x, float y, float xStep, float yStep,
3262 boolean sync) {
Dianne Hackborn19382ac2009-09-11 21:13:37 -07003263 if (sync) {
3264 try {
3265 sWindowSession.wallpaperOffsetsComplete(asBinder());
3266 } catch (RemoteException e) {
3267 }
3268 }
Dianne Hackborn72c82ab2009-08-11 21:13:54 -07003269 }
Dianne Hackborn75804932009-10-20 20:15:20 -07003270
3271 public void dispatchWallpaperCommand(String action, int x, int y,
3272 int z, Bundle extras, boolean sync) {
3273 if (sync) {
3274 try {
3275 sWindowSession.wallpaperCommandComplete(asBinder(), null);
3276 } catch (RemoteException e) {
3277 }
3278 }
3279 }
Christopher Tatea53146c2010-09-07 11:57:52 -07003280
3281 /* Drag/drop */
3282 public void dispatchDragEvent(DragEvent event) {
3283 final ViewRoot viewRoot = mViewRoot.get();
3284 if (viewRoot != null) {
3285 viewRoot.dispatchDragEvent(event);
3286 }
3287 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003288 }
3289
3290 /**
3291 * Maintains state information for a single trackball axis, generating
3292 * discrete (DPAD) movements based on raw trackball motion.
3293 */
3294 static final class TrackballAxis {
3295 /**
3296 * The maximum amount of acceleration we will apply.
3297 */
3298 static final float MAX_ACCELERATION = 20;
Romain Guy8506ab42009-06-11 17:35:47 -07003299
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003300 /**
3301 * The maximum amount of time (in milliseconds) between events in order
3302 * for us to consider the user to be doing fast trackball movements,
3303 * and thus apply an acceleration.
3304 */
3305 static final long FAST_MOVE_TIME = 150;
Romain Guy8506ab42009-06-11 17:35:47 -07003306
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003307 /**
3308 * Scaling factor to the time (in milliseconds) between events to how
3309 * much to multiple/divide the current acceleration. When movement
3310 * is < FAST_MOVE_TIME this multiplies the acceleration; when >
3311 * FAST_MOVE_TIME it divides it.
3312 */
3313 static final float ACCEL_MOVE_SCALING_FACTOR = (1.0f/40);
Romain Guy8506ab42009-06-11 17:35:47 -07003314
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003315 float position;
3316 float absPosition;
3317 float acceleration = 1;
3318 long lastMoveTime = 0;
3319 int step;
3320 int dir;
3321 int nonAccelMovement;
3322
3323 void reset(int _step) {
3324 position = 0;
3325 acceleration = 1;
3326 lastMoveTime = 0;
3327 step = _step;
3328 dir = 0;
3329 }
3330
3331 /**
3332 * Add trackball movement into the state. If the direction of movement
3333 * has been reversed, the state is reset before adding the
3334 * movement (so that you don't have to compensate for any previously
3335 * collected movement before see the result of the movement in the
3336 * new direction).
3337 *
3338 * @return Returns the absolute value of the amount of movement
3339 * collected so far.
3340 */
3341 float collect(float off, long time, String axis) {
3342 long normTime;
3343 if (off > 0) {
3344 normTime = (long)(off * FAST_MOVE_TIME);
3345 if (dir < 0) {
3346 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to positive!");
3347 position = 0;
3348 step = 0;
3349 acceleration = 1;
3350 lastMoveTime = 0;
3351 }
3352 dir = 1;
3353 } else if (off < 0) {
3354 normTime = (long)((-off) * FAST_MOVE_TIME);
3355 if (dir > 0) {
3356 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to negative!");
3357 position = 0;
3358 step = 0;
3359 acceleration = 1;
3360 lastMoveTime = 0;
3361 }
3362 dir = -1;
3363 } else {
3364 normTime = 0;
3365 }
Romain Guy8506ab42009-06-11 17:35:47 -07003366
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003367 // The number of milliseconds between each movement that is
3368 // considered "normal" and will not result in any acceleration
3369 // or deceleration, scaled by the offset we have here.
3370 if (normTime > 0) {
3371 long delta = time - lastMoveTime;
3372 lastMoveTime = time;
3373 float acc = acceleration;
3374 if (delta < normTime) {
3375 // The user is scrolling rapidly, so increase acceleration.
3376 float scale = (normTime-delta) * ACCEL_MOVE_SCALING_FACTOR;
3377 if (scale > 1) acc *= scale;
3378 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " accelerate: off="
3379 + off + " normTime=" + normTime + " delta=" + delta
3380 + " scale=" + scale + " acc=" + acc);
3381 acceleration = acc < MAX_ACCELERATION ? acc : MAX_ACCELERATION;
3382 } else {
3383 // The user is scrolling slowly, so decrease acceleration.
3384 float scale = (delta-normTime) * ACCEL_MOVE_SCALING_FACTOR;
3385 if (scale > 1) acc /= scale;
3386 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " deccelerate: off="
3387 + off + " normTime=" + normTime + " delta=" + delta
3388 + " scale=" + scale + " acc=" + acc);
3389 acceleration = acc > 1 ? acc : 1;
3390 }
3391 }
3392 position += off;
3393 return (absPosition = Math.abs(position));
3394 }
3395
3396 /**
3397 * Generate the number of discrete movement events appropriate for
3398 * the currently collected trackball movement.
3399 *
3400 * @param precision The minimum movement required to generate the
3401 * first discrete movement.
3402 *
3403 * @return Returns the number of discrete movements, either positive
3404 * or negative, or 0 if there is not enough trackball movement yet
3405 * for a discrete movement.
3406 */
3407 int generate(float precision) {
3408 int movement = 0;
3409 nonAccelMovement = 0;
3410 do {
3411 final int dir = position >= 0 ? 1 : -1;
3412 switch (step) {
3413 // If we are going to execute the first step, then we want
3414 // to do this as soon as possible instead of waiting for
3415 // a full movement, in order to make things look responsive.
3416 case 0:
3417 if (absPosition < precision) {
3418 return movement;
3419 }
3420 movement += dir;
3421 nonAccelMovement += dir;
3422 step = 1;
3423 break;
3424 // If we have generated the first movement, then we need
3425 // to wait for the second complete trackball motion before
3426 // generating the second discrete movement.
3427 case 1:
3428 if (absPosition < 2) {
3429 return movement;
3430 }
3431 movement += dir;
3432 nonAccelMovement += dir;
3433 position += dir > 0 ? -2 : 2;
3434 absPosition = Math.abs(position);
3435 step = 2;
3436 break;
3437 // After the first two, we generate discrete movements
3438 // consistently with the trackball, applying an acceleration
3439 // if the trackball is moving quickly. This is a simple
3440 // acceleration on top of what we already compute based
3441 // on how quickly the wheel is being turned, to apply
3442 // a longer increasing acceleration to continuous movement
3443 // in one direction.
3444 default:
3445 if (absPosition < 1) {
3446 return movement;
3447 }
3448 movement += dir;
3449 position += dir >= 0 ? -1 : 1;
3450 absPosition = Math.abs(position);
3451 float acc = acceleration;
3452 acc *= 1.1f;
3453 acceleration = acc < MAX_ACCELERATION ? acc : acceleration;
3454 break;
3455 }
3456 } while (true);
3457 }
3458 }
3459
3460 public static final class CalledFromWrongThreadException extends AndroidRuntimeException {
3461 public CalledFromWrongThreadException(String msg) {
3462 super(msg);
3463 }
3464 }
3465
3466 private SurfaceHolder mHolder = new SurfaceHolder() {
3467 // we only need a SurfaceHolder for opengl. it would be nice
3468 // to implement everything else though, especially the callback
3469 // support (opengl doesn't make use of it right now, but eventually
3470 // will).
3471 public Surface getSurface() {
3472 return mSurface;
3473 }
3474
3475 public boolean isCreating() {
3476 return false;
3477 }
3478
3479 public void addCallback(Callback callback) {
3480 }
3481
3482 public void removeCallback(Callback callback) {
3483 }
3484
3485 public void setFixedSize(int width, int height) {
3486 }
3487
3488 public void setSizeFromLayout() {
3489 }
3490
3491 public void setFormat(int format) {
3492 }
3493
3494 public void setType(int type) {
3495 }
3496
3497 public void setKeepScreenOn(boolean screenOn) {
3498 }
3499
3500 public Canvas lockCanvas() {
3501 return null;
3502 }
3503
3504 public Canvas lockCanvas(Rect dirty) {
3505 return null;
3506 }
3507
3508 public void unlockCanvasAndPost(Canvas canvas) {
3509 }
3510 public Rect getSurfaceFrame() {
3511 return null;
3512 }
3513 };
3514
3515 static RunQueue getRunQueue() {
3516 RunQueue rq = sRunQueues.get();
3517 if (rq != null) {
3518 return rq;
3519 }
3520 rq = new RunQueue();
3521 sRunQueues.set(rq);
3522 return rq;
3523 }
Romain Guy8506ab42009-06-11 17:35:47 -07003524
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003525 /**
3526 * @hide
3527 */
3528 static final class RunQueue {
3529 private final ArrayList<HandlerAction> mActions = new ArrayList<HandlerAction>();
3530
3531 void post(Runnable action) {
3532 postDelayed(action, 0);
3533 }
3534
3535 void postDelayed(Runnable action, long delayMillis) {
3536 HandlerAction handlerAction = new HandlerAction();
3537 handlerAction.action = action;
3538 handlerAction.delay = delayMillis;
3539
3540 synchronized (mActions) {
3541 mActions.add(handlerAction);
3542 }
3543 }
3544
3545 void removeCallbacks(Runnable action) {
3546 final HandlerAction handlerAction = new HandlerAction();
3547 handlerAction.action = action;
3548
3549 synchronized (mActions) {
3550 final ArrayList<HandlerAction> actions = mActions;
3551
3552 while (actions.remove(handlerAction)) {
3553 // Keep going
3554 }
3555 }
3556 }
3557
3558 void executeActions(Handler handler) {
3559 synchronized (mActions) {
3560 final ArrayList<HandlerAction> actions = mActions;
3561 final int count = actions.size();
3562
3563 for (int i = 0; i < count; i++) {
3564 final HandlerAction handlerAction = actions.get(i);
3565 handler.postDelayed(handlerAction.action, handlerAction.delay);
3566 }
3567
Romain Guy15df6702009-08-17 20:17:30 -07003568 actions.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003569 }
3570 }
3571
3572 private static class HandlerAction {
3573 Runnable action;
3574 long delay;
3575
3576 @Override
3577 public boolean equals(Object o) {
3578 if (this == o) return true;
3579 if (o == null || getClass() != o.getClass()) return false;
3580
3581 HandlerAction that = (HandlerAction) o;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003582 return !(action != null ? !action.equals(that.action) : that.action != null);
3583
3584 }
3585
3586 @Override
3587 public int hashCode() {
3588 int result = action != null ? action.hashCode() : 0;
3589 result = 31 * result + (int) (delay ^ (delay >>> 32));
3590 return result;
3591 }
3592 }
3593 }
3594
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003595 private static native void nativeShowFPS(Canvas canvas, int durationMillis);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003596}