blob: cb7d0e277e6238279ba7444643e664fe3c33df10 [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;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080028import android.graphics.Canvas;
29import android.graphics.PixelFormat;
Christopher Tate2c095f32010-10-04 14:13:40 -070030import android.graphics.Point;
Christopher Tatea53146c2010-09-07 11:57:52 -070031import android.graphics.PointF;
Romain Guy6b7bd242010-10-06 19:49:23 -070032import android.graphics.PorterDuff;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080033import android.graphics.Rect;
34import android.graphics.Region;
Romain Guy6b7bd242010-10-06 19:49:23 -070035import android.media.AudioManager;
36import android.os.Binder;
37import android.os.Bundle;
38import android.os.Debug;
39import android.os.Handler;
40import android.os.LatencyTimer;
41import android.os.Looper;
42import android.os.Message;
43import android.os.ParcelFileDescriptor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080044import android.os.Process;
Romain Guy6b7bd242010-10-06 19:49:23 -070045import android.os.RemoteException;
46import android.os.ServiceManager;
47import android.os.SystemClock;
48import android.os.SystemProperties;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080049import android.util.AndroidRuntimeException;
50import android.util.Config;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -070051import android.util.DisplayMetrics;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080052import android.util.EventLog;
Romain Guy6b7bd242010-10-06 19:49:23 -070053import android.util.Log;
Chet Haase949dbf72010-08-11 18:41:06 -070054import android.util.Slog;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080055import android.util.SparseArray;
Dianne Hackborn711e62a2010-11-29 16:38:22 -080056import android.util.TypedValue;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080057import android.view.View.MeasureSpec;
svetoslavganov75986cf2009-05-14 22:28:01 -070058import android.view.accessibility.AccessibilityEvent;
59import android.view.accessibility.AccessibilityManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080060import android.view.inputmethod.InputConnection;
61import android.view.inputmethod.InputMethodManager;
62import android.widget.Scroller;
Joe Onorato86f67862010-11-05 18:57:34 -070063import com.android.internal.policy.PolicyManager;
Romain Guy6b7bd242010-10-06 19:49:23 -070064import com.android.internal.view.BaseSurfaceHolder;
65import com.android.internal.view.IInputMethodCallback;
66import com.android.internal.view.IInputMethodSession;
67import com.android.internal.view.RootViewSurfaceTaker;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080068
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080069import java.io.IOException;
70import java.io.OutputStream;
Romain Guy6b7bd242010-10-06 19:49:23 -070071import java.lang.ref.WeakReference;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080072import java.util.ArrayList;
73
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080074/**
75 * The top of a view hierarchy, implementing the needed protocol between View
76 * and the WindowManager. This is for the most part an internal implementation
77 * detail of {@link WindowManagerImpl}.
78 *
79 * {@hide}
80 */
Romain Guy812ccbe2010-06-01 14:07:24 -070081@SuppressWarnings({"EmptyCatchBlock", "PointlessBooleanExpression"})
82public final class ViewRoot extends Handler implements ViewParent, View.AttachInfo.Callbacks {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080083 private static final String TAG = "ViewRoot";
84 private static final boolean DBG = false;
Mike Reedfd716532009-10-12 14:42:56 -040085 private static final boolean SHOW_FPS = false;
Romain Guy812ccbe2010-06-01 14:07:24 -070086 private static final boolean LOCAL_LOGV = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080087 /** @noinspection PointlessBooleanExpression*/
88 private static final boolean DEBUG_DRAW = false || LOCAL_LOGV;
89 private static final boolean DEBUG_LAYOUT = false || LOCAL_LOGV;
Dianne Hackborn711e62a2010-11-29 16:38:22 -080090 private static final boolean DEBUG_DIALOG = false || LOCAL_LOGV;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080091 private static final boolean DEBUG_INPUT_RESIZE = false || LOCAL_LOGV;
92 private static final boolean DEBUG_ORIENTATION = false || LOCAL_LOGV;
93 private static final boolean DEBUG_TRACKBALL = false || LOCAL_LOGV;
94 private static final boolean DEBUG_IMF = false || LOCAL_LOGV;
Dianne Hackborn694f79b2010-03-17 19:44:59 -070095 private static final boolean DEBUG_CONFIGURATION = false || LOCAL_LOGV;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080096 private static final boolean WATCH_POINTER = false;
97
Michael Chan53071d62009-05-13 17:29:48 -070098 private static final boolean MEASURE_LATENCY = false;
99 private static LatencyTimer lt;
100
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800101 /**
102 * Maximum time we allow the user to roll the trackball enough to generate
103 * a key event, before resetting the counters.
104 */
105 static final int MAX_TRACKBALL_DELAY = 250;
106
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800107 static IWindowSession sWindowSession;
108
109 static final Object mStaticInit = new Object();
110 static boolean mInitialized = false;
111
112 static final ThreadLocal<RunQueue> sRunQueues = new ThreadLocal<RunQueue>();
113
Dianne Hackborn2a9094d2010-02-03 19:20:09 -0800114 static final ArrayList<Runnable> sFirstDrawHandlers = new ArrayList<Runnable>();
115 static boolean sFirstDrawComplete = false;
116
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800117 static final ArrayList<ComponentCallbacks> sConfigCallbacks
118 = new ArrayList<ComponentCallbacks>();
119
Romain Guy8506ab42009-06-11 17:35:47 -0700120 private static int sDrawTime;
Romain Guy13922e02009-05-12 17:56:14 -0700121
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800122 long mLastTrackballTime = 0;
123 final TrackballAxis mTrackballAxisX = new TrackballAxis();
124 final TrackballAxis mTrackballAxisY = new TrackballAxis();
125
126 final int[] mTmpLocation = new int[2];
Romain Guy8506ab42009-06-11 17:35:47 -0700127
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800128 final TypedValue mTmpValue = new TypedValue();
129
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800130 final InputMethodCallback mInputMethodCallback;
131 final SparseArray<Object> mPendingEvents = new SparseArray<Object>();
132 int mPendingEventSeq = 0;
Romain Guy8506ab42009-06-11 17:35:47 -0700133
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800134 final Thread mThread;
135
136 final WindowLeaked mLocation;
137
138 final WindowManager.LayoutParams mWindowAttributes = new WindowManager.LayoutParams();
139
140 final W mWindow;
141
142 View mView;
143 View mFocusedView;
144 View mRealFocusedView; // this is not set to null in touch mode
145 int mViewVisibility;
146 boolean mAppVisible = true;
147
Dianne Hackbornd76b67c2010-07-13 17:48:30 -0700148 SurfaceHolder.Callback2 mSurfaceHolderCallback;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700149 BaseSurfaceHolder mSurfaceHolder;
150 boolean mIsCreating;
151 boolean mDrawingAllowed;
152
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800153 final Region mTransparentRegion;
154 final Region mPreviousTransparentRegion;
155
156 int mWidth;
157 int mHeight;
158 Rect mDirty; // will be a graphics.Region soon
Romain Guybb93d552009-03-24 21:04:15 -0700159 boolean mIsAnimating;
Romain Guy8506ab42009-06-11 17:35:47 -0700160
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700161 CompatibilityInfo.Translator mTranslator;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800162
163 final View.AttachInfo mAttachInfo;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700164 InputChannel mInputChannel;
Dianne Hackborn1e4b9f32010-06-23 14:10:57 -0700165 InputQueue.Callback mInputQueueCallback;
166 InputQueue mInputQueue;
Joe Onorato86f67862010-11-05 18:57:34 -0700167 FallbackEventHandler mFallbackEventHandler;
Dianne Hackborna95e4cb2010-06-18 18:09:33 -0700168
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800169 final Rect mTempRect; // used in the transaction to not thrash the heap.
170 final Rect mVisRect; // used to retrieve visible rect of focused view.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800171
172 boolean mTraversalScheduled;
173 boolean mWillDrawSoon;
174 boolean mLayoutRequested;
175 boolean mFirst;
176 boolean mReportNextDraw;
177 boolean mFullRedrawNeeded;
178 boolean mNewSurfaceNeeded;
179 boolean mHasHadWindowFocus;
180 boolean mLastWasImTarget;
181
182 boolean mWindowAttributesChanged = false;
183
184 // These can be accessed by any thread, must be protected with a lock.
Mathias Agopian5583dc62009-07-09 16:28:11 -0700185 // Surface can never be reassigned or cleared (use Surface.clear()).
186 private final Surface mSurface = new Surface();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800187
188 boolean mAdded;
189 boolean mAddedTouchMode;
190
191 /*package*/ int mAddNesting;
192
193 // These are accessed by multiple threads.
194 final Rect mWinFrame; // frame given by window manager.
195
196 final Rect mPendingVisibleInsets = new Rect();
197 final Rect mPendingContentInsets = new Rect();
198 final ViewTreeObserver.InternalInsetsInfo mLastGivenInsets
199 = new ViewTreeObserver.InternalInsetsInfo();
200
Dianne Hackborn694f79b2010-03-17 19:44:59 -0700201 final Configuration mLastConfiguration = new Configuration();
202 final Configuration mPendingConfiguration = new Configuration();
203
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800204 class ResizedInfo {
205 Rect coveredInsets;
206 Rect visibleInsets;
207 Configuration newConfig;
208 }
209
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800210 boolean mScrollMayChange;
211 int mSoftInputMode;
212 View mLastScrolledFocus;
213 int mScrollY;
214 int mCurScrollY;
215 Scroller mScroller;
Romain Guy8506ab42009-06-11 17:35:47 -0700216
Romain Guy8506ab42009-06-11 17:35:47 -0700217 final ViewConfiguration mViewConfiguration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800218
Christopher Tatea53146c2010-09-07 11:57:52 -0700219 /* Drag/drop */
220 ClipDescription mDragDescription;
221 View mCurrentDragView;
222 final PointF mDragPoint = new PointF();
Christopher Tate2c095f32010-10-04 14:13:40 -0700223 final PointF mLastTouchPoint = new PointF();
Christopher Tatea53146c2010-09-07 11:57:52 -0700224
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800225 /**
226 * see {@link #playSoundEffect(int)}
227 */
228 AudioManager mAudioManager;
229
Dianne Hackborn11ea3342009-07-22 21:48:55 -0700230 private final int mDensity;
Adam Powellb08013c2010-09-16 16:28:11 -0700231
Dianne Hackborn4c62fc02009-08-08 20:40:27 -0700232 public static IWindowSession getWindowSession(Looper mainLooper) {
233 synchronized (mStaticInit) {
234 if (!mInitialized) {
235 try {
236 InputMethodManager imm = InputMethodManager.getInstance(mainLooper);
237 sWindowSession = IWindowManager.Stub.asInterface(
238 ServiceManager.getService("window"))
239 .openSession(imm.getClient(), imm.getInputContext());
240 mInitialized = true;
241 } catch (RemoteException e) {
242 }
243 }
244 return sWindowSession;
245 }
246 }
247
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800248 public ViewRoot(Context context) {
249 super();
250
Romain Guy812ccbe2010-06-01 14:07:24 -0700251 if (MEASURE_LATENCY) {
252 if (lt == null) {
253 lt = new LatencyTimer(100, 1000);
254 }
Michael Chan53071d62009-05-13 17:29:48 -0700255 }
256
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800257 // Initialize the statics when this class is first instantiated. This is
258 // done here instead of in the static block because Zygote does not
259 // allow the spawning of threads.
Dianne Hackborn4c62fc02009-08-08 20:40:27 -0700260 getWindowSession(context.getMainLooper());
261
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800262 mThread = Thread.currentThread();
263 mLocation = new WindowLeaked(null);
264 mLocation.fillInStackTrace();
265 mWidth = -1;
266 mHeight = -1;
267 mDirty = new Rect();
268 mTempRect = new Rect();
269 mVisRect = new Rect();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800270 mWinFrame = new Rect();
Romain Guyfb8b7632010-08-23 21:05:08 -0700271 mWindow = new W(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800272 mInputMethodCallback = new InputMethodCallback(this);
273 mViewVisibility = View.GONE;
274 mTransparentRegion = new Region();
275 mPreviousTransparentRegion = new Region();
276 mFirst = true; // true for the first time the view is added
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800277 mAdded = false;
278 mAttachInfo = new View.AttachInfo(sWindowSession, mWindow, this, this);
279 mViewConfiguration = ViewConfiguration.get(context);
Dianne Hackborn11ea3342009-07-22 21:48:55 -0700280 mDensity = context.getResources().getDisplayMetrics().densityDpi;
Joe Onorato86f67862010-11-05 18:57:34 -0700281 mFallbackEventHandler = PolicyManager.makeNewFallbackEventHandler(context);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800282 }
283
Dianne Hackborn2a9094d2010-02-03 19:20:09 -0800284 public static void addFirstDrawHandler(Runnable callback) {
285 synchronized (sFirstDrawHandlers) {
286 if (!sFirstDrawComplete) {
287 sFirstDrawHandlers.add(callback);
288 }
289 }
290 }
291
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800292 public static void addConfigCallback(ComponentCallbacks callback) {
293 synchronized (sConfigCallbacks) {
294 sConfigCallbacks.add(callback);
295 }
296 }
297
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800298 // FIXME for perf testing only
299 private boolean mProfile = false;
300
301 /**
302 * Call this to profile the next traversal call.
303 * FIXME for perf testing only. Remove eventually
304 */
305 public void profile() {
306 mProfile = true;
307 }
308
309 /**
310 * Indicates whether we are in touch mode. Calling this method triggers an IPC
311 * call and should be avoided whenever possible.
312 *
313 * @return True, if the device is in touch mode, false otherwise.
314 *
315 * @hide
316 */
317 static boolean isInTouchMode() {
318 if (mInitialized) {
319 try {
320 return sWindowSession.getInTouchMode();
321 } catch (RemoteException e) {
322 }
323 }
324 return false;
325 }
326
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800327 /**
328 * We have one child
329 */
Romain Guye4d01122010-06-16 18:44:05 -0700330 public void setView(View view, WindowManager.LayoutParams attrs, View panelParentView) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800331 synchronized (this) {
332 if (mView == null) {
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700333 mView = view;
Joe Onorato86f67862010-11-05 18:57:34 -0700334 mFallbackEventHandler.setView(view);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700335 mWindowAttributes.copyFrom(attrs);
Mitsuru Oshima1ecf5d22009-07-06 17:20:38 -0700336 attrs = mWindowAttributes;
Romain Guye4d01122010-06-16 18:44:05 -0700337
Romain Guy529b60a2010-08-03 18:05:47 -0700338 enableHardwareAcceleration(attrs);
Romain Guye4d01122010-06-16 18:44:05 -0700339
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700340 if (view instanceof RootViewSurfaceTaker) {
341 mSurfaceHolderCallback =
342 ((RootViewSurfaceTaker)view).willYouTakeTheSurface();
343 if (mSurfaceHolderCallback != null) {
344 mSurfaceHolder = new TakenSurfaceHolder();
Dianne Hackborn289b9b62010-07-09 11:44:11 -0700345 mSurfaceHolder.setFormat(PixelFormat.UNKNOWN);
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700346 }
347 }
Mitsuru Oshima38ed7d772009-07-21 14:39:34 -0700348 Resources resources = mView.getContext().getResources();
349 CompatibilityInfo compatibilityInfo = resources.getCompatibilityInfo();
Mitsuru Oshima589cebe2009-07-22 20:38:58 -0700350 mTranslator = compatibilityInfo.getTranslator();
Mitsuru Oshima38ed7d772009-07-21 14:39:34 -0700351
352 if (mTranslator != null || !compatibilityInfo.supportsScreen()) {
Mitsuru Oshima240f8a72009-07-22 20:39:14 -0700353 mSurface.setCompatibleDisplayMetrics(resources.getDisplayMetrics(),
354 mTranslator);
Mitsuru Oshima38ed7d772009-07-21 14:39:34 -0700355 }
356
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -0700357 boolean restore = false;
Romain Guy35b38ce2009-10-07 13:38:55 -0700358 if (mTranslator != null) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -0700359 restore = true;
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700360 attrs.backup();
361 mTranslator.translateWindowLayout(attrs);
Mitsuru Oshima3d914922009-05-13 22:29:15 -0700362 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700363 if (DEBUG_LAYOUT) Log.d(TAG, "WindowLayout in setView:" + attrs);
364
Mitsuru Oshima1ecf5d22009-07-06 17:20:38 -0700365 if (!compatibilityInfo.supportsScreen()) {
366 attrs.flags |= WindowManager.LayoutParams.FLAG_COMPATIBLE_WINDOW;
367 }
368
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800369 mSoftInputMode = attrs.softInputMode;
370 mWindowAttributesChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800371 mAttachInfo.mRootView = view;
Romain Guy35b38ce2009-10-07 13:38:55 -0700372 mAttachInfo.mScalingRequired = mTranslator != null;
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700373 mAttachInfo.mApplicationScale =
374 mTranslator == null ? 1.0f : mTranslator.applicationScale;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800375 if (panelParentView != null) {
376 mAttachInfo.mPanelParentWindowToken
377 = panelParentView.getApplicationWindowToken();
378 }
379 mAdded = true;
380 int res; /* = WindowManagerImpl.ADD_OKAY; */
Romain Guy8506ab42009-06-11 17:35:47 -0700381
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800382 // Schedule the first layout -before- adding to the window
383 // manager, to make sure we do the relayout before receiving
384 // any other events from the system.
385 requestLayout();
Jeff Brown46b9ac02010-04-22 18:58:52 -0700386 mInputChannel = new InputChannel();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800387 try {
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700388 res = sWindowSession.add(mWindow, mWindowAttributes,
Jeff Brown46b9ac02010-04-22 18:58:52 -0700389 getHostVisibility(), mAttachInfo.mContentInsets,
390 mInputChannel);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800391 } catch (RemoteException e) {
392 mAdded = false;
393 mView = null;
394 mAttachInfo.mRootView = null;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700395 mInputChannel = null;
Joe Onorato86f67862010-11-05 18:57:34 -0700396 mFallbackEventHandler.setView(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800397 unscheduleTraversals();
398 throw new RuntimeException("Adding window failed", e);
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700399 } finally {
400 if (restore) {
401 attrs.restore();
402 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800403 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700404
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700405 if (mTranslator != null) {
406 mTranslator.translateRectInScreenToAppWindow(mAttachInfo.mContentInsets);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700407 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800408 mPendingContentInsets.set(mAttachInfo.mContentInsets);
409 mPendingVisibleInsets.set(0, 0, 0, 0);
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800410 if (DEBUG_LAYOUT) Log.v(TAG, "Added window " + mWindow);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800411 if (res < WindowManagerImpl.ADD_OKAY) {
412 mView = null;
413 mAttachInfo.mRootView = null;
414 mAdded = false;
Joe Onorato86f67862010-11-05 18:57:34 -0700415 mFallbackEventHandler.setView(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800416 unscheduleTraversals();
417 switch (res) {
418 case WindowManagerImpl.ADD_BAD_APP_TOKEN:
419 case WindowManagerImpl.ADD_BAD_SUBWINDOW_TOKEN:
420 throw new WindowManagerImpl.BadTokenException(
421 "Unable to add window -- token " + attrs.token
422 + " is not valid; is your activity running?");
423 case WindowManagerImpl.ADD_NOT_APP_TOKEN:
424 throw new WindowManagerImpl.BadTokenException(
425 "Unable to add window -- token " + attrs.token
426 + " is not for an application");
427 case WindowManagerImpl.ADD_APP_EXITING:
428 throw new WindowManagerImpl.BadTokenException(
429 "Unable to add window -- app for token " + attrs.token
430 + " is exiting");
431 case WindowManagerImpl.ADD_DUPLICATE_ADD:
432 throw new WindowManagerImpl.BadTokenException(
433 "Unable to add window -- window " + mWindow
434 + " has already been added");
435 case WindowManagerImpl.ADD_STARTING_NOT_NEEDED:
436 // Silently ignore -- we would have just removed it
437 // right away, anyway.
438 return;
439 case WindowManagerImpl.ADD_MULTIPLE_SINGLETON:
440 throw new WindowManagerImpl.BadTokenException(
441 "Unable to add window " + mWindow +
442 " -- another window of this type already exists");
443 case WindowManagerImpl.ADD_PERMISSION_DENIED:
444 throw new WindowManagerImpl.BadTokenException(
445 "Unable to add window " + mWindow +
446 " -- permission denied for this window type");
447 }
448 throw new RuntimeException(
449 "Unable to add window -- unknown error code " + res);
450 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700451
Jeff Brown00fa7bd2010-07-02 15:37:36 -0700452 if (view instanceof RootViewSurfaceTaker) {
453 mInputQueueCallback =
454 ((RootViewSurfaceTaker)view).willYouTakeTheInputQueue();
455 }
456 if (mInputQueueCallback != null) {
457 mInputQueue = new InputQueue(mInputChannel);
458 mInputQueueCallback.onInputQueueCreated(mInputQueue);
459 } else {
460 InputQueue.registerInputChannel(mInputChannel, mInputHandler,
461 Looper.myQueue());
Jeff Brown46b9ac02010-04-22 18:58:52 -0700462 }
463
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800464 view.assignParent(this);
465 mAddedTouchMode = (res&WindowManagerImpl.ADD_FLAG_IN_TOUCH_MODE) != 0;
466 mAppVisible = (res&WindowManagerImpl.ADD_FLAG_APP_VISIBLE) != 0;
467 }
468 }
469 }
470
Romain Guy529b60a2010-08-03 18:05:47 -0700471 private void enableHardwareAcceleration(WindowManager.LayoutParams attrs) {
Dianne Hackborn7eec10e2010-11-12 18:03:47 -0800472 mAttachInfo.mHardwareAccelerated = false;
473 mAttachInfo.mHardwareAccelerationRequested = false;
474
475 // Try to enable hardware acceleration if requested
476 if (attrs != null &&
477 (attrs.flags & WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED) != 0) {
478 // Only enable hardware acceleration if we are not in the system process
479 // The window manager creates ViewRoots to display animated preview windows
480 // of launching apps and we don't want those to be hardware accelerated
481 if (!HardwareRenderer.sRendererDisabled) {
Romain Guye4d01122010-06-16 18:44:05 -0700482 final boolean translucent = attrs.format != PixelFormat.OPAQUE;
Romain Guyb051e892010-09-28 19:09:36 -0700483 if (mAttachInfo.mHardwareRenderer != null) {
484 mAttachInfo.mHardwareRenderer.destroy(true);
Romain Guy4caa4ed2010-08-25 14:46:24 -0700485 }
Romain Guyb051e892010-09-28 19:09:36 -0700486 mAttachInfo.mHardwareRenderer = HardwareRenderer.createGlRenderer(2, translucent);
Dianne Hackborn7eec10e2010-11-12 18:03:47 -0800487 mAttachInfo.mHardwareAccelerated = mAttachInfo.mHardwareAccelerationRequested
488 = mAttachInfo.mHardwareRenderer != null;
489 } else if (HardwareRenderer.isAvailable()) {
490 mAttachInfo.mHardwareAccelerationRequested = true;
Romain Guye4d01122010-06-16 18:44:05 -0700491 }
492 }
493 }
494
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800495 public View getView() {
496 return mView;
497 }
498
499 final WindowLeaked getLocation() {
500 return mLocation;
501 }
502
503 void setLayoutParams(WindowManager.LayoutParams attrs, boolean newView) {
504 synchronized (this) {
The Android Open Source Project10592532009-03-18 17:39:46 -0700505 int oldSoftInputMode = mWindowAttributes.softInputMode;
Mitsuru Oshima5a2b91d2009-07-16 16:30:02 -0700506 // preserve compatible window flag if exists.
507 int compatibleWindowFlag =
508 mWindowAttributes.flags & WindowManager.LayoutParams.FLAG_COMPATIBLE_WINDOW;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800509 mWindowAttributes.copyFrom(attrs);
Mitsuru Oshima5a2b91d2009-07-16 16:30:02 -0700510 mWindowAttributes.flags |= compatibleWindowFlag;
511
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800512 if (newView) {
513 mSoftInputMode = attrs.softInputMode;
514 requestLayout();
515 }
The Android Open Source Project10592532009-03-18 17:39:46 -0700516 // Don't lose the mode we last auto-computed.
517 if ((attrs.softInputMode&WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST)
518 == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED) {
519 mWindowAttributes.softInputMode = (mWindowAttributes.softInputMode
520 & ~WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST)
521 | (oldSoftInputMode
522 & WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST);
523 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800524 mWindowAttributesChanged = true;
525 scheduleTraversals();
526 }
527 }
528
529 void handleAppVisibility(boolean visible) {
530 if (mAppVisible != visible) {
531 mAppVisible = visible;
532 scheduleTraversals();
533 }
534 }
535
536 void handleGetNewSurface() {
537 mNewSurfaceNeeded = true;
538 mFullRedrawNeeded = true;
539 scheduleTraversals();
540 }
541
542 /**
543 * {@inheritDoc}
544 */
545 public void requestLayout() {
546 checkThread();
547 mLayoutRequested = true;
548 scheduleTraversals();
549 }
550
551 /**
552 * {@inheritDoc}
553 */
554 public boolean isLayoutRequested() {
555 return mLayoutRequested;
556 }
557
558 public void invalidateChild(View child, Rect dirty) {
559 checkThread();
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700560 if (DEBUG_DRAW) Log.v(TAG, "Invalidate child: " + dirty);
Chet Haase70d4ba12010-10-06 09:46:45 -0700561 if (dirty == null) {
562 // Fast invalidation for GL-enabled applications; GL must redraw everything
563 invalidate();
564 return;
565 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700566 if (mCurScrollY != 0 || mTranslator != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800567 mTempRect.set(dirty);
Romain Guy1e095972009-07-07 11:22:45 -0700568 dirty = mTempRect;
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700569 if (mCurScrollY != 0) {
Romain Guy1e095972009-07-07 11:22:45 -0700570 dirty.offset(0, -mCurScrollY);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700571 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700572 if (mTranslator != null) {
Romain Guy1e095972009-07-07 11:22:45 -0700573 mTranslator.translateRectInAppWindowToScreen(dirty);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700574 }
Romain Guy1e095972009-07-07 11:22:45 -0700575 if (mAttachInfo.mScalingRequired) {
576 dirty.inset(-1, -1);
577 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800578 }
579 mDirty.union(dirty);
580 if (!mWillDrawSoon) {
581 scheduleTraversals();
582 }
583 }
Romain Guy0d9275e2010-10-26 14:22:30 -0700584
585 void invalidate() {
586 mDirty.set(0, 0, mWidth, mHeight);
587 scheduleTraversals();
588 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800589
590 public ViewParent getParent() {
591 return null;
592 }
593
594 public ViewParent invalidateChildInParent(final int[] location, final Rect dirty) {
595 invalidateChild(null, dirty);
596 return null;
597 }
598
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700599 public boolean getChildVisibleRect(View child, Rect r, android.graphics.Point offset) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800600 if (child != mView) {
601 throw new RuntimeException("child is not mine, honest!");
602 }
603 // Note: don't apply scroll offset, because we want to know its
604 // visibility in the virtual canvas being given to the view hierarchy.
605 return r.intersect(0, 0, mWidth, mHeight);
606 }
607
608 public void bringChildToFront(View child) {
609 }
610
611 public void scheduleTraversals() {
612 if (!mTraversalScheduled) {
613 mTraversalScheduled = true;
614 sendEmptyMessage(DO_TRAVERSAL);
615 }
616 }
617
618 public void unscheduleTraversals() {
619 if (mTraversalScheduled) {
620 mTraversalScheduled = false;
621 removeMessages(DO_TRAVERSAL);
622 }
623 }
624
625 int getHostVisibility() {
626 return mAppVisible ? mView.getVisibility() : View.GONE;
627 }
Romain Guy8506ab42009-06-11 17:35:47 -0700628
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800629 private void performTraversals() {
630 // cache mView since it is used so much below...
631 final View host = mView;
632
633 if (DBG) {
634 System.out.println("======================================");
635 System.out.println("performTraversals");
636 host.debug();
637 }
638
639 if (host == null || !mAdded)
640 return;
641
642 mTraversalScheduled = false;
643 mWillDrawSoon = true;
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800644 boolean windowSizeMayChange = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800645 boolean fullRedrawNeeded = mFullRedrawNeeded;
646 boolean newSurface = false;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700647 boolean surfaceChanged = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800648 WindowManager.LayoutParams lp = mWindowAttributes;
649
650 int desiredWindowWidth;
651 int desiredWindowHeight;
652 int childWidthMeasureSpec;
653 int childHeightMeasureSpec;
654
655 final View.AttachInfo attachInfo = mAttachInfo;
656
657 final int viewVisibility = getHostVisibility();
658 boolean viewVisibilityChanged = mViewVisibility != viewVisibility
659 || mNewSurfaceNeeded;
660
661 WindowManager.LayoutParams params = null;
662 if (mWindowAttributesChanged) {
663 mWindowAttributesChanged = false;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700664 surfaceChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800665 params = lp;
666 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700667 Rect frame = mWinFrame;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800668 if (mFirst) {
669 fullRedrawNeeded = true;
670 mLayoutRequested = true;
671
Romain Guy8506ab42009-06-11 17:35:47 -0700672 DisplayMetrics packageMetrics =
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700673 mView.getContext().getResources().getDisplayMetrics();
674 desiredWindowWidth = packageMetrics.widthPixels;
675 desiredWindowHeight = packageMetrics.heightPixels;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800676
677 // For the very first time, tell the view hierarchy that it
678 // is attached to the window. Note that at this point the surface
679 // object is not initialized to its backing store, but soon it
680 // will be (assuming the window is visible).
681 attachInfo.mSurface = mSurface;
Adam Powell26153a32010-11-08 15:22:27 -0800682 attachInfo.mUse32BitDrawingCache = PixelFormat.formatHasAlpha(lp.format) ||
683 lp.format == PixelFormat.RGBX_8888;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800684 attachInfo.mHasWindowFocus = false;
685 attachInfo.mWindowVisibility = viewVisibility;
686 attachInfo.mRecomputeGlobalAttributes = false;
687 attachInfo.mKeepScreenOn = false;
688 viewVisibilityChanged = false;
Dianne Hackborn694f79b2010-03-17 19:44:59 -0700689 mLastConfiguration.setTo(host.getResources().getConfiguration());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800690 host.dispatchAttachedToWindow(attachInfo, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800691 //Log.i(TAG, "Screen on initialized: " + attachInfo.mKeepScreenOn);
svetoslavganov75986cf2009-05-14 22:28:01 -0700692
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800693 } else {
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700694 desiredWindowWidth = frame.width();
695 desiredWindowHeight = frame.height();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800696 if (desiredWindowWidth != mWidth || desiredWindowHeight != mHeight) {
Jeff Brownc5ed5912010-07-14 18:48:53 -0700697 if (DEBUG_ORIENTATION) Log.v(TAG,
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700698 "View " + host + " resized to: " + frame);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800699 fullRedrawNeeded = true;
700 mLayoutRequested = true;
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800701 windowSizeMayChange = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800702 }
703 }
704
705 if (viewVisibilityChanged) {
706 attachInfo.mWindowVisibility = viewVisibility;
707 host.dispatchWindowVisibilityChanged(viewVisibility);
708 if (viewVisibility != View.VISIBLE || mNewSurfaceNeeded) {
Romain Guyb051e892010-09-28 19:09:36 -0700709 if (mAttachInfo.mHardwareRenderer != null) {
710 mAttachInfo.mHardwareRenderer.destroy(false);
Romain Guy4caa4ed2010-08-25 14:46:24 -0700711 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800712 }
713 if (viewVisibility == View.GONE) {
714 // After making a window gone, we will count it as being
715 // shown for the first time the next time it gets focus.
716 mHasHadWindowFocus = false;
717 }
718 }
719
720 boolean insetsChanged = false;
Romain Guy8506ab42009-06-11 17:35:47 -0700721
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800722 if (mLayoutRequested) {
Romain Guy15df6702009-08-17 20:17:30 -0700723 // Execute enqueued actions on every layout in case a view that was detached
724 // enqueued an action after being detached
725 getRunQueue().executeActions(attachInfo.mHandler);
726
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800727 final Resources res = mView.getContext().getResources();
728
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800729 if (mFirst) {
730 host.fitSystemWindows(mAttachInfo.mContentInsets);
731 // make sure touch mode code executes by setting cached value
732 // to opposite of the added touch mode.
733 mAttachInfo.mInTouchMode = !mAddedTouchMode;
Romain Guy2d4cff62010-04-09 15:39:00 -0700734 ensureTouchModeLocally(mAddedTouchMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800735 } else {
736 if (!mAttachInfo.mContentInsets.equals(mPendingContentInsets)) {
737 mAttachInfo.mContentInsets.set(mPendingContentInsets);
738 host.fitSystemWindows(mAttachInfo.mContentInsets);
739 insetsChanged = true;
740 if (DEBUG_LAYOUT) Log.v(TAG, "Content insets changing to: "
741 + mAttachInfo.mContentInsets);
742 }
743 if (!mAttachInfo.mVisibleInsets.equals(mPendingVisibleInsets)) {
744 mAttachInfo.mVisibleInsets.set(mPendingVisibleInsets);
745 if (DEBUG_LAYOUT) Log.v(TAG, "Visible insets changing to: "
746 + mAttachInfo.mVisibleInsets);
747 }
748 if (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT
749 || lp.height == ViewGroup.LayoutParams.WRAP_CONTENT) {
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800750 windowSizeMayChange = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800751
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800752 DisplayMetrics packageMetrics = res.getDisplayMetrics();
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700753 desiredWindowWidth = packageMetrics.widthPixels;
754 desiredWindowHeight = packageMetrics.heightPixels;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800755 }
756 }
757
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800758 // Ask host how big it wants to be
Jeff Brownc5ed5912010-07-14 18:48:53 -0700759 if (DEBUG_ORIENTATION || DEBUG_LAYOUT) Log.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800760 "Measuring " + host + " in display " + desiredWindowWidth
761 + "x" + desiredWindowHeight + "...");
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800762
763 boolean goodMeasure = false;
764 if (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT
765 || lp.height == ViewGroup.LayoutParams.WRAP_CONTENT) {
766 // On large screens, we don't want to allow dialogs to just
767 // stretch to fill the entire width of the screen to display
768 // one line of text. First try doing the layout at a smaller
769 // size to see if it will fit.
770 final DisplayMetrics packageMetrics = res.getDisplayMetrics();
771 res.getValue(com.android.internal.R.dimen.config_prefDialogWidth, mTmpValue, true);
772 int baseSize = 0;
773 if (mTmpValue.type == TypedValue.TYPE_DIMENSION) {
774 baseSize = (int)mTmpValue.getDimension(packageMetrics);
775 }
776 if (DEBUG_DIALOG) Log.v(TAG, "Window " + mView + ": baseSize=" + baseSize);
Dianne Hackborn7d3a5bc2010-11-29 22:52:12 -0800777 if (baseSize != 0 && desiredWindowWidth > baseSize) {
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800778 int maxHeight = (desiredWindowHeight*2)/3;
779 childWidthMeasureSpec = getRootMeasureSpec(baseSize, lp.width);
780 childHeightMeasureSpec = getRootMeasureSpec(desiredWindowHeight, lp.height);
781 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
782 if (DEBUG_DIALOG) Log.v(TAG, "Window " + mView + ": measured ("
783 + host.getWidth() + "," + host.getHeight() + ")");
784 // Note: for now we are not taking into account height, since we
785 // can't distinguish between places where it would be useful to
786 // increase the width (text) vs. where it would not (a list).
787 // Maybe we can just try the next size up, and see if that reduces
788 // the height?
789 if (host.getWidth() <= baseSize /*&& host.getHeight() <= maxHeight*/) {
790 Log.v(TAG, "Good!");
791 goodMeasure = true;
792 } else {
793 // Didn't fit in that size... try expanding a bit.
794 baseSize = (baseSize+desiredWindowWidth)/2;
795 if (DEBUG_DIALOG) Log.v(TAG, "Window " + mView + ": next baseSize="
796 + baseSize);
797 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
798 if (DEBUG_DIALOG) Log.v(TAG, "Window " + mView + ": measured ("
799 + host.getWidth() + "," + host.getHeight() + ")");
800 if (host.getWidth() <= baseSize /*&& host.getHeight() <= maxHeight*/) {
801 if (DEBUG_DIALOG) Log.v(TAG, "Good!");
802 goodMeasure = true;
803 }
804 }
805 }
806 }
807
808 if (!goodMeasure) {
809 childWidthMeasureSpec = getRootMeasureSpec(desiredWindowWidth, lp.width);
810 childHeightMeasureSpec = getRootMeasureSpec(desiredWindowHeight, lp.height);
811 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
812 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800813
814 if (DBG) {
815 System.out.println("======================================");
816 System.out.println("performTraversals -- after measure");
817 host.debug();
818 }
819 }
820
821 if (attachInfo.mRecomputeGlobalAttributes) {
822 //Log.i(TAG, "Computing screen on!");
823 attachInfo.mRecomputeGlobalAttributes = false;
824 boolean oldVal = attachInfo.mKeepScreenOn;
825 attachInfo.mKeepScreenOn = false;
826 host.dispatchCollectViewAttributes(0);
827 if (attachInfo.mKeepScreenOn != oldVal) {
828 params = lp;
829 //Log.i(TAG, "Keep screen on changed: " + attachInfo.mKeepScreenOn);
830 }
831 }
832
833 if (mFirst || attachInfo.mViewVisibilityChanged) {
834 attachInfo.mViewVisibilityChanged = false;
835 int resizeMode = mSoftInputMode &
836 WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST;
837 // If we are in auto resize mode, then we need to determine
838 // what mode to use now.
839 if (resizeMode == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED) {
840 final int N = attachInfo.mScrollContainers.size();
841 for (int i=0; i<N; i++) {
842 if (attachInfo.mScrollContainers.get(i).isShown()) {
843 resizeMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE;
844 }
845 }
846 if (resizeMode == 0) {
847 resizeMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN;
848 }
849 if ((lp.softInputMode &
850 WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) != resizeMode) {
851 lp.softInputMode = (lp.softInputMode &
852 ~WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) |
853 resizeMode;
854 params = lp;
855 }
856 }
857 }
Romain Guy8506ab42009-06-11 17:35:47 -0700858
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800859 if (params != null && (host.mPrivateFlags & View.REQUEST_TRANSPARENT_REGIONS) != 0) {
860 if (!PixelFormat.formatHasAlpha(params.format)) {
861 params.format = PixelFormat.TRANSLUCENT;
862 }
863 }
864
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800865 boolean windowShouldResize = mLayoutRequested && windowSizeMayChange
Romain Guy2e4f4262010-04-06 11:07:52 -0700866 && ((mWidth != host.mMeasuredWidth || mHeight != host.mMeasuredHeight)
867 || (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT &&
868 frame.width() < desiredWindowWidth && frame.width() != mWidth)
869 || (lp.height == ViewGroup.LayoutParams.WRAP_CONTENT &&
870 frame.height() < desiredWindowHeight && frame.height() != mHeight));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800871
872 final boolean computesInternalInsets =
873 attachInfo.mTreeObserver.hasComputeInternalInsetsListeners();
Romain Guy812ccbe2010-06-01 14:07:24 -0700874
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800875 boolean insetsPending = false;
876 int relayoutResult = 0;
Romain Guy812ccbe2010-06-01 14:07:24 -0700877
878 if (mFirst || windowShouldResize || insetsChanged ||
879 viewVisibilityChanged || params != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800880
881 if (viewVisibility == View.VISIBLE) {
882 // If this window is giving internal insets to the window
883 // manager, and it is being added or changing its visibility,
884 // then we want to first give the window manager "fake"
885 // insets to cause it to effectively ignore the content of
886 // the window during layout. This avoids it briefly causing
887 // other windows to resize/move based on the raw frame of the
888 // window, waiting until we can finish laying out this window
889 // and get back to the window manager with the ultimately
890 // computed insets.
Romain Guy812ccbe2010-06-01 14:07:24 -0700891 insetsPending = computesInternalInsets && (mFirst || viewVisibilityChanged);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800892 }
893
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700894 if (mSurfaceHolder != null) {
895 mSurfaceHolder.mSurfaceLock.lock();
896 mDrawingAllowed = true;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700897 }
Romain Guy812ccbe2010-06-01 14:07:24 -0700898
Romain Guyc361da82010-10-25 15:29:10 -0700899 boolean hwInitialized = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800900 boolean contentInsetsChanged = false;
Romain Guy13922e02009-05-12 17:56:14 -0700901 boolean visibleInsetsChanged;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700902 boolean hadSurface = mSurface.isValid();
Romain Guy812ccbe2010-06-01 14:07:24 -0700903
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800904 try {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800905 int fl = 0;
906 if (params != null) {
907 fl = params.flags;
908 if (attachInfo.mKeepScreenOn) {
909 params.flags |= WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
910 }
911 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700912 if (DEBUG_LAYOUT) {
913 Log.i(TAG, "host=w:" + host.mMeasuredWidth + ", h:" +
914 host.mMeasuredHeight + ", params=" + params);
915 }
916 relayoutResult = relayoutWindow(params, viewVisibility, insetsPending);
917
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800918 if (params != null) {
919 params.flags = fl;
920 }
921
922 if (DEBUG_LAYOUT) Log.v(TAG, "relayout: frame=" + frame.toShortString()
923 + " content=" + mPendingContentInsets.toShortString()
924 + " visible=" + mPendingVisibleInsets.toShortString()
925 + " surface=" + mSurface);
Romain Guy8506ab42009-06-11 17:35:47 -0700926
Dianne Hackborn694f79b2010-03-17 19:44:59 -0700927 if (mPendingConfiguration.seq != 0) {
928 if (DEBUG_CONFIGURATION) Log.v(TAG, "Visible with new config: "
929 + mPendingConfiguration);
930 updateConfiguration(mPendingConfiguration, !mFirst);
931 mPendingConfiguration.seq = 0;
932 }
933
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800934 contentInsetsChanged = !mPendingContentInsets.equals(
935 mAttachInfo.mContentInsets);
936 visibleInsetsChanged = !mPendingVisibleInsets.equals(
937 mAttachInfo.mVisibleInsets);
938 if (contentInsetsChanged) {
939 mAttachInfo.mContentInsets.set(mPendingContentInsets);
940 host.fitSystemWindows(mAttachInfo.mContentInsets);
941 if (DEBUG_LAYOUT) Log.v(TAG, "Content insets changing to: "
942 + mAttachInfo.mContentInsets);
943 }
944 if (visibleInsetsChanged) {
945 mAttachInfo.mVisibleInsets.set(mPendingVisibleInsets);
946 if (DEBUG_LAYOUT) Log.v(TAG, "Visible insets changing to: "
947 + mAttachInfo.mVisibleInsets);
948 }
949
950 if (!hadSurface) {
951 if (mSurface.isValid()) {
952 // If we are creating a new surface, then we need to
953 // completely redraw it. Also, when we get to the
954 // point of drawing it we will hold off and schedule
955 // a new traversal instead. This is so we can tell the
956 // window manager about all of the windows being displayed
957 // before actually drawing them, so it can display then
958 // all at once.
959 newSurface = true;
960 fullRedrawNeeded = true;
Jack Palevich61a6e682009-10-09 17:37:50 -0700961 mPreviousTransparentRegion.setEmpty();
Romain Guy8506ab42009-06-11 17:35:47 -0700962
Romain Guyb051e892010-09-28 19:09:36 -0700963 if (mAttachInfo.mHardwareRenderer != null) {
Romain Guyc361da82010-10-25 15:29:10 -0700964 hwInitialized = mAttachInfo.mHardwareRenderer.initialize(mHolder);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800965 }
966 }
967 } else if (!mSurface.isValid()) {
968 // If the surface has been removed, then reset the scroll
969 // positions.
970 mLastScrolledFocus = null;
971 mScrollY = mCurScrollY = 0;
972 if (mScroller != null) {
973 mScroller.abortAnimation();
974 }
975 }
976 } catch (RemoteException e) {
977 }
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700978
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800979 if (DEBUG_ORIENTATION) Log.v(
Jeff Brownc5ed5912010-07-14 18:48:53 -0700980 TAG, "Relayout returned: frame=" + frame + ", surface=" + mSurface);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800981
982 attachInfo.mWindowLeft = frame.left;
983 attachInfo.mWindowTop = frame.top;
984
985 // !!FIXME!! This next section handles the case where we did not get the
986 // window size we asked for. We should avoid this by getting a maximum size from
987 // the window session beforehand.
988 mWidth = frame.width();
989 mHeight = frame.height();
990
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700991 if (mSurfaceHolder != null) {
992 // The app owns the surface; tell it about what is going on.
993 if (mSurface.isValid()) {
994 // XXX .copyFrom() doesn't work!
995 //mSurfaceHolder.mSurface.copyFrom(mSurface);
996 mSurfaceHolder.mSurface = mSurface;
997 }
998 mSurfaceHolder.mSurfaceLock.unlock();
999 if (mSurface.isValid()) {
1000 if (!hadSurface) {
1001 mSurfaceHolder.ungetCallbacks();
1002
1003 mIsCreating = true;
1004 mSurfaceHolderCallback.surfaceCreated(mSurfaceHolder);
1005 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
1006 if (callbacks != null) {
1007 for (SurfaceHolder.Callback c : callbacks) {
1008 c.surfaceCreated(mSurfaceHolder);
1009 }
1010 }
1011 surfaceChanged = true;
Romain Guyc361da82010-10-25 15:29:10 -07001012
1013 if (mAttachInfo.mHardwareRenderer != null) {
1014 // This will bail out early if already initialized
1015 mAttachInfo.mHardwareRenderer.initialize(mHolder);
1016 }
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001017 }
1018 if (surfaceChanged) {
1019 mSurfaceHolderCallback.surfaceChanged(mSurfaceHolder,
1020 lp.format, mWidth, mHeight);
1021 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
1022 if (callbacks != null) {
1023 for (SurfaceHolder.Callback c : callbacks) {
1024 c.surfaceChanged(mSurfaceHolder, lp.format,
1025 mWidth, mHeight);
1026 }
1027 }
1028 }
1029 mIsCreating = false;
1030 } else if (hadSurface) {
1031 mSurfaceHolder.ungetCallbacks();
1032 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
1033 mSurfaceHolderCallback.surfaceDestroyed(mSurfaceHolder);
1034 if (callbacks != null) {
1035 for (SurfaceHolder.Callback c : callbacks) {
1036 c.surfaceDestroyed(mSurfaceHolder);
1037 }
1038 }
1039 mSurfaceHolder.mSurfaceLock.lock();
1040 // Make surface invalid.
1041 //mSurfaceHolder.mSurface.copyFrom(mSurface);
1042 mSurfaceHolder.mSurface = new Surface();
1043 mSurfaceHolder.mSurfaceLock.unlock();
1044 }
1045 }
Romain Guy53389bd2010-09-07 17:16:32 -07001046
Romain Guyc361da82010-10-25 15:29:10 -07001047 if (hwInitialized || (windowShouldResize && mAttachInfo.mHardwareRenderer != null)) {
Romain Guyb051e892010-09-28 19:09:36 -07001048 mAttachInfo.mHardwareRenderer.setup(mWidth, mHeight);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001049 }
1050
1051 boolean focusChangedDueToTouchMode = ensureTouchModeLocally(
Romain Guy2d4cff62010-04-09 15:39:00 -07001052 (relayoutResult&WindowManagerImpl.RELAYOUT_IN_TOUCH_MODE) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001053 if (focusChangedDueToTouchMode || mWidth != host.mMeasuredWidth
1054 || mHeight != host.mMeasuredHeight || contentInsetsChanged) {
1055 childWidthMeasureSpec = getRootMeasureSpec(mWidth, lp.width);
1056 childHeightMeasureSpec = getRootMeasureSpec(mHeight, lp.height);
1057
1058 if (DEBUG_LAYOUT) Log.v(TAG, "Ooops, something changed! mWidth="
1059 + mWidth + " measuredWidth=" + host.mMeasuredWidth
1060 + " mHeight=" + mHeight
1061 + " measuredHeight" + host.mMeasuredHeight
1062 + " coveredInsetsChanged=" + contentInsetsChanged);
Romain Guy8506ab42009-06-11 17:35:47 -07001063
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001064 // Ask host how big it wants to be
1065 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
1066
1067 // Implementation of weights from WindowManager.LayoutParams
1068 // We just grow the dimensions as needed and re-measure if
1069 // needs be
1070 int width = host.mMeasuredWidth;
1071 int height = host.mMeasuredHeight;
1072 boolean measureAgain = false;
1073
1074 if (lp.horizontalWeight > 0.0f) {
1075 width += (int) ((mWidth - width) * lp.horizontalWeight);
1076 childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(width,
1077 MeasureSpec.EXACTLY);
1078 measureAgain = true;
1079 }
1080 if (lp.verticalWeight > 0.0f) {
1081 height += (int) ((mHeight - height) * lp.verticalWeight);
1082 childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(height,
1083 MeasureSpec.EXACTLY);
1084 measureAgain = true;
1085 }
1086
1087 if (measureAgain) {
1088 if (DEBUG_LAYOUT) Log.v(TAG,
1089 "And hey let's measure once more: width=" + width
1090 + " height=" + height);
1091 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
1092 }
1093
1094 mLayoutRequested = true;
1095 }
1096 }
1097
1098 final boolean didLayout = mLayoutRequested;
1099 boolean triggerGlobalLayoutListener = didLayout
1100 || attachInfo.mRecomputeGlobalAttributes;
1101 if (didLayout) {
1102 mLayoutRequested = false;
1103 mScrollMayChange = true;
1104 if (DEBUG_ORIENTATION || DEBUG_LAYOUT) Log.v(
Jeff Brownc5ed5912010-07-14 18:48:53 -07001105 TAG, "Laying out " + host + " to (" +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001106 host.mMeasuredWidth + ", " + host.mMeasuredHeight + ")");
Romain Guy13922e02009-05-12 17:56:14 -07001107 long startTime = 0L;
Romain Guy5429e1d2010-09-07 12:38:00 -07001108 if (ViewDebug.DEBUG_PROFILE_LAYOUT) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001109 startTime = SystemClock.elapsedRealtime();
1110 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001111 host.layout(0, 0, host.mMeasuredWidth, host.mMeasuredHeight);
1112
Romain Guy13922e02009-05-12 17:56:14 -07001113 if (Config.DEBUG && ViewDebug.consistencyCheckEnabled) {
1114 if (!host.dispatchConsistencyCheck(ViewDebug.CONSISTENCY_LAYOUT)) {
1115 throw new IllegalStateException("The view hierarchy is an inconsistent state,"
1116 + "please refer to the logs with the tag "
1117 + ViewDebug.CONSISTENCY_LOG_TAG + " for more infomation.");
1118 }
1119 }
1120
Romain Guy5429e1d2010-09-07 12:38:00 -07001121 if (ViewDebug.DEBUG_PROFILE_LAYOUT) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001122 EventLog.writeEvent(60001, SystemClock.elapsedRealtime() - startTime);
1123 }
1124
1125 // By this point all views have been sized and positionned
1126 // We can compute the transparent area
1127
1128 if ((host.mPrivateFlags & View.REQUEST_TRANSPARENT_REGIONS) != 0) {
1129 // start out transparent
1130 // TODO: AVOID THAT CALL BY CACHING THE RESULT?
1131 host.getLocationInWindow(mTmpLocation);
1132 mTransparentRegion.set(mTmpLocation[0], mTmpLocation[1],
1133 mTmpLocation[0] + host.mRight - host.mLeft,
1134 mTmpLocation[1] + host.mBottom - host.mTop);
1135
1136 host.gatherTransparentRegion(mTransparentRegion);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001137 if (mTranslator != null) {
1138 mTranslator.translateRegionInWindowToScreen(mTransparentRegion);
1139 }
1140
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001141 if (!mTransparentRegion.equals(mPreviousTransparentRegion)) {
1142 mPreviousTransparentRegion.set(mTransparentRegion);
1143 // reconfigure window manager
1144 try {
1145 sWindowSession.setTransparentRegion(mWindow, mTransparentRegion);
1146 } catch (RemoteException e) {
1147 }
1148 }
1149 }
1150
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001151 if (DBG) {
1152 System.out.println("======================================");
1153 System.out.println("performTraversals -- after setFrame");
1154 host.debug();
1155 }
1156 }
1157
1158 if (triggerGlobalLayoutListener) {
1159 attachInfo.mRecomputeGlobalAttributes = false;
1160 attachInfo.mTreeObserver.dispatchOnGlobalLayout();
1161 }
1162
1163 if (computesInternalInsets) {
1164 ViewTreeObserver.InternalInsetsInfo insets = attachInfo.mGivenInternalInsets;
1165 final Rect givenContent = attachInfo.mGivenInternalInsets.contentInsets;
1166 final Rect givenVisible = attachInfo.mGivenInternalInsets.visibleInsets;
1167 givenContent.left = givenContent.top = givenContent.right
1168 = givenContent.bottom = givenVisible.left = givenVisible.top
1169 = givenVisible.right = givenVisible.bottom = 0;
1170 attachInfo.mTreeObserver.dispatchOnComputeInternalInsets(insets);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001171 Rect contentInsets = insets.contentInsets;
1172 Rect visibleInsets = insets.visibleInsets;
1173 if (mTranslator != null) {
1174 contentInsets = mTranslator.getTranslatedContentInsets(contentInsets);
1175 visibleInsets = mTranslator.getTranslatedVisbileInsets(visibleInsets);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001176 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001177 if (insetsPending || !mLastGivenInsets.equals(insets)) {
1178 mLastGivenInsets.set(insets);
1179 try {
1180 sWindowSession.setInsets(mWindow, insets.mTouchableInsets,
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001181 contentInsets, visibleInsets);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001182 } catch (RemoteException e) {
1183 }
1184 }
1185 }
Romain Guy8506ab42009-06-11 17:35:47 -07001186
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001187 if (mFirst) {
1188 // handle first focus request
1189 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: mView.hasFocus()="
1190 + mView.hasFocus());
1191 if (mView != null) {
1192 if (!mView.hasFocus()) {
1193 mView.requestFocus(View.FOCUS_FORWARD);
1194 mFocusedView = mRealFocusedView = mView.findFocus();
1195 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: requested focused view="
1196 + mFocusedView);
1197 } else {
1198 mRealFocusedView = mView.findFocus();
1199 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: existing focused view="
1200 + mRealFocusedView);
1201 }
1202 }
1203 }
1204
1205 mFirst = false;
1206 mWillDrawSoon = false;
1207 mNewSurfaceNeeded = false;
1208 mViewVisibility = viewVisibility;
1209
1210 if (mAttachInfo.mHasWindowFocus) {
1211 final boolean imTarget = WindowManager.LayoutParams
1212 .mayUseInputMethod(mWindowAttributes.flags);
1213 if (imTarget != mLastWasImTarget) {
1214 mLastWasImTarget = imTarget;
1215 InputMethodManager imm = InputMethodManager.peekInstance();
1216 if (imm != null && imTarget) {
1217 imm.startGettingWindowFocus(mView);
1218 imm.onWindowFocus(mView, mView.findFocus(),
1219 mWindowAttributes.softInputMode,
1220 !mHasHadWindowFocus, mWindowAttributes.flags);
1221 }
1222 }
1223 }
Romain Guy8506ab42009-06-11 17:35:47 -07001224
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001225 boolean cancelDraw = attachInfo.mTreeObserver.dispatchOnPreDraw();
1226
1227 if (!cancelDraw && !newSurface) {
1228 mFullRedrawNeeded = false;
1229 draw(fullRedrawNeeded);
1230
1231 if ((relayoutResult&WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0
1232 || mReportNextDraw) {
1233 if (LOCAL_LOGV) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001234 Log.v(TAG, "FINISHED DRAWING: " + mWindowAttributes.getTitle());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001235 }
1236 mReportNextDraw = false;
Dianne Hackbornd76b67c2010-07-13 17:48:30 -07001237 if (mSurfaceHolder != null && mSurface.isValid()) {
1238 mSurfaceHolderCallback.surfaceRedrawNeeded(mSurfaceHolder);
1239 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
1240 if (callbacks != null) {
1241 for (SurfaceHolder.Callback c : callbacks) {
1242 if (c instanceof SurfaceHolder.Callback2) {
1243 ((SurfaceHolder.Callback2)c).surfaceRedrawNeeded(
1244 mSurfaceHolder);
1245 }
1246 }
1247 }
1248 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001249 try {
1250 sWindowSession.finishDrawing(mWindow);
1251 } catch (RemoteException e) {
1252 }
1253 }
1254 } else {
1255 // We were supposed to report when we are done drawing. Since we canceled the
1256 // draw, remember it here.
1257 if ((relayoutResult&WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0) {
1258 mReportNextDraw = true;
1259 }
1260 if (fullRedrawNeeded) {
1261 mFullRedrawNeeded = true;
1262 }
1263 // Try again
1264 scheduleTraversals();
1265 }
1266 }
1267
1268 public void requestTransparentRegion(View child) {
1269 // the test below should not fail unless someone is messing with us
1270 checkThread();
1271 if (mView == child) {
1272 mView.mPrivateFlags |= View.REQUEST_TRANSPARENT_REGIONS;
1273 // Need to make sure we re-evaluate the window attributes next
1274 // time around, to ensure the window has the correct format.
1275 mWindowAttributesChanged = true;
Mathias Agopian1bd80ad2010-11-04 17:13:39 -07001276 requestLayout();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001277 }
1278 }
1279
1280 /**
1281 * Figures out the measure spec for the root view in a window based on it's
1282 * layout params.
1283 *
1284 * @param windowSize
1285 * The available width or height of the window
1286 *
1287 * @param rootDimension
1288 * The layout params for one dimension (width or height) of the
1289 * window.
1290 *
1291 * @return The measure spec to use to measure the root view.
1292 */
1293 private int getRootMeasureSpec(int windowSize, int rootDimension) {
1294 int measureSpec;
1295 switch (rootDimension) {
1296
Romain Guy980a9382010-01-08 15:06:28 -08001297 case ViewGroup.LayoutParams.MATCH_PARENT:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001298 // Window can't resize. Force root view to be windowSize.
1299 measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.EXACTLY);
1300 break;
1301 case ViewGroup.LayoutParams.WRAP_CONTENT:
1302 // Window can resize. Set max size for root view.
1303 measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.AT_MOST);
1304 break;
1305 default:
1306 // Window wants to be an exact size. Force root view to be that size.
1307 measureSpec = MeasureSpec.makeMeasureSpec(rootDimension, MeasureSpec.EXACTLY);
1308 break;
1309 }
1310 return measureSpec;
1311 }
1312
1313 private void draw(boolean fullRedrawNeeded) {
1314 Surface surface = mSurface;
1315 if (surface == null || !surface.isValid()) {
1316 return;
1317 }
1318
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001319 if (!sFirstDrawComplete) {
1320 synchronized (sFirstDrawHandlers) {
1321 sFirstDrawComplete = true;
Romain Guy812ccbe2010-06-01 14:07:24 -07001322 final int count = sFirstDrawHandlers.size();
1323 for (int i = 0; i< count; i++) {
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001324 post(sFirstDrawHandlers.get(i));
1325 }
1326 }
1327 }
1328
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001329 scrollToRectOrFocus(null, false);
1330
1331 if (mAttachInfo.mViewScrollChanged) {
1332 mAttachInfo.mViewScrollChanged = false;
1333 mAttachInfo.mTreeObserver.dispatchOnScrollChanged();
1334 }
Romain Guy8506ab42009-06-11 17:35:47 -07001335
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001336 int yoff;
Romain Guy5bcdff42009-05-14 21:27:18 -07001337 final boolean scrolling = mScroller != null && mScroller.computeScrollOffset();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001338 if (scrolling) {
1339 yoff = mScroller.getCurrY();
1340 } else {
1341 yoff = mScrollY;
1342 }
1343 if (mCurScrollY != yoff) {
1344 mCurScrollY = yoff;
1345 fullRedrawNeeded = true;
1346 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001347 float appScale = mAttachInfo.mApplicationScale;
1348 boolean scalingRequired = mAttachInfo.mScalingRequired;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001349
1350 Rect dirty = mDirty;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001351 if (mSurfaceHolder != null) {
1352 // The app owns the surface, we won't draw.
1353 dirty.setEmpty();
1354 return;
1355 }
Romain Guy58ef7fb2010-09-13 12:52:37 -07001356
1357 if (fullRedrawNeeded) {
1358 mAttachInfo.mIgnoreDirtyState = true;
1359 dirty.union(0, 0, (int) (mWidth * appScale + 0.5f), (int) (mHeight * appScale + 0.5f));
1360 }
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001361
Romain Guyb051e892010-09-28 19:09:36 -07001362 if (mAttachInfo.mHardwareRenderer != null && mAttachInfo.mHardwareRenderer.isEnabled()) {
Romain Guyfd507262010-10-10 15:42:49 -07001363 if (!dirty.isEmpty() || mIsAnimating) {
Romain Guy101e2ae2010-10-11 12:41:21 -07001364 mIsAnimating = false;
Romain Guyfd507262010-10-10 15:42:49 -07001365 dirty.setEmpty();
Romain Guy101e2ae2010-10-11 12:41:21 -07001366 mAttachInfo.mHardwareRenderer.draw(mView, mAttachInfo, yoff);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001367 }
Romain Guy812ccbe2010-06-01 14:07:24 -07001368
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001369 if (scrolling) {
1370 mFullRedrawNeeded = true;
1371 scheduleTraversals();
1372 }
Romain Guy812ccbe2010-06-01 14:07:24 -07001373
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001374 return;
1375 }
1376
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001377 if (DEBUG_ORIENTATION || DEBUG_DRAW) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001378 Log.v(TAG, "Draw " + mView + "/"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001379 + mWindowAttributes.getTitle()
1380 + ": dirty={" + dirty.left + "," + dirty.top
1381 + "," + dirty.right + "," + dirty.bottom + "} surface="
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001382 + surface + " surface.isValid()=" + surface.isValid() + ", appScale:" +
1383 appScale + ", width=" + mWidth + ", height=" + mHeight);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001384 }
1385
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001386 if (!dirty.isEmpty() || mIsAnimating) {
1387 Canvas canvas;
1388 try {
1389 int left = dirty.left;
1390 int top = dirty.top;
1391 int right = dirty.right;
1392 int bottom = dirty.bottom;
1393 canvas = surface.lockCanvas(dirty);
Romain Guy5bcdff42009-05-14 21:27:18 -07001394
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001395 if (left != dirty.left || top != dirty.top || right != dirty.right ||
1396 bottom != dirty.bottom) {
1397 mAttachInfo.mIgnoreDirtyState = true;
1398 }
1399
1400 // TODO: Do this in native
1401 canvas.setDensity(mDensity);
1402 } catch (Surface.OutOfResourcesException e) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001403 Log.e(TAG, "OutOfResourcesException locking surface", e);
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001404 // TODO: we should ask the window manager to do something!
1405 // for now we just do nothing
1406 return;
1407 } catch (IllegalArgumentException e) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001408 Log.e(TAG, "IllegalArgumentException locking surface", e);
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001409 // TODO: we should ask the window manager to do something!
1410 // for now we just do nothing
1411 return;
Romain Guy5bcdff42009-05-14 21:27:18 -07001412 }
1413
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001414 try {
1415 if (!dirty.isEmpty() || mIsAnimating) {
1416 long startTime = 0L;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001417
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001418 if (DEBUG_ORIENTATION || DEBUG_DRAW) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001419 Log.v(TAG, "Surface " + surface + " drawing to bitmap w="
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001420 + canvas.getWidth() + ", h=" + canvas.getHeight());
1421 //canvas.drawARGB(255, 255, 0, 0);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001422 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001423
Romain Guy5429e1d2010-09-07 12:38:00 -07001424 if (ViewDebug.DEBUG_PROFILE_DRAWING) {
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001425 startTime = SystemClock.elapsedRealtime();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001426 }
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001427
1428 // If this bitmap's format includes an alpha channel, we
1429 // need to clear it before drawing so that the child will
1430 // properly re-composite its drawing on a transparent
1431 // background. This automatically respects the clip/dirty region
1432 // or
1433 // If we are applying an offset, we need to clear the area
1434 // where the offset doesn't appear to avoid having garbage
1435 // left in the blank areas.
1436 if (!canvas.isOpaque() || yoff != 0) {
1437 canvas.drawColor(0, PorterDuff.Mode.CLEAR);
1438 }
1439
1440 dirty.setEmpty();
1441 mIsAnimating = false;
1442 mAttachInfo.mDrawingTime = SystemClock.uptimeMillis();
1443 mView.mPrivateFlags |= View.DRAWN;
1444
1445 if (DEBUG_DRAW) {
1446 Context cxt = mView.getContext();
1447 Log.i(TAG, "Drawing: package:" + cxt.getPackageName() +
1448 ", metrics=" + cxt.getResources().getDisplayMetrics() +
1449 ", compatibilityInfo=" + cxt.getResources().getCompatibilityInfo());
1450 }
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001451 try {
1452 canvas.translate(0, -yoff);
1453 if (mTranslator != null) {
1454 mTranslator.translateCanvas(canvas);
1455 }
1456 canvas.setScreenDensity(scalingRequired
1457 ? DisplayMetrics.DENSITY_DEVICE : 0);
1458 mView.draw(canvas);
1459 } finally {
1460 mAttachInfo.mIgnoreDirtyState = false;
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001461 }
1462
1463 if (Config.DEBUG && ViewDebug.consistencyCheckEnabled) {
1464 mView.dispatchConsistencyCheck(ViewDebug.CONSISTENCY_DRAWING);
1465 }
1466
Romain Guy5429e1d2010-09-07 12:38:00 -07001467 if (SHOW_FPS || ViewDebug.DEBUG_SHOW_FPS) {
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001468 int now = (int)SystemClock.elapsedRealtime();
1469 if (sDrawTime != 0) {
1470 nativeShowFPS(canvas, now - sDrawTime);
1471 }
1472 sDrawTime = now;
1473 }
1474
Romain Guy5429e1d2010-09-07 12:38:00 -07001475 if (ViewDebug.DEBUG_PROFILE_DRAWING) {
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001476 EventLog.writeEvent(60000, SystemClock.elapsedRealtime() - startTime);
1477 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001478 }
1479
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001480 } finally {
1481 surface.unlockCanvasAndPost(canvas);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001482 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001483 }
1484
1485 if (LOCAL_LOGV) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001486 Log.v(TAG, "Surface " + surface + " unlockCanvasAndPost");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001487 }
Romain Guy8506ab42009-06-11 17:35:47 -07001488
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001489 if (scrolling) {
1490 mFullRedrawNeeded = true;
1491 scheduleTraversals();
1492 }
1493 }
1494
1495 boolean scrollToRectOrFocus(Rect rectangle, boolean immediate) {
1496 final View.AttachInfo attachInfo = mAttachInfo;
1497 final Rect ci = attachInfo.mContentInsets;
1498 final Rect vi = attachInfo.mVisibleInsets;
1499 int scrollY = 0;
1500 boolean handled = false;
Romain Guy8506ab42009-06-11 17:35:47 -07001501
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001502 if (vi.left > ci.left || vi.top > ci.top
1503 || vi.right > ci.right || vi.bottom > ci.bottom) {
1504 // We'll assume that we aren't going to change the scroll
1505 // offset, since we want to avoid that unless it is actually
1506 // going to make the focus visible... otherwise we scroll
1507 // all over the place.
1508 scrollY = mScrollY;
1509 // We can be called for two different situations: during a draw,
1510 // to update the scroll position if the focus has changed (in which
1511 // case 'rectangle' is null), or in response to a
1512 // requestChildRectangleOnScreen() call (in which case 'rectangle'
1513 // is non-null and we just want to scroll to whatever that
1514 // rectangle is).
1515 View focus = mRealFocusedView;
Romain Guye8b16522009-07-14 13:06:42 -07001516
1517 // When in touch mode, focus points to the previously focused view,
1518 // which may have been removed from the view hierarchy. The following
Joe Onoratob71193b2009-11-24 18:34:42 -05001519 // line checks whether the view is still in our hierarchy.
1520 if (focus == null || focus.mAttachInfo != mAttachInfo) {
Romain Guye8b16522009-07-14 13:06:42 -07001521 mRealFocusedView = null;
1522 return false;
1523 }
1524
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001525 if (focus != mLastScrolledFocus) {
1526 // If the focus has changed, then ignore any requests to scroll
1527 // to a rectangle; first we want to make sure the entire focus
1528 // view is visible.
1529 rectangle = null;
1530 }
1531 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Eval scroll: focus=" + focus
1532 + " rectangle=" + rectangle + " ci=" + ci
1533 + " vi=" + vi);
1534 if (focus == mLastScrolledFocus && !mScrollMayChange
1535 && rectangle == null) {
1536 // Optimization: if the focus hasn't changed since last
1537 // time, and no layout has happened, then just leave things
1538 // as they are.
1539 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Keeping scroll y="
1540 + mScrollY + " vi=" + vi.toShortString());
1541 } else if (focus != null) {
1542 // We need to determine if the currently focused view is
1543 // within the visible part of the window and, if not, apply
1544 // a pan so it can be seen.
1545 mLastScrolledFocus = focus;
1546 mScrollMayChange = false;
1547 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Need to scroll?");
1548 // Try to find the rectangle from the focus view.
1549 if (focus.getGlobalVisibleRect(mVisRect, null)) {
1550 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Root w="
1551 + mView.getWidth() + " h=" + mView.getHeight()
1552 + " ci=" + ci.toShortString()
1553 + " vi=" + vi.toShortString());
1554 if (rectangle == null) {
1555 focus.getFocusedRect(mTempRect);
1556 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Focus " + focus
1557 + ": focusRect=" + mTempRect.toShortString());
Dianne Hackborn1c6a8942010-03-23 16:34:20 -07001558 if (mView instanceof ViewGroup) {
1559 ((ViewGroup) mView).offsetDescendantRectToMyCoords(
1560 focus, mTempRect);
1561 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001562 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1563 "Focus in window: focusRect="
1564 + mTempRect.toShortString()
1565 + " visRect=" + mVisRect.toShortString());
1566 } else {
1567 mTempRect.set(rectangle);
1568 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1569 "Request scroll to rect: "
1570 + mTempRect.toShortString()
1571 + " visRect=" + mVisRect.toShortString());
1572 }
1573 if (mTempRect.intersect(mVisRect)) {
1574 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1575 "Focus window visible rect: "
1576 + mTempRect.toShortString());
1577 if (mTempRect.height() >
1578 (mView.getHeight()-vi.top-vi.bottom)) {
1579 // If the focus simply is not going to fit, then
1580 // best is probably just to leave things as-is.
1581 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1582 "Too tall; leaving scrollY=" + scrollY);
1583 } else if ((mTempRect.top-scrollY) < vi.top) {
1584 scrollY -= vi.top - (mTempRect.top-scrollY);
1585 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1586 "Top covered; scrollY=" + scrollY);
1587 } else if ((mTempRect.bottom-scrollY)
1588 > (mView.getHeight()-vi.bottom)) {
1589 scrollY += (mTempRect.bottom-scrollY)
1590 - (mView.getHeight()-vi.bottom);
1591 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1592 "Bottom covered; scrollY=" + scrollY);
1593 }
1594 handled = true;
1595 }
1596 }
1597 }
1598 }
Romain Guy8506ab42009-06-11 17:35:47 -07001599
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001600 if (scrollY != mScrollY) {
1601 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Pan scroll changed: old="
1602 + mScrollY + " , new=" + scrollY);
1603 if (!immediate) {
1604 if (mScroller == null) {
1605 mScroller = new Scroller(mView.getContext());
1606 }
1607 mScroller.startScroll(0, mScrollY, 0, scrollY-mScrollY);
1608 } else if (mScroller != null) {
1609 mScroller.abortAnimation();
1610 }
1611 mScrollY = scrollY;
1612 }
Romain Guy8506ab42009-06-11 17:35:47 -07001613
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001614 return handled;
1615 }
Romain Guy8506ab42009-06-11 17:35:47 -07001616
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001617 public void requestChildFocus(View child, View focused) {
1618 checkThread();
1619 if (mFocusedView != focused) {
1620 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(mFocusedView, focused);
1621 scheduleTraversals();
1622 }
1623 mFocusedView = mRealFocusedView = focused;
1624 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Request child focus: focus now "
1625 + mFocusedView);
1626 }
1627
1628 public void clearChildFocus(View child) {
1629 checkThread();
1630
1631 View oldFocus = mFocusedView;
1632
1633 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Clearing child focus");
1634 mFocusedView = mRealFocusedView = null;
1635 if (mView != null && !mView.hasFocus()) {
1636 // If a view gets the focus, the listener will be invoked from requestChildFocus()
1637 if (!mView.requestFocus(View.FOCUS_FORWARD)) {
1638 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
1639 }
1640 } else if (oldFocus != null) {
1641 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
1642 }
1643 }
1644
1645
1646 public void focusableViewAvailable(View v) {
1647 checkThread();
1648
1649 if (mView != null && !mView.hasFocus()) {
1650 v.requestFocus();
1651 } else {
1652 // the one case where will transfer focus away from the current one
1653 // is if the current view is a view group that prefers to give focus
1654 // to its children first AND the view is a descendant of it.
1655 mFocusedView = mView.findFocus();
1656 boolean descendantsHaveDibsOnFocus =
1657 (mFocusedView instanceof ViewGroup) &&
1658 (((ViewGroup) mFocusedView).getDescendantFocusability() ==
1659 ViewGroup.FOCUS_AFTER_DESCENDANTS);
1660 if (descendantsHaveDibsOnFocus && isViewDescendantOf(v, mFocusedView)) {
1661 // If a view gets the focus, the listener will be invoked from requestChildFocus()
1662 v.requestFocus();
1663 }
1664 }
1665 }
1666
1667 public void recomputeViewAttributes(View child) {
1668 checkThread();
1669 if (mView == child) {
1670 mAttachInfo.mRecomputeGlobalAttributes = true;
1671 if (!mWillDrawSoon) {
1672 scheduleTraversals();
1673 }
1674 }
1675 }
1676
1677 void dispatchDetachedFromWindow() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001678 if (mView != null) {
1679 mView.dispatchDetachedFromWindow();
1680 }
1681
1682 mView = null;
1683 mAttachInfo.mRootView = null;
Mathias Agopian5583dc62009-07-09 16:28:11 -07001684 mAttachInfo.mSurface = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001685
Romain Guy29d89972010-09-22 16:10:57 -07001686 destroyHardwareRenderer();
Romain Guy4caa4ed2010-08-25 14:46:24 -07001687
Dianne Hackborn0586a1b2009-09-06 21:08:27 -07001688 mSurface.release();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001689
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001690 if (mInputChannel != null) {
1691 if (mInputQueueCallback != null) {
1692 mInputQueueCallback.onInputQueueDestroyed(mInputQueue);
1693 mInputQueueCallback = null;
1694 } else {
1695 InputQueue.unregisterInputChannel(mInputChannel);
Jeff Brown46b9ac02010-04-22 18:58:52 -07001696 }
1697 }
1698
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001699 try {
1700 sWindowSession.remove(mWindow);
1701 } catch (RemoteException e) {
1702 }
Jeff Brown349703e2010-06-22 01:27:15 -07001703
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001704 // Dispose the input channel after removing the window so the Window Manager
1705 // doesn't interpret the input channel being closed as an abnormal termination.
1706 if (mInputChannel != null) {
1707 mInputChannel.dispose();
1708 mInputChannel = null;
Jeff Brown349703e2010-06-22 01:27:15 -07001709 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001710 }
Romain Guy8506ab42009-06-11 17:35:47 -07001711
Dianne Hackborn694f79b2010-03-17 19:44:59 -07001712 void updateConfiguration(Configuration config, boolean force) {
1713 if (DEBUG_CONFIGURATION) Log.v(TAG,
1714 "Applying new config to window "
1715 + mWindowAttributes.getTitle()
1716 + ": " + config);
1717 synchronized (sConfigCallbacks) {
1718 for (int i=sConfigCallbacks.size()-1; i>=0; i--) {
1719 sConfigCallbacks.get(i).onConfigurationChanged(config);
1720 }
1721 }
1722 if (mView != null) {
1723 // At this point the resources have been updated to
1724 // have the most recent config, whatever that is. Use
1725 // the on in them which may be newer.
1726 if (mView != null) {
1727 config = mView.getResources().getConfiguration();
1728 }
1729 if (force || mLastConfiguration.diff(config) != 0) {
1730 mLastConfiguration.setTo(config);
1731 mView.dispatchConfigurationChanged(config);
1732 }
1733 }
1734 }
1735
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001736 /**
1737 * Return true if child is an ancestor of parent, (or equal to the parent).
1738 */
1739 private static boolean isViewDescendantOf(View child, View parent) {
1740 if (child == parent) {
1741 return true;
1742 }
1743
1744 final ViewParent theParent = child.getParent();
1745 return (theParent instanceof ViewGroup) && isViewDescendantOf((View) theParent, parent);
1746 }
1747
Romain Guycdb86672010-03-18 18:54:50 -07001748 private static void forceLayout(View view) {
1749 view.forceLayout();
1750 if (view instanceof ViewGroup) {
1751 ViewGroup group = (ViewGroup) view;
1752 final int count = group.getChildCount();
1753 for (int i = 0; i < count; i++) {
1754 forceLayout(group.getChildAt(i));
1755 }
1756 }
1757 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001758
1759 public final static int DO_TRAVERSAL = 1000;
1760 public final static int DIE = 1001;
1761 public final static int RESIZED = 1002;
1762 public final static int RESIZED_REPORT = 1003;
1763 public final static int WINDOW_FOCUS_CHANGED = 1004;
1764 public final static int DISPATCH_KEY = 1005;
1765 public final static int DISPATCH_POINTER = 1006;
1766 public final static int DISPATCH_TRACKBALL = 1007;
1767 public final static int DISPATCH_APP_VISIBILITY = 1008;
1768 public final static int DISPATCH_GET_NEW_SURFACE = 1009;
1769 public final static int FINISHED_EVENT = 1010;
1770 public final static int DISPATCH_KEY_FROM_IME = 1011;
1771 public final static int FINISH_INPUT_CONNECTION = 1012;
1772 public final static int CHECK_FOCUS = 1013;
Dianne Hackbornffa42482009-09-23 22:20:11 -07001773 public final static int CLOSE_SYSTEM_DIALOGS = 1014;
Christopher Tatea53146c2010-09-07 11:57:52 -07001774 public final static int DISPATCH_DRAG_EVENT = 1015;
Chris Tate91e9bb32010-10-12 12:58:43 -07001775 public final static int DISPATCH_DRAG_LOCATION_EVENT = 1016;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001776
1777 @Override
1778 public void handleMessage(Message msg) {
1779 switch (msg.what) {
1780 case View.AttachInfo.INVALIDATE_MSG:
1781 ((View) msg.obj).invalidate();
1782 break;
1783 case View.AttachInfo.INVALIDATE_RECT_MSG:
1784 final View.AttachInfo.InvalidateInfo info = (View.AttachInfo.InvalidateInfo) msg.obj;
1785 info.target.invalidate(info.left, info.top, info.right, info.bottom);
1786 info.release();
1787 break;
1788 case DO_TRAVERSAL:
1789 if (mProfile) {
1790 Debug.startMethodTracing("ViewRoot");
1791 }
1792
1793 performTraversals();
1794
1795 if (mProfile) {
1796 Debug.stopMethodTracing();
1797 mProfile = false;
1798 }
1799 break;
1800 case FINISHED_EVENT:
1801 handleFinishedEvent(msg.arg1, msg.arg2 != 0);
1802 break;
1803 case DISPATCH_KEY:
Jeff Brown92ff1dd2010-08-11 16:16:06 -07001804 deliverKeyEvent((KeyEvent)msg.obj, msg.arg1 != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001805 break;
Jeff Brown3915bb82010-11-05 15:02:16 -07001806 case DISPATCH_POINTER:
1807 deliverPointerEvent((MotionEvent) msg.obj, msg.arg1 != 0);
1808 break;
1809 case DISPATCH_TRACKBALL:
1810 deliverTrackballEvent((MotionEvent) msg.obj, msg.arg1 != 0);
1811 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001812 case DISPATCH_APP_VISIBILITY:
1813 handleAppVisibility(msg.arg1 != 0);
1814 break;
1815 case DISPATCH_GET_NEW_SURFACE:
1816 handleGetNewSurface();
1817 break;
1818 case RESIZED:
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001819 ResizedInfo ri = (ResizedInfo)msg.obj;
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001820
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001821 if (mWinFrame.width() == msg.arg1 && mWinFrame.height() == msg.arg2
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001822 && mPendingContentInsets.equals(ri.coveredInsets)
Dianne Hackbornd49258f2010-03-26 00:44:29 -07001823 && mPendingVisibleInsets.equals(ri.visibleInsets)
1824 && ((ResizedInfo)msg.obj).newConfig == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001825 break;
1826 }
1827 // fall through...
1828 case RESIZED_REPORT:
1829 if (mAdded) {
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001830 Configuration config = ((ResizedInfo)msg.obj).newConfig;
1831 if (config != null) {
Dianne Hackborn694f79b2010-03-17 19:44:59 -07001832 updateConfiguration(config, false);
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001833 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001834 mWinFrame.left = 0;
1835 mWinFrame.right = msg.arg1;
1836 mWinFrame.top = 0;
1837 mWinFrame.bottom = msg.arg2;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001838 mPendingContentInsets.set(((ResizedInfo)msg.obj).coveredInsets);
1839 mPendingVisibleInsets.set(((ResizedInfo)msg.obj).visibleInsets);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001840 if (msg.what == RESIZED_REPORT) {
1841 mReportNextDraw = true;
1842 }
Romain Guycdb86672010-03-18 18:54:50 -07001843
1844 if (mView != null) {
1845 forceLayout(mView);
1846 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001847 requestLayout();
1848 }
1849 break;
1850 case WINDOW_FOCUS_CHANGED: {
1851 if (mAdded) {
1852 boolean hasWindowFocus = msg.arg1 != 0;
1853 mAttachInfo.mHasWindowFocus = hasWindowFocus;
1854 if (hasWindowFocus) {
1855 boolean inTouchMode = msg.arg2 != 0;
Romain Guy2d4cff62010-04-09 15:39:00 -07001856 ensureTouchModeLocally(inTouchMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001857
Romain Guyc361da82010-10-25 15:29:10 -07001858 if (mAttachInfo.mHardwareRenderer != null &&
1859 mSurface != null && mSurface.isValid()) {
Romain Guyb051e892010-09-28 19:09:36 -07001860 mAttachInfo.mHardwareRenderer.initializeIfNeeded(mWidth, mHeight,
1861 mAttachInfo, mHolder);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001862 }
1863 }
Romain Guy8506ab42009-06-11 17:35:47 -07001864
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001865 mLastWasImTarget = WindowManager.LayoutParams
1866 .mayUseInputMethod(mWindowAttributes.flags);
Romain Guy8506ab42009-06-11 17:35:47 -07001867
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001868 InputMethodManager imm = InputMethodManager.peekInstance();
1869 if (mView != null) {
1870 if (hasWindowFocus && imm != null && mLastWasImTarget) {
1871 imm.startGettingWindowFocus(mView);
1872 }
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07001873 mAttachInfo.mKeyDispatchState.reset();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001874 mView.dispatchWindowFocusChanged(hasWindowFocus);
1875 }
svetoslavganov75986cf2009-05-14 22:28:01 -07001876
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001877 // Note: must be done after the focus change callbacks,
1878 // so all of the view state is set up correctly.
1879 if (hasWindowFocus) {
1880 if (imm != null && mLastWasImTarget) {
1881 imm.onWindowFocus(mView, mView.findFocus(),
1882 mWindowAttributes.softInputMode,
1883 !mHasHadWindowFocus, mWindowAttributes.flags);
1884 }
1885 // Clear the forward bit. We can just do this directly, since
1886 // the window manager doesn't care about it.
1887 mWindowAttributes.softInputMode &=
1888 ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
1889 ((WindowManager.LayoutParams)mView.getLayoutParams())
1890 .softInputMode &=
1891 ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
1892 mHasHadWindowFocus = true;
1893 }
svetoslavganov75986cf2009-05-14 22:28:01 -07001894
1895 if (hasWindowFocus && mView != null) {
1896 sendAccessibilityEvents();
1897 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001898 }
1899 } break;
1900 case DIE:
Dianne Hackborn94d69142009-09-28 22:14:42 -07001901 doDie();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001902 break;
The Android Open Source Project10592532009-03-18 17:39:46 -07001903 case DISPATCH_KEY_FROM_IME: {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001904 if (LOCAL_LOGV) Log.v(
Jeff Brownc5ed5912010-07-14 18:48:53 -07001905 TAG, "Dispatching key "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001906 + msg.obj + " from IME to " + mView);
The Android Open Source Project10592532009-03-18 17:39:46 -07001907 KeyEvent event = (KeyEvent)msg.obj;
1908 if ((event.getFlags()&KeyEvent.FLAG_FROM_SYSTEM) != 0) {
1909 // The IME is trying to say this event is from the
1910 // system! Bad bad bad!
Romain Guy812ccbe2010-06-01 14:07:24 -07001911 event = KeyEvent.changeFlags(event, event.getFlags() & ~KeyEvent.FLAG_FROM_SYSTEM);
The Android Open Source Project10592532009-03-18 17:39:46 -07001912 }
Jeff Brown3915bb82010-11-05 15:02:16 -07001913 deliverKeyEventPostIme((KeyEvent)msg.obj, false);
The Android Open Source Project10592532009-03-18 17:39:46 -07001914 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001915 case FINISH_INPUT_CONNECTION: {
1916 InputMethodManager imm = InputMethodManager.peekInstance();
1917 if (imm != null) {
1918 imm.reportFinishInputConnection((InputConnection)msg.obj);
1919 }
1920 } break;
1921 case CHECK_FOCUS: {
1922 InputMethodManager imm = InputMethodManager.peekInstance();
1923 if (imm != null) {
1924 imm.checkFocus();
1925 }
1926 } break;
Dianne Hackbornffa42482009-09-23 22:20:11 -07001927 case CLOSE_SYSTEM_DIALOGS: {
1928 if (mView != null) {
1929 mView.onCloseSystemDialogs((String)msg.obj);
1930 }
1931 } break;
Chris Tate91e9bb32010-10-12 12:58:43 -07001932 case DISPATCH_DRAG_EVENT:
1933 case DISPATCH_DRAG_LOCATION_EVENT: {
Christopher Tatea53146c2010-09-07 11:57:52 -07001934 handleDragEvent((DragEvent)msg.obj);
1935 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001936 }
1937 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07001938
Jeff Brown3915bb82010-11-05 15:02:16 -07001939 private void startInputEvent(InputQueue.FinishedCallback finishedCallback) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07001940 if (mFinishedCallback != null) {
1941 Slog.w(TAG, "Received a new input event from the input queue but there is "
1942 + "already an unfinished input event in progress.");
1943 }
1944
1945 mFinishedCallback = finishedCallback;
1946 }
1947
Jeff Brown3915bb82010-11-05 15:02:16 -07001948 private void finishInputEvent(boolean handled) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07001949 if (LOCAL_LOGV) Log.v(TAG, "Telling window manager input event is finished");
Jeff Brown92ff1dd2010-08-11 16:16:06 -07001950
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001951 if (mFinishedCallback != null) {
Jeff Brown3915bb82010-11-05 15:02:16 -07001952 mFinishedCallback.finished(handled);
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001953 mFinishedCallback = null;
Jeff Brown92ff1dd2010-08-11 16:16:06 -07001954 } else {
Jeff Brown93ed4e32010-09-23 13:51:48 -07001955 Slog.w(TAG, "Attempted to tell the input queue that the current input event "
1956 + "is finished but there is no input event actually in progress.");
Jeff Brown46b9ac02010-04-22 18:58:52 -07001957 }
1958 }
1959
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001960 /**
1961 * Something in the current window tells us we need to change the touch mode. For
1962 * example, we are not in touch mode, and the user touches the screen.
1963 *
1964 * If the touch mode has changed, tell the window manager, and handle it locally.
1965 *
1966 * @param inTouchMode Whether we want to be in touch mode.
1967 * @return True if the touch mode changed and focus changed was changed as a result
1968 */
1969 boolean ensureTouchMode(boolean inTouchMode) {
1970 if (DBG) Log.d("touchmode", "ensureTouchMode(" + inTouchMode + "), current "
1971 + "touch mode is " + mAttachInfo.mInTouchMode);
1972 if (mAttachInfo.mInTouchMode == inTouchMode) return false;
1973
1974 // tell the window manager
1975 try {
1976 sWindowSession.setInTouchMode(inTouchMode);
1977 } catch (RemoteException e) {
1978 throw new RuntimeException(e);
1979 }
1980
1981 // handle the change
Romain Guy2d4cff62010-04-09 15:39:00 -07001982 return ensureTouchModeLocally(inTouchMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001983 }
1984
1985 /**
1986 * Ensure that the touch mode for this window is set, and if it is changing,
1987 * take the appropriate action.
1988 * @param inTouchMode Whether we want to be in touch mode.
1989 * @return True if the touch mode changed and focus changed was changed as a result
1990 */
Romain Guy2d4cff62010-04-09 15:39:00 -07001991 private boolean ensureTouchModeLocally(boolean inTouchMode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001992 if (DBG) Log.d("touchmode", "ensureTouchModeLocally(" + inTouchMode + "), current "
1993 + "touch mode is " + mAttachInfo.mInTouchMode);
1994
1995 if (mAttachInfo.mInTouchMode == inTouchMode) return false;
1996
1997 mAttachInfo.mInTouchMode = inTouchMode;
1998 mAttachInfo.mTreeObserver.dispatchOnTouchModeChanged(inTouchMode);
1999
Romain Guy2d4cff62010-04-09 15:39:00 -07002000 return (inTouchMode) ? enterTouchMode() : leaveTouchMode();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002001 }
2002
2003 private boolean enterTouchMode() {
2004 if (mView != null) {
2005 if (mView.hasFocus()) {
2006 // note: not relying on mFocusedView here because this could
2007 // be when the window is first being added, and mFocused isn't
2008 // set yet.
2009 final View focused = mView.findFocus();
2010 if (focused != null && !focused.isFocusableInTouchMode()) {
2011
2012 final ViewGroup ancestorToTakeFocus =
2013 findAncestorToTakeFocusInTouchMode(focused);
2014 if (ancestorToTakeFocus != null) {
2015 // there is an ancestor that wants focus after its descendants that
2016 // is focusable in touch mode.. give it focus
2017 return ancestorToTakeFocus.requestFocus();
2018 } else {
2019 // nothing appropriate to have focus in touch mode, clear it out
2020 mView.unFocus();
2021 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(focused, null);
2022 mFocusedView = null;
2023 return true;
2024 }
2025 }
2026 }
2027 }
2028 return false;
2029 }
2030
2031
2032 /**
2033 * Find an ancestor of focused that wants focus after its descendants and is
2034 * focusable in touch mode.
2035 * @param focused The currently focused view.
2036 * @return An appropriate view, or null if no such view exists.
2037 */
2038 private ViewGroup findAncestorToTakeFocusInTouchMode(View focused) {
2039 ViewParent parent = focused.getParent();
2040 while (parent instanceof ViewGroup) {
2041 final ViewGroup vgParent = (ViewGroup) parent;
2042 if (vgParent.getDescendantFocusability() == ViewGroup.FOCUS_AFTER_DESCENDANTS
2043 && vgParent.isFocusableInTouchMode()) {
2044 return vgParent;
2045 }
2046 if (vgParent.isRootNamespace()) {
2047 return null;
2048 } else {
2049 parent = vgParent.getParent();
2050 }
2051 }
2052 return null;
2053 }
2054
2055 private boolean leaveTouchMode() {
2056 if (mView != null) {
2057 if (mView.hasFocus()) {
2058 // i learned the hard way to not trust mFocusedView :)
2059 mFocusedView = mView.findFocus();
2060 if (!(mFocusedView instanceof ViewGroup)) {
2061 // some view has focus, let it keep it
2062 return false;
2063 } else if (((ViewGroup)mFocusedView).getDescendantFocusability() !=
2064 ViewGroup.FOCUS_AFTER_DESCENDANTS) {
2065 // some view group has focus, and doesn't prefer its children
2066 // over itself for focus, so let them keep it.
2067 return false;
2068 }
2069 }
2070
2071 // find the best view to give focus to in this brave new non-touch-mode
2072 // world
2073 final View focused = focusSearch(null, View.FOCUS_DOWN);
2074 if (focused != null) {
2075 return focused.requestFocus(View.FOCUS_DOWN);
2076 }
2077 }
2078 return false;
2079 }
2080
Jeff Brown3915bb82010-11-05 15:02:16 -07002081 private void deliverPointerEvent(MotionEvent event, boolean sendDone) {
2082 // If there is no view, then the event will not be handled.
2083 if (mView == null || !mAdded) {
2084 finishPointerEvent(event, sendDone, false);
2085 return;
2086 }
2087
2088 // Translate the pointer event for compatibility, if needed.
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002089 if (mTranslator != null) {
2090 mTranslator.translateEventInScreenToAppWindow(event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002091 }
2092
Jeff Brown3915bb82010-11-05 15:02:16 -07002093 // Enter touch mode on the down.
2094 boolean isDown = event.getAction() == MotionEvent.ACTION_DOWN;
2095 if (isDown) {
2096 ensureTouchMode(true);
2097 }
2098 if(Config.LOGV) {
2099 captureMotionLog("captureDispatchPointer", event);
2100 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002101
Jeff Brown3915bb82010-11-05 15:02:16 -07002102 // Offset the scroll position.
2103 if (mCurScrollY != 0) {
2104 event.offsetLocation(0, mCurScrollY);
2105 }
2106 if (MEASURE_LATENCY) {
2107 lt.sample("A Dispatching TouchEvents", System.nanoTime() - event.getEventTimeNano());
2108 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002109
Jeff Brown3915bb82010-11-05 15:02:16 -07002110 // Remember the touch position for possible drag-initiation.
2111 mLastTouchPoint.x = event.getRawX();
2112 mLastTouchPoint.y = event.getRawY();
2113
2114 // Dispatch touch to view hierarchy.
2115 boolean handled = mView.dispatchTouchEvent(event);
2116 if (MEASURE_LATENCY) {
2117 lt.sample("B Dispatched TouchEvents ", System.nanoTime() - event.getEventTimeNano());
2118 }
2119 if (handled) {
2120 finishPointerEvent(event, sendDone, true);
2121 return;
2122 }
2123
2124 // Apply edge slop and try again, if appropriate.
2125 final int edgeFlags = event.getEdgeFlags();
2126 if (edgeFlags != 0 && mView instanceof ViewGroup) {
2127 final int edgeSlop = mViewConfiguration.getScaledEdgeSlop();
2128 int direction = View.FOCUS_UP;
2129 int x = (int)event.getX();
2130 int y = (int)event.getY();
2131 final int[] deltas = new int[2];
2132
2133 if ((edgeFlags & MotionEvent.EDGE_TOP) != 0) {
2134 direction = View.FOCUS_DOWN;
2135 if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
2136 deltas[0] = edgeSlop;
2137 x += edgeSlop;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002138 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
Jeff Brown3915bb82010-11-05 15:02:16 -07002139 deltas[0] = -edgeSlop;
2140 x -= edgeSlop;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002141 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002142 } else if ((edgeFlags & MotionEvent.EDGE_BOTTOM) != 0) {
2143 direction = View.FOCUS_UP;
2144 if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
2145 deltas[0] = edgeSlop;
2146 x += edgeSlop;
2147 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
2148 deltas[0] = -edgeSlop;
2149 x -= edgeSlop;
2150 }
2151 } else if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
2152 direction = View.FOCUS_RIGHT;
2153 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
2154 direction = View.FOCUS_LEFT;
2155 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002156
Jeff Brown3915bb82010-11-05 15:02:16 -07002157 View nearest = FocusFinder.getInstance().findNearestTouchable(
2158 ((ViewGroup) mView), x, y, direction, deltas);
2159 if (nearest != null) {
2160 event.offsetLocation(deltas[0], deltas[1]);
2161 event.setEdgeFlags(0);
2162 if (mView.dispatchTouchEvent(event)) {
2163 finishPointerEvent(event, sendDone, true);
2164 return;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002165 }
2166 }
2167 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002168
2169 // Pointer event was unhandled.
2170 finishPointerEvent(event, sendDone, false);
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002171 }
2172
Jeff Brown3915bb82010-11-05 15:02:16 -07002173 private void finishPointerEvent(MotionEvent event, boolean sendDone, boolean handled) {
2174 event.recycle();
2175 if (sendDone) {
2176 finishInputEvent(handled);
2177 }
2178 if (LOCAL_LOGV || WATCH_POINTER) Log.i(TAG, "Done dispatching!");
2179 }
2180
2181 private void deliverTrackballEvent(MotionEvent event, boolean sendDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002182 if (DEBUG_TRACKBALL) Log.v(TAG, "Motion event:" + event);
2183
Jeff Brown3915bb82010-11-05 15:02:16 -07002184 // If there is no view, then the event will not be handled.
2185 if (mView == null || !mAdded) {
2186 finishTrackballEvent(event, sendDone, false);
2187 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002188 }
2189
Jeff Brown3915bb82010-11-05 15:02:16 -07002190 // Deliver the trackball event to the view.
2191 if (mView.dispatchTrackballEvent(event)) {
2192 // If we reach this, we delivered a trackball event to mView and
2193 // mView consumed it. Because we will not translate the trackball
2194 // event into a key event, touch mode will not exit, so we exit
2195 // touch mode here.
2196 ensureTouchMode(false);
2197
2198 finishTrackballEvent(event, sendDone, true);
2199 mLastTrackballTime = Integer.MIN_VALUE;
2200 return;
2201 }
2202
2203 // Translate the trackball event into DPAD keys and try to deliver those.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002204 final TrackballAxis x = mTrackballAxisX;
2205 final TrackballAxis y = mTrackballAxisY;
2206
2207 long curTime = SystemClock.uptimeMillis();
Jeff Brown3915bb82010-11-05 15:02:16 -07002208 if ((mLastTrackballTime + MAX_TRACKBALL_DELAY) < curTime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002209 // It has been too long since the last movement,
2210 // so restart at the beginning.
2211 x.reset(0);
2212 y.reset(0);
2213 mLastTrackballTime = curTime;
2214 }
2215
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002216 final int action = event.getAction();
2217 final int metastate = event.getMetaState();
2218 switch (action) {
2219 case MotionEvent.ACTION_DOWN:
2220 x.reset(2);
2221 y.reset(2);
2222 deliverKeyEvent(new KeyEvent(curTime, curTime,
2223 KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_CENTER,
2224 0, metastate), false);
2225 break;
2226 case MotionEvent.ACTION_UP:
2227 x.reset(2);
2228 y.reset(2);
2229 deliverKeyEvent(new KeyEvent(curTime, curTime,
2230 KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_CENTER,
2231 0, metastate), false);
2232 break;
2233 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002234
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002235 if (DEBUG_TRACKBALL) Log.v(TAG, "TB X=" + x.position + " step="
2236 + x.step + " dir=" + x.dir + " acc=" + x.acceleration
2237 + " move=" + event.getX()
2238 + " / Y=" + y.position + " step="
2239 + y.step + " dir=" + y.dir + " acc=" + y.acceleration
2240 + " move=" + event.getY());
2241 final float xOff = x.collect(event.getX(), event.getEventTime(), "X");
2242 final float yOff = y.collect(event.getY(), event.getEventTime(), "Y");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002243
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002244 // Generate DPAD events based on the trackball movement.
2245 // We pick the axis that has moved the most as the direction of
2246 // the DPAD. When we generate DPAD events for one axis, then the
2247 // other axis is reset -- we don't want to perform DPAD jumps due
2248 // to slight movements in the trackball when making major movements
2249 // along the other axis.
2250 int keycode = 0;
2251 int movement = 0;
2252 float accel = 1;
2253 if (xOff > yOff) {
2254 movement = x.generate((2/event.getXPrecision()));
2255 if (movement != 0) {
2256 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_RIGHT
2257 : KeyEvent.KEYCODE_DPAD_LEFT;
2258 accel = x.acceleration;
2259 y.reset(2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002260 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002261 } else if (yOff > 0) {
2262 movement = y.generate((2/event.getYPrecision()));
2263 if (movement != 0) {
2264 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_DOWN
2265 : KeyEvent.KEYCODE_DPAD_UP;
2266 accel = y.acceleration;
2267 x.reset(2);
2268 }
2269 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002270
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002271 if (keycode != 0) {
2272 if (movement < 0) movement = -movement;
2273 int accelMovement = (int)(movement * accel);
2274 if (DEBUG_TRACKBALL) Log.v(TAG, "Move: movement=" + movement
2275 + " accelMovement=" + accelMovement
2276 + " accel=" + accel);
2277 if (accelMovement > movement) {
2278 if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: "
2279 + keycode);
2280 movement--;
2281 deliverKeyEvent(new KeyEvent(curTime, curTime,
2282 KeyEvent.ACTION_MULTIPLE, keycode,
2283 accelMovement-movement, metastate), false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002284 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002285 while (movement > 0) {
2286 if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: "
2287 + keycode);
2288 movement--;
2289 curTime = SystemClock.uptimeMillis();
2290 deliverKeyEvent(new KeyEvent(curTime, curTime,
2291 KeyEvent.ACTION_DOWN, keycode, 0, event.getMetaState()), false);
2292 deliverKeyEvent(new KeyEvent(curTime, curTime,
2293 KeyEvent.ACTION_UP, keycode, 0, metastate), false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002294 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002295 mLastTrackballTime = curTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002296 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002297
2298 // Unfortunately we can't tell whether the application consumed the keys, so
2299 // we always consider the trackball event handled.
2300 finishTrackballEvent(event, sendDone, true);
2301 }
2302
2303 private void finishTrackballEvent(MotionEvent event, boolean sendDone, boolean handled) {
2304 event.recycle();
2305 if (sendDone) {
2306 finishInputEvent(handled);
2307 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002308 }
2309
2310 /**
2311 * @param keyCode The key code
2312 * @return True if the key is directional.
2313 */
2314 static boolean isDirectional(int keyCode) {
2315 switch (keyCode) {
2316 case KeyEvent.KEYCODE_DPAD_LEFT:
2317 case KeyEvent.KEYCODE_DPAD_RIGHT:
2318 case KeyEvent.KEYCODE_DPAD_UP:
2319 case KeyEvent.KEYCODE_DPAD_DOWN:
2320 return true;
2321 }
2322 return false;
2323 }
2324
2325 /**
2326 * Returns true if this key is a keyboard key.
2327 * @param keyEvent The key event.
2328 * @return whether this key is a keyboard key.
2329 */
2330 private static boolean isKeyboardKey(KeyEvent keyEvent) {
2331 final int convertedKey = keyEvent.getUnicodeChar();
2332 return convertedKey > 0;
2333 }
2334
2335
2336
2337 /**
2338 * See if the key event means we should leave touch mode (and leave touch
2339 * mode if so).
2340 * @param event The key event.
2341 * @return Whether this key event should be consumed (meaning the act of
2342 * leaving touch mode alone is considered the event).
2343 */
2344 private boolean checkForLeavingTouchModeAndConsume(KeyEvent event) {
Adam Powell51a6bee2010-03-15 14:07:28 -07002345 final int action = event.getAction();
2346 if (action != KeyEvent.ACTION_DOWN && action != KeyEvent.ACTION_MULTIPLE) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002347 return false;
2348 }
2349 if ((event.getFlags()&KeyEvent.FLAG_KEEP_TOUCH_MODE) != 0) {
2350 return false;
2351 }
2352
2353 // only relevant if we are in touch mode
2354 if (!mAttachInfo.mInTouchMode) {
2355 return false;
2356 }
2357
2358 // if something like an edit text has focus and the user is typing,
2359 // leave touch mode
2360 //
2361 // note: the condition of not being a keyboard key is kind of a hacky
2362 // approximation of whether we think the focused view will want the
2363 // key; if we knew for sure whether the focused view would consume
2364 // the event, that would be better.
2365 if (isKeyboardKey(event) && mView != null && mView.hasFocus()) {
2366 mFocusedView = mView.findFocus();
2367 if ((mFocusedView instanceof ViewGroup)
2368 && ((ViewGroup) mFocusedView).getDescendantFocusability() ==
2369 ViewGroup.FOCUS_AFTER_DESCENDANTS) {
2370 // something has focus, but is holding it weakly as a container
2371 return false;
2372 }
2373 if (ensureTouchMode(false)) {
2374 throw new IllegalStateException("should not have changed focus "
2375 + "when leaving touch mode while a view has focus.");
2376 }
2377 return false;
2378 }
2379
2380 if (isDirectional(event.getKeyCode())) {
2381 // no view has focus, so we leave touch mode (and find something
2382 // to give focus to). the event is consumed if we were able to
2383 // find something to give focus to.
2384 return ensureTouchMode(false);
2385 }
2386 return false;
2387 }
2388
2389 /**
Romain Guy8506ab42009-06-11 17:35:47 -07002390 * log motion events
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002391 */
2392 private static void captureMotionLog(String subTag, MotionEvent ev) {
Romain Guy8506ab42009-06-11 17:35:47 -07002393 //check dynamic switch
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002394 if (ev == null ||
2395 SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_EVENT, 0) == 0) {
2396 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002397 }
Romain Guy8506ab42009-06-11 17:35:47 -07002398
2399 StringBuilder sb = new StringBuilder(subTag + ": ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002400 sb.append(ev.getDownTime()).append(',');
2401 sb.append(ev.getEventTime()).append(',');
2402 sb.append(ev.getAction()).append(',');
Romain Guy8506ab42009-06-11 17:35:47 -07002403 sb.append(ev.getX()).append(',');
2404 sb.append(ev.getY()).append(',');
2405 sb.append(ev.getPressure()).append(',');
2406 sb.append(ev.getSize()).append(',');
2407 sb.append(ev.getMetaState()).append(',');
2408 sb.append(ev.getXPrecision()).append(',');
2409 sb.append(ev.getYPrecision()).append(',');
2410 sb.append(ev.getDeviceId()).append(',');
2411 sb.append(ev.getEdgeFlags());
2412 Log.d(TAG, sb.toString());
2413 }
2414 /**
2415 * log motion events
2416 */
2417 private static void captureKeyLog(String subTag, KeyEvent ev) {
2418 //check dynamic switch
2419 if (ev == null ||
2420 SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_EVENT, 0) == 0) {
2421 return;
2422 }
2423 StringBuilder sb = new StringBuilder(subTag + ": ");
2424 sb.append(ev.getDownTime()).append(',');
2425 sb.append(ev.getEventTime()).append(',');
2426 sb.append(ev.getAction()).append(',');
2427 sb.append(ev.getKeyCode()).append(',');
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002428 sb.append(ev.getRepeatCount()).append(',');
2429 sb.append(ev.getMetaState()).append(',');
2430 sb.append(ev.getDeviceId()).append(',');
2431 sb.append(ev.getScanCode());
Romain Guy8506ab42009-06-11 17:35:47 -07002432 Log.d(TAG, sb.toString());
2433 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002434
2435 int enqueuePendingEvent(Object event, boolean sendDone) {
2436 int seq = mPendingEventSeq+1;
2437 if (seq < 0) seq = 0;
2438 mPendingEventSeq = seq;
2439 mPendingEvents.put(seq, event);
2440 return sendDone ? seq : -seq;
2441 }
2442
2443 Object retrievePendingEvent(int seq) {
2444 if (seq < 0) seq = -seq;
2445 Object event = mPendingEvents.get(seq);
2446 if (event != null) {
2447 mPendingEvents.remove(seq);
2448 }
2449 return event;
2450 }
Romain Guy8506ab42009-06-11 17:35:47 -07002451
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002452 private void deliverKeyEvent(KeyEvent event, boolean sendDone) {
Jeff Brown3915bb82010-11-05 15:02:16 -07002453 // If there is no view, then the event will not be handled.
2454 if (mView == null || !mAdded) {
2455 finishKeyEvent(event, sendDone, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002456 return;
2457 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002458
2459 if (LOCAL_LOGV) Log.v(TAG, "Dispatching key " + event + " to " + mView);
2460
2461 // Perform predispatching before the IME.
2462 if (mView.dispatchKeyEventPreIme(event)) {
2463 finishKeyEvent(event, sendDone, true);
2464 return;
2465 }
2466
2467 // Dispatch to the IME before propagating down the view hierarchy.
2468 // The IME will eventually call back into handleFinishedEvent.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002469 if (mLastWasImTarget) {
2470 InputMethodManager imm = InputMethodManager.peekInstance();
Jeff Brown3915bb82010-11-05 15:02:16 -07002471 if (imm != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002472 int seq = enqueuePendingEvent(event, sendDone);
2473 if (DEBUG_IMF) Log.v(TAG, "Sending key event to IME: seq="
2474 + seq + " event=" + event);
Jeff Brown3915bb82010-11-05 15:02:16 -07002475 imm.dispatchKeyEvent(mView.getContext(), seq, event, mInputMethodCallback);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002476 return;
2477 }
2478 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002479
2480 // Not dispatching to IME, continue with post IME actions.
2481 deliverKeyEventPostIme(event, sendDone);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002482 }
2483
Jeff Brown3915bb82010-11-05 15:02:16 -07002484 private void handleFinishedEvent(int seq, boolean handled) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002485 final KeyEvent event = (KeyEvent)retrievePendingEvent(seq);
2486 if (DEBUG_IMF) Log.v(TAG, "IME finished event: seq=" + seq
2487 + " handled=" + handled + " event=" + event);
2488 if (event != null) {
2489 final boolean sendDone = seq >= 0;
Jeff Brown3915bb82010-11-05 15:02:16 -07002490 if (handled) {
2491 finishKeyEvent(event, sendDone, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002492 } else {
Jeff Brown3915bb82010-11-05 15:02:16 -07002493 deliverKeyEventPostIme(event, sendDone);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002494 }
2495 }
2496 }
Romain Guy8506ab42009-06-11 17:35:47 -07002497
Jeff Brown3915bb82010-11-05 15:02:16 -07002498 private void deliverKeyEventPostIme(KeyEvent event, boolean sendDone) {
2499 // If the view went away, then the event will not be handled.
2500 if (mView == null || !mAdded) {
2501 finishKeyEvent(event, sendDone, false);
2502 return;
2503 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002504
Jeff Brown3915bb82010-11-05 15:02:16 -07002505 // If the key's purpose is to exit touch mode then we consume it and consider it handled.
2506 if (checkForLeavingTouchModeAndConsume(event)) {
2507 finishKeyEvent(event, sendDone, true);
2508 return;
2509 }
Romain Guy8506ab42009-06-11 17:35:47 -07002510
Jeff Brown3915bb82010-11-05 15:02:16 -07002511 if (Config.LOGV) {
2512 captureKeyLog("captureDispatchKeyEvent", event);
2513 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002514
Jeff Brown3915bb82010-11-05 15:02:16 -07002515 // Deliver the key to the view hierarchy.
2516 if (mView.dispatchKeyEvent(event)) {
2517 finishKeyEvent(event, sendDone, true);
2518 return;
2519 }
Joe Onorato86f67862010-11-05 18:57:34 -07002520
Jeff Brown3915bb82010-11-05 15:02:16 -07002521 // Apply the fallback event policy.
2522 if (mFallbackEventHandler.dispatchKeyEvent(event)) {
2523 finishKeyEvent(event, sendDone, true);
2524 return;
2525 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002526
Jeff Brown3915bb82010-11-05 15:02:16 -07002527 // Handle automatic focus changes.
2528 if (event.getAction() == KeyEvent.ACTION_DOWN) {
2529 int direction = 0;
2530 switch (event.getKeyCode()) {
2531 case KeyEvent.KEYCODE_DPAD_LEFT:
2532 direction = View.FOCUS_LEFT;
2533 break;
2534 case KeyEvent.KEYCODE_DPAD_RIGHT:
2535 direction = View.FOCUS_RIGHT;
2536 break;
2537 case KeyEvent.KEYCODE_DPAD_UP:
2538 direction = View.FOCUS_UP;
2539 break;
2540 case KeyEvent.KEYCODE_DPAD_DOWN:
2541 direction = View.FOCUS_DOWN;
2542 break;
2543 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002544
Jeff Brown3915bb82010-11-05 15:02:16 -07002545 if (direction != 0) {
2546 View focused = mView != null ? mView.findFocus() : null;
2547 if (focused != null) {
2548 View v = focused.focusSearch(direction);
2549 if (v != null && v != focused) {
2550 // do the math the get the interesting rect
2551 // of previous focused into the coord system of
2552 // newly focused view
2553 focused.getFocusedRect(mTempRect);
2554 if (mView instanceof ViewGroup) {
2555 ((ViewGroup) mView).offsetDescendantRectToMyCoords(
2556 focused, mTempRect);
2557 ((ViewGroup) mView).offsetRectIntoDescendantCoords(
2558 v, mTempRect);
2559 }
2560 if (v.requestFocus(direction, mTempRect)) {
2561 playSoundEffect(
2562 SoundEffectConstants.getContantForFocusDirection(direction));
2563 finishKeyEvent(event, sendDone, true);
2564 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002565 }
2566 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002567
2568 // Give the focused view a last chance to handle the dpad key.
2569 if (mView.dispatchUnhandledMove(focused, direction)) {
2570 finishKeyEvent(event, sendDone, true);
2571 return;
2572 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002573 }
2574 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002575 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002576
Jeff Brown3915bb82010-11-05 15:02:16 -07002577 // Key was unhandled.
2578 finishKeyEvent(event, sendDone, false);
2579 }
2580
2581 private void finishKeyEvent(KeyEvent event, boolean sendDone, boolean handled) {
2582 if (sendDone) {
2583 finishInputEvent(handled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002584 }
2585 }
2586
Christopher Tatea53146c2010-09-07 11:57:52 -07002587 /* drag/drop */
2588 private void handleDragEvent(DragEvent event) {
2589 // From the root, only drag start/end/location are dispatched. entered/exited
2590 // are determined and dispatched by the viewgroup hierarchy, who then report
2591 // that back here for ultimate reporting back to the framework.
2592 if (mView != null && mAdded) {
2593 final int what = event.mAction;
2594
2595 if (what == DragEvent.ACTION_DRAG_EXITED) {
2596 // A direct EXITED event means that the window manager knows we've just crossed
2597 // a window boundary, so the current drag target within this one must have
2598 // just been exited. Send it the usual notifications and then we're done
2599 // for now.
Chris Tate9d1ab882010-11-02 15:55:39 -07002600 mView.dispatchDragEvent(event);
Christopher Tatea53146c2010-09-07 11:57:52 -07002601 } else {
2602 // Cache the drag description when the operation starts, then fill it in
2603 // on subsequent calls as a convenience
2604 if (what == DragEvent.ACTION_DRAG_STARTED) {
Chris Tate9d1ab882010-11-02 15:55:39 -07002605 mCurrentDragView = null; // Start the current-recipient tracking
Christopher Tatea53146c2010-09-07 11:57:52 -07002606 mDragDescription = event.mClipDescription;
2607 } else {
2608 event.mClipDescription = mDragDescription;
2609 }
2610
2611 // For events with a [screen] location, translate into window coordinates
2612 if ((what == DragEvent.ACTION_DRAG_LOCATION) || (what == DragEvent.ACTION_DROP)) {
2613 mDragPoint.set(event.mX, event.mY);
2614 if (mTranslator != null) {
2615 mTranslator.translatePointInScreenToAppWindow(mDragPoint);
2616 }
2617
2618 if (mCurScrollY != 0) {
2619 mDragPoint.offset(0, mCurScrollY);
2620 }
2621
2622 event.mX = mDragPoint.x;
2623 event.mY = mDragPoint.y;
2624 }
2625
2626 // Remember who the current drag target is pre-dispatch
2627 final View prevDragView = mCurrentDragView;
2628
2629 // Now dispatch the drag/drop event
Chris Tated4533f12010-10-19 15:15:08 -07002630 boolean result = mView.dispatchDragEvent(event);
Christopher Tatea53146c2010-09-07 11:57:52 -07002631
2632 // If we changed apparent drag target, tell the OS about it
2633 if (prevDragView != mCurrentDragView) {
2634 try {
2635 if (prevDragView != null) {
2636 sWindowSession.dragRecipientExited(mWindow);
2637 }
2638 if (mCurrentDragView != null) {
2639 sWindowSession.dragRecipientEntered(mWindow);
2640 }
2641 } catch (RemoteException e) {
2642 Slog.e(TAG, "Unable to note drag target change");
2643 }
Christopher Tatea53146c2010-09-07 11:57:52 -07002644 }
Chris Tated4533f12010-10-19 15:15:08 -07002645
2646 // Report the drop result if necessary
2647 if (what == DragEvent.ACTION_DROP) {
2648 try {
2649 Log.i(TAG, "Reporting drop result: " + result);
2650 sWindowSession.reportDropResult(mWindow, result);
2651 } catch (RemoteException e) {
2652 Log.e(TAG, "Unable to report drop result");
2653 }
2654 }
Christopher Tatea53146c2010-09-07 11:57:52 -07002655 }
2656 }
2657 event.recycle();
2658 }
2659
Christopher Tate2c095f32010-10-04 14:13:40 -07002660 public void getLastTouchPoint(Point outLocation) {
2661 outLocation.x = (int) mLastTouchPoint.x;
2662 outLocation.y = (int) mLastTouchPoint.y;
2663 }
2664
Chris Tate9d1ab882010-11-02 15:55:39 -07002665 public void setDragFocus(View newDragTarget) {
Christopher Tatea53146c2010-09-07 11:57:52 -07002666 if (mCurrentDragView != newDragTarget) {
Chris Tate048691c2010-10-12 17:39:18 -07002667 mCurrentDragView = newDragTarget;
Christopher Tatea53146c2010-09-07 11:57:52 -07002668 }
Christopher Tatea53146c2010-09-07 11:57:52 -07002669 }
2670
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002671 private AudioManager getAudioManager() {
2672 if (mView == null) {
2673 throw new IllegalStateException("getAudioManager called when there is no mView");
2674 }
2675 if (mAudioManager == null) {
2676 mAudioManager = (AudioManager) mView.getContext().getSystemService(Context.AUDIO_SERVICE);
2677 }
2678 return mAudioManager;
2679 }
2680
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002681 private int relayoutWindow(WindowManager.LayoutParams params, int viewVisibility,
2682 boolean insetsPending) throws RemoteException {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002683
2684 float appScale = mAttachInfo.mApplicationScale;
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002685 boolean restore = false;
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002686 if (params != null && mTranslator != null) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07002687 restore = true;
2688 params.backup();
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002689 mTranslator.translateWindowLayout(params);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002690 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002691 if (params != null) {
2692 if (DBG) Log.d(TAG, "WindowLayout in layoutWindow:" + params);
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002693 }
Dianne Hackborn694f79b2010-03-17 19:44:59 -07002694 mPendingConfiguration.seq = 0;
Dianne Hackbornf123e492010-09-24 11:16:23 -07002695 //Log.d(TAG, ">>>>>> CALLING relayout");
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002696 int relayoutResult = sWindowSession.relayout(
2697 mWindow, params,
Mitsuru Oshima61324e52009-07-21 15:40:36 -07002698 (int) (mView.mMeasuredWidth * appScale + 0.5f),
2699 (int) (mView.mMeasuredHeight * appScale + 0.5f),
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002700 viewVisibility, insetsPending, mWinFrame,
Dianne Hackborn694f79b2010-03-17 19:44:59 -07002701 mPendingContentInsets, mPendingVisibleInsets,
2702 mPendingConfiguration, mSurface);
Dianne Hackbornf123e492010-09-24 11:16:23 -07002703 //Log.d(TAG, "<<<<<< BACK FROM relayout");
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002704 if (restore) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07002705 params.restore();
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002706 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002707
2708 if (mTranslator != null) {
2709 mTranslator.translateRectInScreenToAppWinFrame(mWinFrame);
2710 mTranslator.translateRectInScreenToAppWindow(mPendingContentInsets);
2711 mTranslator.translateRectInScreenToAppWindow(mPendingVisibleInsets);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002712 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002713 return relayoutResult;
2714 }
Romain Guy8506ab42009-06-11 17:35:47 -07002715
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002716 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002717 * {@inheritDoc}
2718 */
2719 public void playSoundEffect(int effectId) {
2720 checkThread();
2721
Jean-Michel Trivi13b18fd2010-05-05 09:18:15 -07002722 try {
2723 final AudioManager audioManager = getAudioManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002724
Jean-Michel Trivi13b18fd2010-05-05 09:18:15 -07002725 switch (effectId) {
2726 case SoundEffectConstants.CLICK:
2727 audioManager.playSoundEffect(AudioManager.FX_KEY_CLICK);
2728 return;
2729 case SoundEffectConstants.NAVIGATION_DOWN:
2730 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_DOWN);
2731 return;
2732 case SoundEffectConstants.NAVIGATION_LEFT:
2733 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_LEFT);
2734 return;
2735 case SoundEffectConstants.NAVIGATION_RIGHT:
2736 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_RIGHT);
2737 return;
2738 case SoundEffectConstants.NAVIGATION_UP:
2739 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_UP);
2740 return;
2741 default:
2742 throw new IllegalArgumentException("unknown effect id " + effectId +
2743 " not defined in " + SoundEffectConstants.class.getCanonicalName());
2744 }
2745 } catch (IllegalStateException e) {
2746 // Exception thrown by getAudioManager() when mView is null
2747 Log.e(TAG, "FATAL EXCEPTION when attempting to play sound effect: " + e);
2748 e.printStackTrace();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002749 }
2750 }
2751
2752 /**
2753 * {@inheritDoc}
2754 */
2755 public boolean performHapticFeedback(int effectId, boolean always) {
2756 try {
2757 return sWindowSession.performHapticFeedback(mWindow, effectId, always);
2758 } catch (RemoteException e) {
2759 return false;
2760 }
2761 }
2762
2763 /**
2764 * {@inheritDoc}
2765 */
2766 public View focusSearch(View focused, int direction) {
2767 checkThread();
2768 if (!(mView instanceof ViewGroup)) {
2769 return null;
2770 }
2771 return FocusFinder.getInstance().findNextFocus((ViewGroup) mView, focused, direction);
2772 }
2773
2774 public void debug() {
2775 mView.debug();
2776 }
2777
2778 public void die(boolean immediate) {
Dianne Hackborn94d69142009-09-28 22:14:42 -07002779 if (immediate) {
2780 doDie();
2781 } else {
2782 sendEmptyMessage(DIE);
2783 }
2784 }
2785
2786 void doDie() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002787 checkThread();
Jeff Brownb75fa302010-07-15 23:47:29 -07002788 if (LOCAL_LOGV) Log.v(TAG, "DIE in " + this + " of " + mSurface);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002789 synchronized (this) {
2790 if (mAdded && !mFirst) {
Romain Guy29d89972010-09-22 16:10:57 -07002791 destroyHardwareRenderer();
2792
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002793 int viewVisibility = mView.getVisibility();
2794 boolean viewVisibilityChanged = mViewVisibility != viewVisibility;
2795 if (mWindowAttributesChanged || viewVisibilityChanged) {
2796 // If layout params have been changed, first give them
2797 // to the window manager to make sure it has the correct
2798 // animation info.
2799 try {
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002800 if ((relayoutWindow(mWindowAttributes, viewVisibility, false)
2801 & WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002802 sWindowSession.finishDrawing(mWindow);
2803 }
2804 } catch (RemoteException e) {
2805 }
2806 }
2807
Dianne Hackborn0586a1b2009-09-06 21:08:27 -07002808 mSurface.release();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002809 }
2810 if (mAdded) {
2811 mAdded = false;
Dianne Hackborn94d69142009-09-28 22:14:42 -07002812 dispatchDetachedFromWindow();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002813 }
2814 }
2815 }
2816
Romain Guy29d89972010-09-22 16:10:57 -07002817 private void destroyHardwareRenderer() {
Romain Guyb051e892010-09-28 19:09:36 -07002818 if (mAttachInfo.mHardwareRenderer != null) {
2819 mAttachInfo.mHardwareRenderer.destroy(true);
2820 mAttachInfo.mHardwareRenderer = null;
Romain Guy29d89972010-09-22 16:10:57 -07002821 mAttachInfo.mHardwareAccelerated = false;
2822 }
2823 }
2824
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002825 public void dispatchFinishedEvent(int seq, boolean handled) {
2826 Message msg = obtainMessage(FINISHED_EVENT);
2827 msg.arg1 = seq;
2828 msg.arg2 = handled ? 1 : 0;
2829 sendMessage(msg);
2830 }
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002831
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002832 public void dispatchResized(int w, int h, Rect coveredInsets,
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002833 Rect visibleInsets, boolean reportDraw, Configuration newConfig) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002834 if (DEBUG_LAYOUT) Log.v(TAG, "Resizing " + this + ": w=" + w
2835 + " h=" + h + " coveredInsets=" + coveredInsets.toShortString()
2836 + " visibleInsets=" + visibleInsets.toShortString()
2837 + " reportDraw=" + reportDraw);
2838 Message msg = obtainMessage(reportDraw ? RESIZED_REPORT :RESIZED);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002839 if (mTranslator != null) {
2840 mTranslator.translateRectInScreenToAppWindow(coveredInsets);
2841 mTranslator.translateRectInScreenToAppWindow(visibleInsets);
2842 w *= mTranslator.applicationInvertedScale;
2843 h *= mTranslator.applicationInvertedScale;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002844 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002845 msg.arg1 = w;
2846 msg.arg2 = h;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002847 ResizedInfo ri = new ResizedInfo();
2848 ri.coveredInsets = new Rect(coveredInsets);
2849 ri.visibleInsets = new Rect(visibleInsets);
2850 ri.newConfig = newConfig;
2851 msg.obj = ri;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002852 sendMessage(msg);
2853 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002854
Jeff Brown3915bb82010-11-05 15:02:16 -07002855 private InputQueue.FinishedCallback mFinishedCallback;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002856
2857 private final InputHandler mInputHandler = new InputHandler() {
Jeff Brown3915bb82010-11-05 15:02:16 -07002858 public void handleKey(KeyEvent event, InputQueue.FinishedCallback finishedCallback) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07002859 startInputEvent(finishedCallback);
Jeff Brown92ff1dd2010-08-11 16:16:06 -07002860 dispatchKey(event, true);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002861 }
2862
Jeff Brown3915bb82010-11-05 15:02:16 -07002863 public void handleMotion(MotionEvent event, InputQueue.FinishedCallback finishedCallback) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07002864 startInputEvent(finishedCallback);
2865 dispatchMotion(event, true);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002866 }
2867 };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002868
2869 public void dispatchKey(KeyEvent event) {
Jeff Brown92ff1dd2010-08-11 16:16:06 -07002870 dispatchKey(event, false);
2871 }
2872
2873 private void dispatchKey(KeyEvent event, boolean sendDone) {
2874 //noinspection ConstantConditions
2875 if (false && event.getAction() == KeyEvent.ACTION_DOWN) {
2876 if (event.getKeyCode() == KeyEvent.KEYCODE_CAMERA) {
Romain Guy812ccbe2010-06-01 14:07:24 -07002877 if (DBG) Log.d("keydisp", "===================================================");
2878 if (DBG) Log.d("keydisp", "Focused view Hierarchy is:");
2879
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002880 debug();
2881
Romain Guy812ccbe2010-06-01 14:07:24 -07002882 if (DBG) Log.d("keydisp", "===================================================");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002883 }
2884 }
2885
2886 Message msg = obtainMessage(DISPATCH_KEY);
2887 msg.obj = event;
Jeff Brown92ff1dd2010-08-11 16:16:06 -07002888 msg.arg1 = sendDone ? 1 : 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002889
2890 if (LOCAL_LOGV) Log.v(
Jeff Brownc5ed5912010-07-14 18:48:53 -07002891 TAG, "sending key " + event + " to " + mView);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002892
2893 sendMessageAtTime(msg, event.getEventTime());
2894 }
Jeff Brownc5ed5912010-07-14 18:48:53 -07002895
2896 public void dispatchMotion(MotionEvent event) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07002897 dispatchMotion(event, false);
2898 }
2899
2900 private void dispatchMotion(MotionEvent event, boolean sendDone) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07002901 int source = event.getSource();
2902 if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07002903 dispatchPointer(event, sendDone);
Jeff Brownc5ed5912010-07-14 18:48:53 -07002904 } else if ((source & InputDevice.SOURCE_CLASS_TRACKBALL) != 0) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07002905 dispatchTrackball(event, sendDone);
Jeff Brownc5ed5912010-07-14 18:48:53 -07002906 } else {
2907 // TODO
2908 Log.v(TAG, "Dropping unsupported motion event (unimplemented): " + event);
Jeff Brown93ed4e32010-09-23 13:51:48 -07002909 if (sendDone) {
Jeff Brown3915bb82010-11-05 15:02:16 -07002910 finishInputEvent(false);
Jeff Brown93ed4e32010-09-23 13:51:48 -07002911 }
Jeff Brownc5ed5912010-07-14 18:48:53 -07002912 }
2913 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002914
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002915 public void dispatchPointer(MotionEvent event) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07002916 dispatchPointer(event, false);
2917 }
2918
2919 private void dispatchPointer(MotionEvent event, boolean sendDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002920 Message msg = obtainMessage(DISPATCH_POINTER);
2921 msg.obj = event;
Jeff Brown93ed4e32010-09-23 13:51:48 -07002922 msg.arg1 = sendDone ? 1 : 0;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002923 sendMessageAtTime(msg, event.getEventTime());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002924 }
2925
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002926 public void dispatchTrackball(MotionEvent event) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07002927 dispatchTrackball(event, false);
2928 }
2929
2930 private void dispatchTrackball(MotionEvent event, boolean sendDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002931 Message msg = obtainMessage(DISPATCH_TRACKBALL);
2932 msg.obj = event;
Jeff Brown93ed4e32010-09-23 13:51:48 -07002933 msg.arg1 = sendDone ? 1 : 0;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002934 sendMessageAtTime(msg, event.getEventTime());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002935 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002936
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002937 public void dispatchAppVisibility(boolean visible) {
2938 Message msg = obtainMessage(DISPATCH_APP_VISIBILITY);
2939 msg.arg1 = visible ? 1 : 0;
2940 sendMessage(msg);
2941 }
2942
2943 public void dispatchGetNewSurface() {
2944 Message msg = obtainMessage(DISPATCH_GET_NEW_SURFACE);
2945 sendMessage(msg);
2946 }
2947
2948 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
2949 Message msg = Message.obtain();
2950 msg.what = WINDOW_FOCUS_CHANGED;
2951 msg.arg1 = hasFocus ? 1 : 0;
2952 msg.arg2 = inTouchMode ? 1 : 0;
2953 sendMessage(msg);
2954 }
2955
Dianne Hackbornffa42482009-09-23 22:20:11 -07002956 public void dispatchCloseSystemDialogs(String reason) {
2957 Message msg = Message.obtain();
2958 msg.what = CLOSE_SYSTEM_DIALOGS;
2959 msg.obj = reason;
2960 sendMessage(msg);
2961 }
Christopher Tatea53146c2010-09-07 11:57:52 -07002962
2963 public void dispatchDragEvent(DragEvent event) {
Chris Tate91e9bb32010-10-12 12:58:43 -07002964 final int what;
2965 if (event.getAction() == DragEvent.ACTION_DRAG_LOCATION) {
2966 what = DISPATCH_DRAG_LOCATION_EVENT;
2967 removeMessages(what);
2968 } else {
2969 what = DISPATCH_DRAG_EVENT;
2970 }
2971 Message msg = obtainMessage(what, event);
Christopher Tatea53146c2010-09-07 11:57:52 -07002972 sendMessage(msg);
2973 }
2974
svetoslavganov75986cf2009-05-14 22:28:01 -07002975 /**
2976 * The window is getting focus so if there is anything focused/selected
2977 * send an {@link AccessibilityEvent} to announce that.
2978 */
2979 private void sendAccessibilityEvents() {
2980 if (!AccessibilityManager.getInstance(mView.getContext()).isEnabled()) {
2981 return;
2982 }
2983 mView.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
2984 View focusedView = mView.findFocus();
2985 if (focusedView != null && focusedView != mView) {
2986 focusedView.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
2987 }
2988 }
2989
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002990 public boolean showContextMenuForChild(View originalView) {
2991 return false;
2992 }
2993
Adam Powell6e346362010-07-23 10:18:23 -07002994 public ActionMode startActionModeForChild(View originalView, ActionMode.Callback callback) {
2995 return null;
2996 }
2997
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002998 public void createContextMenu(ContextMenu menu) {
2999 }
3000
3001 public void childDrawableStateChanged(View child) {
3002 }
3003
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003004 void checkThread() {
3005 if (mThread != Thread.currentThread()) {
3006 throw new CalledFromWrongThreadException(
3007 "Only the original thread that created a view hierarchy can touch its views.");
3008 }
3009 }
3010
3011 public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
3012 // ViewRoot never intercepts touch event, so this can be a no-op
3013 }
3014
3015 public boolean requestChildRectangleOnScreen(View child, Rect rectangle,
3016 boolean immediate) {
3017 return scrollToRectOrFocus(rectangle, immediate);
3018 }
Romain Guy8506ab42009-06-11 17:35:47 -07003019
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07003020 class TakenSurfaceHolder extends BaseSurfaceHolder {
3021 @Override
3022 public boolean onAllowLockCanvas() {
3023 return mDrawingAllowed;
3024 }
3025
3026 @Override
3027 public void onRelayoutContainer() {
3028 // Not currently interesting -- from changing between fixed and layout size.
3029 }
3030
3031 public void setFormat(int format) {
3032 ((RootViewSurfaceTaker)mView).setSurfaceFormat(format);
3033 }
3034
3035 public void setType(int type) {
3036 ((RootViewSurfaceTaker)mView).setSurfaceType(type);
3037 }
3038
3039 @Override
3040 public void onUpdateSurface() {
3041 // We take care of format and type changes on our own.
3042 throw new IllegalStateException("Shouldn't be here");
3043 }
3044
3045 public boolean isCreating() {
3046 return mIsCreating;
3047 }
3048
3049 @Override
3050 public void setFixedSize(int width, int height) {
3051 throw new UnsupportedOperationException(
3052 "Currently only support sizing from layout");
3053 }
3054
3055 public void setKeepScreenOn(boolean screenOn) {
3056 ((RootViewSurfaceTaker)mView).setSurfaceKeepScreenOn(screenOn);
3057 }
3058 }
3059
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003060 static class InputMethodCallback extends IInputMethodCallback.Stub {
3061 private WeakReference<ViewRoot> mViewRoot;
3062
3063 public InputMethodCallback(ViewRoot viewRoot) {
3064 mViewRoot = new WeakReference<ViewRoot>(viewRoot);
3065 }
Romain Guy8506ab42009-06-11 17:35:47 -07003066
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003067 public void finishedEvent(int seq, boolean handled) {
3068 final ViewRoot viewRoot = mViewRoot.get();
3069 if (viewRoot != null) {
3070 viewRoot.dispatchFinishedEvent(seq, handled);
3071 }
3072 }
3073
3074 public void sessionCreated(IInputMethodSession session) throws RemoteException {
3075 // Stub -- not for use in the client.
3076 }
3077 }
Romain Guy8506ab42009-06-11 17:35:47 -07003078
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003079 static class W extends IWindow.Stub {
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07003080 private final WeakReference<ViewRoot> mViewRoot;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003081
Romain Guyfb8b7632010-08-23 21:05:08 -07003082 W(ViewRoot viewRoot) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003083 mViewRoot = new WeakReference<ViewRoot>(viewRoot);
3084 }
3085
Romain Guyfb8b7632010-08-23 21:05:08 -07003086 public void resized(int w, int h, Rect coveredInsets, Rect visibleInsets,
3087 boolean reportDraw, Configuration newConfig) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003088 final ViewRoot viewRoot = mViewRoot.get();
3089 if (viewRoot != null) {
Romain Guyfb8b7632010-08-23 21:05:08 -07003090 viewRoot.dispatchResized(w, h, coveredInsets, visibleInsets, reportDraw, newConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003091 }
3092 }
3093
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003094 public void dispatchAppVisibility(boolean visible) {
3095 final ViewRoot viewRoot = mViewRoot.get();
3096 if (viewRoot != null) {
3097 viewRoot.dispatchAppVisibility(visible);
3098 }
3099 }
3100
3101 public void dispatchGetNewSurface() {
3102 final ViewRoot viewRoot = mViewRoot.get();
3103 if (viewRoot != null) {
3104 viewRoot.dispatchGetNewSurface();
3105 }
3106 }
3107
3108 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
3109 final ViewRoot viewRoot = mViewRoot.get();
3110 if (viewRoot != null) {
3111 viewRoot.windowFocusChanged(hasFocus, inTouchMode);
3112 }
3113 }
3114
3115 private static int checkCallingPermission(String permission) {
3116 if (!Process.supportsProcesses()) {
3117 return PackageManager.PERMISSION_GRANTED;
3118 }
3119
3120 try {
3121 return ActivityManagerNative.getDefault().checkPermission(
3122 permission, Binder.getCallingPid(), Binder.getCallingUid());
3123 } catch (RemoteException e) {
3124 return PackageManager.PERMISSION_DENIED;
3125 }
3126 }
3127
3128 public void executeCommand(String command, String parameters, ParcelFileDescriptor out) {
3129 final ViewRoot viewRoot = mViewRoot.get();
3130 if (viewRoot != null) {
3131 final View view = viewRoot.mView;
3132 if (view != null) {
3133 if (checkCallingPermission(Manifest.permission.DUMP) !=
3134 PackageManager.PERMISSION_GRANTED) {
3135 throw new SecurityException("Insufficient permissions to invoke"
3136 + " executeCommand() from pid=" + Binder.getCallingPid()
3137 + ", uid=" + Binder.getCallingUid());
3138 }
3139
3140 OutputStream clientStream = null;
3141 try {
3142 clientStream = new ParcelFileDescriptor.AutoCloseOutputStream(out);
3143 ViewDebug.dispatchCommand(view, command, parameters, clientStream);
3144 } catch (IOException e) {
3145 e.printStackTrace();
3146 } finally {
3147 if (clientStream != null) {
3148 try {
3149 clientStream.close();
3150 } catch (IOException e) {
3151 e.printStackTrace();
3152 }
3153 }
3154 }
3155 }
3156 }
3157 }
Dianne Hackborn72c82ab2009-08-11 21:13:54 -07003158
Dianne Hackbornffa42482009-09-23 22:20:11 -07003159 public void closeSystemDialogs(String reason) {
3160 final ViewRoot viewRoot = mViewRoot.get();
3161 if (viewRoot != null) {
3162 viewRoot.dispatchCloseSystemDialogs(reason);
3163 }
3164 }
3165
Marco Nelissenbf6956b2009-11-09 15:21:13 -08003166 public void dispatchWallpaperOffsets(float x, float y, float xStep, float yStep,
3167 boolean sync) {
Dianne Hackborn19382ac2009-09-11 21:13:37 -07003168 if (sync) {
3169 try {
3170 sWindowSession.wallpaperOffsetsComplete(asBinder());
3171 } catch (RemoteException e) {
3172 }
3173 }
Dianne Hackborn72c82ab2009-08-11 21:13:54 -07003174 }
Dianne Hackborn75804932009-10-20 20:15:20 -07003175
3176 public void dispatchWallpaperCommand(String action, int x, int y,
3177 int z, Bundle extras, boolean sync) {
3178 if (sync) {
3179 try {
3180 sWindowSession.wallpaperCommandComplete(asBinder(), null);
3181 } catch (RemoteException e) {
3182 }
3183 }
3184 }
Christopher Tatea53146c2010-09-07 11:57:52 -07003185
3186 /* Drag/drop */
3187 public void dispatchDragEvent(DragEvent event) {
3188 final ViewRoot viewRoot = mViewRoot.get();
3189 if (viewRoot != null) {
3190 viewRoot.dispatchDragEvent(event);
3191 }
3192 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003193 }
3194
3195 /**
3196 * Maintains state information for a single trackball axis, generating
3197 * discrete (DPAD) movements based on raw trackball motion.
3198 */
3199 static final class TrackballAxis {
3200 /**
3201 * The maximum amount of acceleration we will apply.
3202 */
3203 static final float MAX_ACCELERATION = 20;
Romain Guy8506ab42009-06-11 17:35:47 -07003204
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003205 /**
3206 * The maximum amount of time (in milliseconds) between events in order
3207 * for us to consider the user to be doing fast trackball movements,
3208 * and thus apply an acceleration.
3209 */
3210 static final long FAST_MOVE_TIME = 150;
Romain Guy8506ab42009-06-11 17:35:47 -07003211
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003212 /**
3213 * Scaling factor to the time (in milliseconds) between events to how
3214 * much to multiple/divide the current acceleration. When movement
3215 * is < FAST_MOVE_TIME this multiplies the acceleration; when >
3216 * FAST_MOVE_TIME it divides it.
3217 */
3218 static final float ACCEL_MOVE_SCALING_FACTOR = (1.0f/40);
Romain Guy8506ab42009-06-11 17:35:47 -07003219
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003220 float position;
3221 float absPosition;
3222 float acceleration = 1;
3223 long lastMoveTime = 0;
3224 int step;
3225 int dir;
3226 int nonAccelMovement;
3227
3228 void reset(int _step) {
3229 position = 0;
3230 acceleration = 1;
3231 lastMoveTime = 0;
3232 step = _step;
3233 dir = 0;
3234 }
3235
3236 /**
3237 * Add trackball movement into the state. If the direction of movement
3238 * has been reversed, the state is reset before adding the
3239 * movement (so that you don't have to compensate for any previously
3240 * collected movement before see the result of the movement in the
3241 * new direction).
3242 *
3243 * @return Returns the absolute value of the amount of movement
3244 * collected so far.
3245 */
3246 float collect(float off, long time, String axis) {
3247 long normTime;
3248 if (off > 0) {
3249 normTime = (long)(off * FAST_MOVE_TIME);
3250 if (dir < 0) {
3251 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to positive!");
3252 position = 0;
3253 step = 0;
3254 acceleration = 1;
3255 lastMoveTime = 0;
3256 }
3257 dir = 1;
3258 } else if (off < 0) {
3259 normTime = (long)((-off) * FAST_MOVE_TIME);
3260 if (dir > 0) {
3261 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to negative!");
3262 position = 0;
3263 step = 0;
3264 acceleration = 1;
3265 lastMoveTime = 0;
3266 }
3267 dir = -1;
3268 } else {
3269 normTime = 0;
3270 }
Romain Guy8506ab42009-06-11 17:35:47 -07003271
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003272 // The number of milliseconds between each movement that is
3273 // considered "normal" and will not result in any acceleration
3274 // or deceleration, scaled by the offset we have here.
3275 if (normTime > 0) {
3276 long delta = time - lastMoveTime;
3277 lastMoveTime = time;
3278 float acc = acceleration;
3279 if (delta < normTime) {
3280 // The user is scrolling rapidly, so increase acceleration.
3281 float scale = (normTime-delta) * ACCEL_MOVE_SCALING_FACTOR;
3282 if (scale > 1) acc *= scale;
3283 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " accelerate: off="
3284 + off + " normTime=" + normTime + " delta=" + delta
3285 + " scale=" + scale + " acc=" + acc);
3286 acceleration = acc < MAX_ACCELERATION ? acc : MAX_ACCELERATION;
3287 } else {
3288 // The user is scrolling slowly, so decrease acceleration.
3289 float scale = (delta-normTime) * ACCEL_MOVE_SCALING_FACTOR;
3290 if (scale > 1) acc /= scale;
3291 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " deccelerate: off="
3292 + off + " normTime=" + normTime + " delta=" + delta
3293 + " scale=" + scale + " acc=" + acc);
3294 acceleration = acc > 1 ? acc : 1;
3295 }
3296 }
3297 position += off;
3298 return (absPosition = Math.abs(position));
3299 }
3300
3301 /**
3302 * Generate the number of discrete movement events appropriate for
3303 * the currently collected trackball movement.
3304 *
3305 * @param precision The minimum movement required to generate the
3306 * first discrete movement.
3307 *
3308 * @return Returns the number of discrete movements, either positive
3309 * or negative, or 0 if there is not enough trackball movement yet
3310 * for a discrete movement.
3311 */
3312 int generate(float precision) {
3313 int movement = 0;
3314 nonAccelMovement = 0;
3315 do {
3316 final int dir = position >= 0 ? 1 : -1;
3317 switch (step) {
3318 // If we are going to execute the first step, then we want
3319 // to do this as soon as possible instead of waiting for
3320 // a full movement, in order to make things look responsive.
3321 case 0:
3322 if (absPosition < precision) {
3323 return movement;
3324 }
3325 movement += dir;
3326 nonAccelMovement += dir;
3327 step = 1;
3328 break;
3329 // If we have generated the first movement, then we need
3330 // to wait for the second complete trackball motion before
3331 // generating the second discrete movement.
3332 case 1:
3333 if (absPosition < 2) {
3334 return movement;
3335 }
3336 movement += dir;
3337 nonAccelMovement += dir;
3338 position += dir > 0 ? -2 : 2;
3339 absPosition = Math.abs(position);
3340 step = 2;
3341 break;
3342 // After the first two, we generate discrete movements
3343 // consistently with the trackball, applying an acceleration
3344 // if the trackball is moving quickly. This is a simple
3345 // acceleration on top of what we already compute based
3346 // on how quickly the wheel is being turned, to apply
3347 // a longer increasing acceleration to continuous movement
3348 // in one direction.
3349 default:
3350 if (absPosition < 1) {
3351 return movement;
3352 }
3353 movement += dir;
3354 position += dir >= 0 ? -1 : 1;
3355 absPosition = Math.abs(position);
3356 float acc = acceleration;
3357 acc *= 1.1f;
3358 acceleration = acc < MAX_ACCELERATION ? acc : acceleration;
3359 break;
3360 }
3361 } while (true);
3362 }
3363 }
3364
3365 public static final class CalledFromWrongThreadException extends AndroidRuntimeException {
3366 public CalledFromWrongThreadException(String msg) {
3367 super(msg);
3368 }
3369 }
3370
3371 private SurfaceHolder mHolder = new SurfaceHolder() {
3372 // we only need a SurfaceHolder for opengl. it would be nice
3373 // to implement everything else though, especially the callback
3374 // support (opengl doesn't make use of it right now, but eventually
3375 // will).
3376 public Surface getSurface() {
3377 return mSurface;
3378 }
3379
3380 public boolean isCreating() {
3381 return false;
3382 }
3383
3384 public void addCallback(Callback callback) {
3385 }
3386
3387 public void removeCallback(Callback callback) {
3388 }
3389
3390 public void setFixedSize(int width, int height) {
3391 }
3392
3393 public void setSizeFromLayout() {
3394 }
3395
3396 public void setFormat(int format) {
3397 }
3398
3399 public void setType(int type) {
3400 }
3401
3402 public void setKeepScreenOn(boolean screenOn) {
3403 }
3404
3405 public Canvas lockCanvas() {
3406 return null;
3407 }
3408
3409 public Canvas lockCanvas(Rect dirty) {
3410 return null;
3411 }
3412
3413 public void unlockCanvasAndPost(Canvas canvas) {
3414 }
3415 public Rect getSurfaceFrame() {
3416 return null;
3417 }
3418 };
3419
3420 static RunQueue getRunQueue() {
3421 RunQueue rq = sRunQueues.get();
3422 if (rq != null) {
3423 return rq;
3424 }
3425 rq = new RunQueue();
3426 sRunQueues.set(rq);
3427 return rq;
3428 }
Romain Guy8506ab42009-06-11 17:35:47 -07003429
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003430 /**
3431 * @hide
3432 */
3433 static final class RunQueue {
3434 private final ArrayList<HandlerAction> mActions = new ArrayList<HandlerAction>();
3435
3436 void post(Runnable action) {
3437 postDelayed(action, 0);
3438 }
3439
3440 void postDelayed(Runnable action, long delayMillis) {
3441 HandlerAction handlerAction = new HandlerAction();
3442 handlerAction.action = action;
3443 handlerAction.delay = delayMillis;
3444
3445 synchronized (mActions) {
3446 mActions.add(handlerAction);
3447 }
3448 }
3449
3450 void removeCallbacks(Runnable action) {
3451 final HandlerAction handlerAction = new HandlerAction();
3452 handlerAction.action = action;
3453
3454 synchronized (mActions) {
3455 final ArrayList<HandlerAction> actions = mActions;
3456
3457 while (actions.remove(handlerAction)) {
3458 // Keep going
3459 }
3460 }
3461 }
3462
3463 void executeActions(Handler handler) {
3464 synchronized (mActions) {
3465 final ArrayList<HandlerAction> actions = mActions;
3466 final int count = actions.size();
3467
3468 for (int i = 0; i < count; i++) {
3469 final HandlerAction handlerAction = actions.get(i);
3470 handler.postDelayed(handlerAction.action, handlerAction.delay);
3471 }
3472
Romain Guy15df6702009-08-17 20:17:30 -07003473 actions.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003474 }
3475 }
3476
3477 private static class HandlerAction {
3478 Runnable action;
3479 long delay;
3480
3481 @Override
3482 public boolean equals(Object o) {
3483 if (this == o) return true;
3484 if (o == null || getClass() != o.getClass()) return false;
3485
3486 HandlerAction that = (HandlerAction) o;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003487 return !(action != null ? !action.equals(that.action) : that.action != null);
3488
3489 }
3490
3491 @Override
3492 public int hashCode() {
3493 int result = action != null ? action.hashCode() : 0;
3494 result = 31 * result + (int) (delay ^ (delay >>> 32));
3495 return result;
3496 }
3497 }
3498 }
3499
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003500 private static native void nativeShowFPS(Canvas canvas, int durationMillis);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003501}