blob: 39f99b8c841246d8cd7c96513d6ec506b96b78aa [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.view;
18
Romain Guy6b7bd242010-10-06 19:49:23 -070019import android.Manifest;
20import android.app.ActivityManagerNative;
21import android.content.ClipDescription;
22import android.content.ComponentCallbacks;
23import android.content.Context;
24import android.content.pm.PackageManager;
25import android.content.res.CompatibilityInfo;
26import android.content.res.Configuration;
27import android.content.res.Resources;
Dianne Hackborn0f761d62010-11-30 22:06:10 -080028import android.graphics.Bitmap;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080029import android.graphics.Canvas;
Dianne Hackborn0f761d62010-11-30 22:06:10 -080030import android.graphics.Paint;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080031import android.graphics.PixelFormat;
Christopher Tate2c095f32010-10-04 14:13:40 -070032import android.graphics.Point;
Christopher Tatea53146c2010-09-07 11:57:52 -070033import android.graphics.PointF;
Romain Guy6b7bd242010-10-06 19:49:23 -070034import android.graphics.PorterDuff;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080035import android.graphics.Rect;
36import android.graphics.Region;
Romain Guy6b7bd242010-10-06 19:49:23 -070037import android.media.AudioManager;
38import android.os.Binder;
39import android.os.Bundle;
40import android.os.Debug;
41import android.os.Handler;
42import android.os.LatencyTimer;
43import android.os.Looper;
44import android.os.Message;
45import android.os.ParcelFileDescriptor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080046import android.os.Process;
Romain Guy6b7bd242010-10-06 19:49:23 -070047import android.os.RemoteException;
48import android.os.ServiceManager;
49import android.os.SystemClock;
50import android.os.SystemProperties;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080051import android.util.AndroidRuntimeException;
52import android.util.Config;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -070053import android.util.DisplayMetrics;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080054import android.util.EventLog;
Romain Guy6b7bd242010-10-06 19:49:23 -070055import android.util.Log;
Chet Haase949dbf72010-08-11 18:41:06 -070056import android.util.Slog;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080057import android.util.SparseArray;
Dianne Hackborn711e62a2010-11-29 16:38:22 -080058import android.util.TypedValue;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080059import android.view.View.MeasureSpec;
svetoslavganov75986cf2009-05-14 22:28:01 -070060import android.view.accessibility.AccessibilityEvent;
61import android.view.accessibility.AccessibilityManager;
Dianne Hackborn0f761d62010-11-30 22:06:10 -080062import android.view.animation.AccelerateDecelerateInterpolator;
63import android.view.animation.Interpolator;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080064import android.view.inputmethod.InputConnection;
65import android.view.inputmethod.InputMethodManager;
66import android.widget.Scroller;
Joe Onorato86f67862010-11-05 18:57:34 -070067import com.android.internal.policy.PolicyManager;
Romain Guy6b7bd242010-10-06 19:49:23 -070068import com.android.internal.view.BaseSurfaceHolder;
69import com.android.internal.view.IInputMethodCallback;
70import com.android.internal.view.IInputMethodSession;
71import com.android.internal.view.RootViewSurfaceTaker;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080072
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080073import java.io.IOException;
74import java.io.OutputStream;
Romain Guy6b7bd242010-10-06 19:49:23 -070075import java.lang.ref.WeakReference;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080076import java.util.ArrayList;
77
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080078/**
79 * The top of a view hierarchy, implementing the needed protocol between View
80 * and the WindowManager. This is for the most part an internal implementation
81 * detail of {@link WindowManagerImpl}.
82 *
83 * {@hide}
84 */
Romain Guy812ccbe2010-06-01 14:07:24 -070085@SuppressWarnings({"EmptyCatchBlock", "PointlessBooleanExpression"})
Dianne Hackborn0f761d62010-11-30 22:06:10 -080086public final class ViewRoot extends Handler implements ViewParent,
87 View.AttachInfo.Callbacks, HardwareRenderer.HardwareDrawCallbacks {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080088 private static final String TAG = "ViewRoot";
89 private static final boolean DBG = false;
Mike Reedfd716532009-10-12 14:42:56 -040090 private static final boolean SHOW_FPS = false;
Romain Guy812ccbe2010-06-01 14:07:24 -070091 private static final boolean LOCAL_LOGV = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080092 /** @noinspection PointlessBooleanExpression*/
93 private static final boolean DEBUG_DRAW = false || LOCAL_LOGV;
94 private static final boolean DEBUG_LAYOUT = false || LOCAL_LOGV;
Dianne Hackborn711e62a2010-11-29 16:38:22 -080095 private static final boolean DEBUG_DIALOG = false || LOCAL_LOGV;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080096 private static final boolean DEBUG_INPUT_RESIZE = false || LOCAL_LOGV;
97 private static final boolean DEBUG_ORIENTATION = false || LOCAL_LOGV;
98 private static final boolean DEBUG_TRACKBALL = false || LOCAL_LOGV;
99 private static final boolean DEBUG_IMF = false || LOCAL_LOGV;
Dianne Hackborn694f79b2010-03-17 19:44:59 -0700100 private static final boolean DEBUG_CONFIGURATION = false || LOCAL_LOGV;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800101 private static final boolean WATCH_POINTER = false;
102
Michael Chan53071d62009-05-13 17:29:48 -0700103 private static final boolean MEASURE_LATENCY = false;
104 private static LatencyTimer lt;
105
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800106 /**
107 * Maximum time we allow the user to roll the trackball enough to generate
108 * a key event, before resetting the counters.
109 */
110 static final int MAX_TRACKBALL_DELAY = 250;
111
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800112 static IWindowSession sWindowSession;
113
114 static final Object mStaticInit = new Object();
115 static boolean mInitialized = false;
116
117 static final ThreadLocal<RunQueue> sRunQueues = new ThreadLocal<RunQueue>();
118
Dianne Hackborn2a9094d2010-02-03 19:20:09 -0800119 static final ArrayList<Runnable> sFirstDrawHandlers = new ArrayList<Runnable>();
120 static boolean sFirstDrawComplete = false;
121
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800122 static final ArrayList<ComponentCallbacks> sConfigCallbacks
123 = new ArrayList<ComponentCallbacks>();
124
Romain Guy8506ab42009-06-11 17:35:47 -0700125 private static int sDrawTime;
Romain Guy13922e02009-05-12 17:56:14 -0700126
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800127 long mLastTrackballTime = 0;
128 final TrackballAxis mTrackballAxisX = new TrackballAxis();
129 final TrackballAxis mTrackballAxisY = new TrackballAxis();
130
Jeff Browncb1404e2011-01-15 18:14:15 -0800131 int mLastJoystickXDirection;
132 int mLastJoystickYDirection;
133 int mLastJoystickXKeyCode;
134 int mLastJoystickYKeyCode;
135
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800136 final int[] mTmpLocation = new int[2];
Romain Guy8506ab42009-06-11 17:35:47 -0700137
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800138 final TypedValue mTmpValue = new TypedValue();
139
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800140 final InputMethodCallback mInputMethodCallback;
141 final SparseArray<Object> mPendingEvents = new SparseArray<Object>();
142 int mPendingEventSeq = 0;
Romain Guy8506ab42009-06-11 17:35:47 -0700143
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800144 final Thread mThread;
145
146 final WindowLeaked mLocation;
147
148 final WindowManager.LayoutParams mWindowAttributes = new WindowManager.LayoutParams();
149
150 final W mWindow;
151
152 View mView;
153 View mFocusedView;
154 View mRealFocusedView; // this is not set to null in touch mode
155 int mViewVisibility;
156 boolean mAppVisible = true;
157
Dianne Hackbornd76b67c2010-07-13 17:48:30 -0700158 SurfaceHolder.Callback2 mSurfaceHolderCallback;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700159 BaseSurfaceHolder mSurfaceHolder;
160 boolean mIsCreating;
161 boolean mDrawingAllowed;
162
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800163 final Region mTransparentRegion;
164 final Region mPreviousTransparentRegion;
165
166 int mWidth;
167 int mHeight;
Romain Guy7d7b5492011-01-24 16:33:45 -0800168 Rect mDirty;
169 final Rect mCurrentDirty = new Rect();
170 final Rect mPreviousDirty = new Rect();
Romain Guybb93d552009-03-24 21:04:15 -0700171 boolean mIsAnimating;
Romain Guy8506ab42009-06-11 17:35:47 -0700172
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700173 CompatibilityInfo.Translator mTranslator;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800174
175 final View.AttachInfo mAttachInfo;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700176 InputChannel mInputChannel;
Dianne Hackborn1e4b9f32010-06-23 14:10:57 -0700177 InputQueue.Callback mInputQueueCallback;
178 InputQueue mInputQueue;
Joe Onorato86f67862010-11-05 18:57:34 -0700179 FallbackEventHandler mFallbackEventHandler;
Dianne Hackborna95e4cb2010-06-18 18:09:33 -0700180
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800181 final Rect mTempRect; // used in the transaction to not thrash the heap.
182 final Rect mVisRect; // used to retrieve visible rect of focused view.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800183
184 boolean mTraversalScheduled;
185 boolean mWillDrawSoon;
186 boolean mLayoutRequested;
187 boolean mFirst;
188 boolean mReportNextDraw;
189 boolean mFullRedrawNeeded;
190 boolean mNewSurfaceNeeded;
191 boolean mHasHadWindowFocus;
192 boolean mLastWasImTarget;
193
194 boolean mWindowAttributesChanged = false;
195
196 // These can be accessed by any thread, must be protected with a lock.
Mathias Agopian5583dc62009-07-09 16:28:11 -0700197 // Surface can never be reassigned or cleared (use Surface.clear()).
198 private final Surface mSurface = new Surface();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800199
200 boolean mAdded;
201 boolean mAddedTouchMode;
202
203 /*package*/ int mAddNesting;
204
205 // These are accessed by multiple threads.
206 final Rect mWinFrame; // frame given by window manager.
207
208 final Rect mPendingVisibleInsets = new Rect();
209 final Rect mPendingContentInsets = new Rect();
210 final ViewTreeObserver.InternalInsetsInfo mLastGivenInsets
211 = new ViewTreeObserver.InternalInsetsInfo();
212
Dianne Hackborn694f79b2010-03-17 19:44:59 -0700213 final Configuration mLastConfiguration = new Configuration();
214 final Configuration mPendingConfiguration = new Configuration();
215
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800216 class ResizedInfo {
217 Rect coveredInsets;
218 Rect visibleInsets;
219 Configuration newConfig;
220 }
221
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800222 boolean mScrollMayChange;
223 int mSoftInputMode;
224 View mLastScrolledFocus;
225 int mScrollY;
226 int mCurScrollY;
227 Scroller mScroller;
Dianne Hackborn0f761d62010-11-30 22:06:10 -0800228 Bitmap mResizeBitmap;
229 long mResizeBitmapStartTime;
230 int mResizeBitmapDuration;
231 static final Interpolator mResizeInterpolator = new AccelerateDecelerateInterpolator();
Romain Guy8506ab42009-06-11 17:35:47 -0700232
Romain Guy8506ab42009-06-11 17:35:47 -0700233 final ViewConfiguration mViewConfiguration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800234
Christopher Tatea53146c2010-09-07 11:57:52 -0700235 /* Drag/drop */
236 ClipDescription mDragDescription;
237 View mCurrentDragView;
Christopher Tate7fb8b562011-01-20 13:46:41 -0800238 volatile Object mLocalDragState;
Christopher Tatea53146c2010-09-07 11:57:52 -0700239 final PointF mDragPoint = new PointF();
Christopher Tate2c095f32010-10-04 14:13:40 -0700240 final PointF mLastTouchPoint = new PointF();
Christopher Tatea53146c2010-09-07 11:57:52 -0700241
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800242 /**
243 * see {@link #playSoundEffect(int)}
244 */
245 AudioManager mAudioManager;
246
Dianne Hackborn11ea3342009-07-22 21:48:55 -0700247 private final int mDensity;
Adam Powellb08013c2010-09-16 16:28:11 -0700248
Dianne Hackborn4c62fc02009-08-08 20:40:27 -0700249 public static IWindowSession getWindowSession(Looper mainLooper) {
250 synchronized (mStaticInit) {
251 if (!mInitialized) {
252 try {
253 InputMethodManager imm = InputMethodManager.getInstance(mainLooper);
254 sWindowSession = IWindowManager.Stub.asInterface(
255 ServiceManager.getService("window"))
256 .openSession(imm.getClient(), imm.getInputContext());
257 mInitialized = true;
258 } catch (RemoteException e) {
259 }
260 }
261 return sWindowSession;
262 }
263 }
264
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800265 public ViewRoot(Context context) {
266 super();
267
Romain Guy812ccbe2010-06-01 14:07:24 -0700268 if (MEASURE_LATENCY) {
269 if (lt == null) {
270 lt = new LatencyTimer(100, 1000);
271 }
Michael Chan53071d62009-05-13 17:29:48 -0700272 }
273
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800274 // Initialize the statics when this class is first instantiated. This is
275 // done here instead of in the static block because Zygote does not
276 // allow the spawning of threads.
Dianne Hackborn4c62fc02009-08-08 20:40:27 -0700277 getWindowSession(context.getMainLooper());
278
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800279 mThread = Thread.currentThread();
280 mLocation = new WindowLeaked(null);
281 mLocation.fillInStackTrace();
282 mWidth = -1;
283 mHeight = -1;
284 mDirty = new Rect();
285 mTempRect = new Rect();
286 mVisRect = new Rect();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800287 mWinFrame = new Rect();
Romain Guyfb8b7632010-08-23 21:05:08 -0700288 mWindow = new W(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800289 mInputMethodCallback = new InputMethodCallback(this);
290 mViewVisibility = View.GONE;
291 mTransparentRegion = new Region();
292 mPreviousTransparentRegion = new Region();
293 mFirst = true; // true for the first time the view is added
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800294 mAdded = false;
295 mAttachInfo = new View.AttachInfo(sWindowSession, mWindow, this, this);
296 mViewConfiguration = ViewConfiguration.get(context);
Dianne Hackborn11ea3342009-07-22 21:48:55 -0700297 mDensity = context.getResources().getDisplayMetrics().densityDpi;
Joe Onorato86f67862010-11-05 18:57:34 -0700298 mFallbackEventHandler = PolicyManager.makeNewFallbackEventHandler(context);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800299 }
300
Dianne Hackborn2a9094d2010-02-03 19:20:09 -0800301 public static void addFirstDrawHandler(Runnable callback) {
302 synchronized (sFirstDrawHandlers) {
303 if (!sFirstDrawComplete) {
304 sFirstDrawHandlers.add(callback);
305 }
306 }
307 }
308
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800309 public static void addConfigCallback(ComponentCallbacks callback) {
310 synchronized (sConfigCallbacks) {
311 sConfigCallbacks.add(callback);
312 }
313 }
314
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800315 // FIXME for perf testing only
316 private boolean mProfile = false;
317
318 /**
319 * Call this to profile the next traversal call.
320 * FIXME for perf testing only. Remove eventually
321 */
322 public void profile() {
323 mProfile = true;
324 }
325
326 /**
327 * Indicates whether we are in touch mode. Calling this method triggers an IPC
328 * call and should be avoided whenever possible.
329 *
330 * @return True, if the device is in touch mode, false otherwise.
331 *
332 * @hide
333 */
334 static boolean isInTouchMode() {
335 if (mInitialized) {
336 try {
337 return sWindowSession.getInTouchMode();
338 } catch (RemoteException e) {
339 }
340 }
341 return false;
342 }
343
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800344 /**
345 * We have one child
346 */
Romain Guye4d01122010-06-16 18:44:05 -0700347 public void setView(View view, WindowManager.LayoutParams attrs, View panelParentView) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800348 synchronized (this) {
349 if (mView == null) {
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700350 mView = view;
Joe Onorato86f67862010-11-05 18:57:34 -0700351 mFallbackEventHandler.setView(view);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700352 mWindowAttributes.copyFrom(attrs);
Mitsuru Oshima1ecf5d22009-07-06 17:20:38 -0700353 attrs = mWindowAttributes;
Romain Guye4d01122010-06-16 18:44:05 -0700354
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700355 if (view instanceof RootViewSurfaceTaker) {
356 mSurfaceHolderCallback =
357 ((RootViewSurfaceTaker)view).willYouTakeTheSurface();
358 if (mSurfaceHolderCallback != null) {
359 mSurfaceHolder = new TakenSurfaceHolder();
Dianne Hackborn289b9b62010-07-09 11:44:11 -0700360 mSurfaceHolder.setFormat(PixelFormat.UNKNOWN);
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700361 }
362 }
Romain Guy1aec9a22011-01-05 09:37:12 -0800363
364 // If the application owns the surface, don't enable hardware acceleration
365 if (mSurfaceHolder == null) {
366 enableHardwareAcceleration(attrs);
367 }
368
Mitsuru Oshima38ed7d772009-07-21 14:39:34 -0700369 Resources resources = mView.getContext().getResources();
370 CompatibilityInfo compatibilityInfo = resources.getCompatibilityInfo();
Mitsuru Oshima589cebe2009-07-22 20:38:58 -0700371 mTranslator = compatibilityInfo.getTranslator();
Mitsuru Oshima38ed7d772009-07-21 14:39:34 -0700372
373 if (mTranslator != null || !compatibilityInfo.supportsScreen()) {
Mitsuru Oshima240f8a72009-07-22 20:39:14 -0700374 mSurface.setCompatibleDisplayMetrics(resources.getDisplayMetrics(),
375 mTranslator);
Mitsuru Oshima38ed7d772009-07-21 14:39:34 -0700376 }
377
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -0700378 boolean restore = false;
Romain Guy35b38ce2009-10-07 13:38:55 -0700379 if (mTranslator != null) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -0700380 restore = true;
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700381 attrs.backup();
382 mTranslator.translateWindowLayout(attrs);
Mitsuru Oshima3d914922009-05-13 22:29:15 -0700383 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700384 if (DEBUG_LAYOUT) Log.d(TAG, "WindowLayout in setView:" + attrs);
385
Mitsuru Oshima1ecf5d22009-07-06 17:20:38 -0700386 if (!compatibilityInfo.supportsScreen()) {
387 attrs.flags |= WindowManager.LayoutParams.FLAG_COMPATIBLE_WINDOW;
388 }
389
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800390 mSoftInputMode = attrs.softInputMode;
391 mWindowAttributesChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800392 mAttachInfo.mRootView = view;
Romain Guy35b38ce2009-10-07 13:38:55 -0700393 mAttachInfo.mScalingRequired = mTranslator != null;
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700394 mAttachInfo.mApplicationScale =
395 mTranslator == null ? 1.0f : mTranslator.applicationScale;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800396 if (panelParentView != null) {
397 mAttachInfo.mPanelParentWindowToken
398 = panelParentView.getApplicationWindowToken();
399 }
400 mAdded = true;
401 int res; /* = WindowManagerImpl.ADD_OKAY; */
Romain Guy8506ab42009-06-11 17:35:47 -0700402
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800403 // Schedule the first layout -before- adding to the window
404 // manager, to make sure we do the relayout before receiving
405 // any other events from the system.
406 requestLayout();
Jeff Brown46b9ac02010-04-22 18:58:52 -0700407 mInputChannel = new InputChannel();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800408 try {
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700409 res = sWindowSession.add(mWindow, mWindowAttributes,
Jeff Brown46b9ac02010-04-22 18:58:52 -0700410 getHostVisibility(), mAttachInfo.mContentInsets,
411 mInputChannel);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800412 } catch (RemoteException e) {
413 mAdded = false;
414 mView = null;
415 mAttachInfo.mRootView = null;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700416 mInputChannel = null;
Joe Onorato86f67862010-11-05 18:57:34 -0700417 mFallbackEventHandler.setView(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800418 unscheduleTraversals();
419 throw new RuntimeException("Adding window failed", e);
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700420 } finally {
421 if (restore) {
422 attrs.restore();
423 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800424 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700425
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700426 if (mTranslator != null) {
427 mTranslator.translateRectInScreenToAppWindow(mAttachInfo.mContentInsets);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700428 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800429 mPendingContentInsets.set(mAttachInfo.mContentInsets);
430 mPendingVisibleInsets.set(0, 0, 0, 0);
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800431 if (DEBUG_LAYOUT) Log.v(TAG, "Added window " + mWindow);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800432 if (res < WindowManagerImpl.ADD_OKAY) {
433 mView = null;
434 mAttachInfo.mRootView = null;
435 mAdded = false;
Joe Onorato86f67862010-11-05 18:57:34 -0700436 mFallbackEventHandler.setView(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800437 unscheduleTraversals();
438 switch (res) {
439 case WindowManagerImpl.ADD_BAD_APP_TOKEN:
440 case WindowManagerImpl.ADD_BAD_SUBWINDOW_TOKEN:
441 throw new WindowManagerImpl.BadTokenException(
442 "Unable to add window -- token " + attrs.token
443 + " is not valid; is your activity running?");
444 case WindowManagerImpl.ADD_NOT_APP_TOKEN:
445 throw new WindowManagerImpl.BadTokenException(
446 "Unable to add window -- token " + attrs.token
447 + " is not for an application");
448 case WindowManagerImpl.ADD_APP_EXITING:
449 throw new WindowManagerImpl.BadTokenException(
450 "Unable to add window -- app for token " + attrs.token
451 + " is exiting");
452 case WindowManagerImpl.ADD_DUPLICATE_ADD:
453 throw new WindowManagerImpl.BadTokenException(
454 "Unable to add window -- window " + mWindow
455 + " has already been added");
456 case WindowManagerImpl.ADD_STARTING_NOT_NEEDED:
457 // Silently ignore -- we would have just removed it
458 // right away, anyway.
459 return;
460 case WindowManagerImpl.ADD_MULTIPLE_SINGLETON:
461 throw new WindowManagerImpl.BadTokenException(
462 "Unable to add window " + mWindow +
463 " -- another window of this type already exists");
464 case WindowManagerImpl.ADD_PERMISSION_DENIED:
465 throw new WindowManagerImpl.BadTokenException(
466 "Unable to add window " + mWindow +
467 " -- permission denied for this window type");
468 }
469 throw new RuntimeException(
470 "Unable to add window -- unknown error code " + res);
471 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700472
Jeff Brown00fa7bd2010-07-02 15:37:36 -0700473 if (view instanceof RootViewSurfaceTaker) {
474 mInputQueueCallback =
475 ((RootViewSurfaceTaker)view).willYouTakeTheInputQueue();
476 }
477 if (mInputQueueCallback != null) {
478 mInputQueue = new InputQueue(mInputChannel);
479 mInputQueueCallback.onInputQueueCreated(mInputQueue);
480 } else {
481 InputQueue.registerInputChannel(mInputChannel, mInputHandler,
482 Looper.myQueue());
Jeff Brown46b9ac02010-04-22 18:58:52 -0700483 }
484
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800485 view.assignParent(this);
486 mAddedTouchMode = (res&WindowManagerImpl.ADD_FLAG_IN_TOUCH_MODE) != 0;
487 mAppVisible = (res&WindowManagerImpl.ADD_FLAG_APP_VISIBLE) != 0;
488 }
489 }
490 }
491
Romain Guy529b60a2010-08-03 18:05:47 -0700492 private void enableHardwareAcceleration(WindowManager.LayoutParams attrs) {
Dianne Hackborn7eec10e2010-11-12 18:03:47 -0800493 mAttachInfo.mHardwareAccelerated = false;
494 mAttachInfo.mHardwareAccelerationRequested = false;
Romain Guy4f6aff32011-01-12 16:21:41 -0800495
Dianne Hackborn7eec10e2010-11-12 18:03:47 -0800496 // Try to enable hardware acceleration if requested
497 if (attrs != null &&
498 (attrs.flags & WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED) != 0) {
499 // Only enable hardware acceleration if we are not in the system process
500 // The window manager creates ViewRoots to display animated preview windows
501 // of launching apps and we don't want those to be hardware accelerated
502 if (!HardwareRenderer.sRendererDisabled) {
Romain Guyff26a0c2011-01-20 11:35:46 -0800503 // Don't enable hardware acceleration when we're not on the main thread
504 if (Looper.getMainLooper() != Looper.myLooper()) {
505 Log.w(HardwareRenderer.LOG_TAG, "Attempting to initialize hardware "
506 + "acceleration outside of the main thread, aborting");
507 return;
508 }
509
Romain Guye4d01122010-06-16 18:44:05 -0700510 final boolean translucent = attrs.format != PixelFormat.OPAQUE;
Romain Guyb051e892010-09-28 19:09:36 -0700511 if (mAttachInfo.mHardwareRenderer != null) {
512 mAttachInfo.mHardwareRenderer.destroy(true);
Romain Guy4caa4ed2010-08-25 14:46:24 -0700513 }
Romain Guyb051e892010-09-28 19:09:36 -0700514 mAttachInfo.mHardwareRenderer = HardwareRenderer.createGlRenderer(2, translucent);
Dianne Hackborn7eec10e2010-11-12 18:03:47 -0800515 mAttachInfo.mHardwareAccelerated = mAttachInfo.mHardwareAccelerationRequested
516 = mAttachInfo.mHardwareRenderer != null;
517 } else if (HardwareRenderer.isAvailable()) {
518 mAttachInfo.mHardwareAccelerationRequested = true;
Romain Guye4d01122010-06-16 18:44:05 -0700519 }
520 }
521 }
522
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800523 public View getView() {
524 return mView;
525 }
526
527 final WindowLeaked getLocation() {
528 return mLocation;
529 }
530
531 void setLayoutParams(WindowManager.LayoutParams attrs, boolean newView) {
532 synchronized (this) {
The Android Open Source Project10592532009-03-18 17:39:46 -0700533 int oldSoftInputMode = mWindowAttributes.softInputMode;
Mitsuru Oshima5a2b91d2009-07-16 16:30:02 -0700534 // preserve compatible window flag if exists.
535 int compatibleWindowFlag =
536 mWindowAttributes.flags & WindowManager.LayoutParams.FLAG_COMPATIBLE_WINDOW;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800537 mWindowAttributes.copyFrom(attrs);
Mitsuru Oshima5a2b91d2009-07-16 16:30:02 -0700538 mWindowAttributes.flags |= compatibleWindowFlag;
539
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800540 if (newView) {
541 mSoftInputMode = attrs.softInputMode;
542 requestLayout();
543 }
The Android Open Source Project10592532009-03-18 17:39:46 -0700544 // Don't lose the mode we last auto-computed.
545 if ((attrs.softInputMode&WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST)
546 == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED) {
547 mWindowAttributes.softInputMode = (mWindowAttributes.softInputMode
548 & ~WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST)
549 | (oldSoftInputMode
550 & WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST);
551 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800552 mWindowAttributesChanged = true;
553 scheduleTraversals();
554 }
555 }
556
557 void handleAppVisibility(boolean visible) {
558 if (mAppVisible != visible) {
559 mAppVisible = visible;
560 scheduleTraversals();
561 }
562 }
563
564 void handleGetNewSurface() {
565 mNewSurfaceNeeded = true;
566 mFullRedrawNeeded = true;
567 scheduleTraversals();
568 }
569
570 /**
571 * {@inheritDoc}
572 */
573 public void requestLayout() {
574 checkThread();
575 mLayoutRequested = true;
576 scheduleTraversals();
577 }
578
579 /**
580 * {@inheritDoc}
581 */
582 public boolean isLayoutRequested() {
583 return mLayoutRequested;
584 }
585
586 public void invalidateChild(View child, Rect dirty) {
587 checkThread();
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700588 if (DEBUG_DRAW) Log.v(TAG, "Invalidate child: " + dirty);
Chet Haase70d4ba12010-10-06 09:46:45 -0700589 if (dirty == null) {
590 // Fast invalidation for GL-enabled applications; GL must redraw everything
591 invalidate();
592 return;
593 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700594 if (mCurScrollY != 0 || mTranslator != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800595 mTempRect.set(dirty);
Romain Guy1e095972009-07-07 11:22:45 -0700596 dirty = mTempRect;
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700597 if (mCurScrollY != 0) {
Romain Guy1e095972009-07-07 11:22:45 -0700598 dirty.offset(0, -mCurScrollY);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700599 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700600 if (mTranslator != null) {
Romain Guy1e095972009-07-07 11:22:45 -0700601 mTranslator.translateRectInAppWindowToScreen(dirty);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700602 }
Romain Guy1e095972009-07-07 11:22:45 -0700603 if (mAttachInfo.mScalingRequired) {
604 dirty.inset(-1, -1);
605 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800606 }
Chet Haasedaf98e92011-01-10 14:10:36 -0800607 if (!mDirty.isEmpty() && !mDirty.contains(dirty)) {
Romain Guy7d695942010-12-01 17:22:29 -0800608 mAttachInfo.mIgnoreDirtyState = true;
609 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800610 mDirty.union(dirty);
611 if (!mWillDrawSoon) {
612 scheduleTraversals();
613 }
614 }
Romain Guy0d9275e2010-10-26 14:22:30 -0700615
616 void invalidate() {
617 mDirty.set(0, 0, mWidth, mHeight);
618 scheduleTraversals();
619 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800620
621 public ViewParent getParent() {
622 return null;
623 }
624
625 public ViewParent invalidateChildInParent(final int[] location, final Rect dirty) {
626 invalidateChild(null, dirty);
627 return null;
628 }
629
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700630 public boolean getChildVisibleRect(View child, Rect r, android.graphics.Point offset) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800631 if (child != mView) {
632 throw new RuntimeException("child is not mine, honest!");
633 }
634 // Note: don't apply scroll offset, because we want to know its
635 // visibility in the virtual canvas being given to the view hierarchy.
636 return r.intersect(0, 0, mWidth, mHeight);
637 }
638
639 public void bringChildToFront(View child) {
640 }
641
642 public void scheduleTraversals() {
643 if (!mTraversalScheduled) {
644 mTraversalScheduled = true;
645 sendEmptyMessage(DO_TRAVERSAL);
646 }
647 }
648
649 public void unscheduleTraversals() {
650 if (mTraversalScheduled) {
651 mTraversalScheduled = false;
652 removeMessages(DO_TRAVERSAL);
653 }
654 }
655
656 int getHostVisibility() {
657 return mAppVisible ? mView.getVisibility() : View.GONE;
658 }
Romain Guy8506ab42009-06-11 17:35:47 -0700659
Dianne Hackborn0f761d62010-11-30 22:06:10 -0800660 void disposeResizeBitmap() {
661 if (mResizeBitmap != null) {
662 mResizeBitmap.recycle();
663 mResizeBitmap = null;
664 }
665 }
666
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800667 private void performTraversals() {
668 // cache mView since it is used so much below...
669 final View host = mView;
670
671 if (DBG) {
672 System.out.println("======================================");
673 System.out.println("performTraversals");
674 host.debug();
675 }
676
677 if (host == null || !mAdded)
678 return;
679
680 mTraversalScheduled = false;
681 mWillDrawSoon = true;
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800682 boolean windowSizeMayChange = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800683 boolean fullRedrawNeeded = mFullRedrawNeeded;
684 boolean newSurface = false;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700685 boolean surfaceChanged = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800686 WindowManager.LayoutParams lp = mWindowAttributes;
687
688 int desiredWindowWidth;
689 int desiredWindowHeight;
690 int childWidthMeasureSpec;
691 int childHeightMeasureSpec;
692
693 final View.AttachInfo attachInfo = mAttachInfo;
694
695 final int viewVisibility = getHostVisibility();
696 boolean viewVisibilityChanged = mViewVisibility != viewVisibility
697 || mNewSurfaceNeeded;
698
699 WindowManager.LayoutParams params = null;
700 if (mWindowAttributesChanged) {
701 mWindowAttributesChanged = false;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700702 surfaceChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800703 params = lp;
704 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700705 Rect frame = mWinFrame;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800706 if (mFirst) {
707 fullRedrawNeeded = true;
708 mLayoutRequested = true;
709
Romain Guy8506ab42009-06-11 17:35:47 -0700710 DisplayMetrics packageMetrics =
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700711 mView.getContext().getResources().getDisplayMetrics();
712 desiredWindowWidth = packageMetrics.widthPixels;
713 desiredWindowHeight = packageMetrics.heightPixels;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800714
715 // For the very first time, tell the view hierarchy that it
716 // is attached to the window. Note that at this point the surface
717 // object is not initialized to its backing store, but soon it
718 // will be (assuming the window is visible).
719 attachInfo.mSurface = mSurface;
Romain Guyc5d55862011-01-21 19:01:46 -0800720 // We used to use the following condition to choose 32 bits drawing caches:
721 // PixelFormat.hasAlpha(lp.format) || lp.format == PixelFormat.RGBX_8888
722 // However, windows are now always 32 bits by default, so choose 32 bits
723 attachInfo.mUse32BitDrawingCache = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800724 attachInfo.mHasWindowFocus = false;
725 attachInfo.mWindowVisibility = viewVisibility;
726 attachInfo.mRecomputeGlobalAttributes = false;
727 attachInfo.mKeepScreenOn = false;
Joe Onorato664644d2011-01-23 17:53:23 -0800728 attachInfo.mSystemUiVisibility = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800729 viewVisibilityChanged = false;
Dianne Hackborn694f79b2010-03-17 19:44:59 -0700730 mLastConfiguration.setTo(host.getResources().getConfiguration());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800731 host.dispatchAttachedToWindow(attachInfo, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800732 //Log.i(TAG, "Screen on initialized: " + attachInfo.mKeepScreenOn);
svetoslavganov75986cf2009-05-14 22:28:01 -0700733
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800734 } else {
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700735 desiredWindowWidth = frame.width();
736 desiredWindowHeight = frame.height();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800737 if (desiredWindowWidth != mWidth || desiredWindowHeight != mHeight) {
Jeff Brownc5ed5912010-07-14 18:48:53 -0700738 if (DEBUG_ORIENTATION) Log.v(TAG,
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700739 "View " + host + " resized to: " + frame);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800740 fullRedrawNeeded = true;
741 mLayoutRequested = true;
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800742 windowSizeMayChange = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800743 }
744 }
745
746 if (viewVisibilityChanged) {
747 attachInfo.mWindowVisibility = viewVisibility;
748 host.dispatchWindowVisibilityChanged(viewVisibility);
749 if (viewVisibility != View.VISIBLE || mNewSurfaceNeeded) {
Romain Guyb051e892010-09-28 19:09:36 -0700750 if (mAttachInfo.mHardwareRenderer != null) {
751 mAttachInfo.mHardwareRenderer.destroy(false);
Romain Guy4caa4ed2010-08-25 14:46:24 -0700752 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800753 }
754 if (viewVisibility == View.GONE) {
755 // After making a window gone, we will count it as being
756 // shown for the first time the next time it gets focus.
757 mHasHadWindowFocus = false;
758 }
759 }
760
761 boolean insetsChanged = false;
Romain Guy8506ab42009-06-11 17:35:47 -0700762
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800763 if (mLayoutRequested) {
Romain Guy15df6702009-08-17 20:17:30 -0700764 // Execute enqueued actions on every layout in case a view that was detached
765 // enqueued an action after being detached
766 getRunQueue().executeActions(attachInfo.mHandler);
767
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800768 final Resources res = mView.getContext().getResources();
769
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800770 if (mFirst) {
771 host.fitSystemWindows(mAttachInfo.mContentInsets);
772 // make sure touch mode code executes by setting cached value
773 // to opposite of the added touch mode.
774 mAttachInfo.mInTouchMode = !mAddedTouchMode;
Romain Guy2d4cff62010-04-09 15:39:00 -0700775 ensureTouchModeLocally(mAddedTouchMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800776 } else {
777 if (!mAttachInfo.mContentInsets.equals(mPendingContentInsets)) {
Dianne Hackborn0f761d62010-11-30 22:06:10 -0800778 if (mWidth > 0 && mHeight > 0 &&
779 mSurface != null && mSurface.isValid() &&
Dianne Hackborn63042d62011-01-26 18:56:29 -0800780 !mAttachInfo.mTurnOffWindowResizeAnim &&
Dianne Hackborn0f761d62010-11-30 22:06:10 -0800781 mAttachInfo.mHardwareRenderer != null &&
782 mAttachInfo.mHardwareRenderer.isEnabled() &&
783 lp != null && !PixelFormat.formatHasAlpha(lp.format)) {
784
785 disposeResizeBitmap();
786
787 boolean completed = false;
788 try {
789 mResizeBitmap = Bitmap.createBitmap(mWidth, mHeight,
790 Bitmap.Config.ARGB_8888);
791 mResizeBitmap.setHasAlpha(false);
792 Canvas canvas = new Canvas(mResizeBitmap);
Romain Guyf90f8172011-01-25 22:53:24 -0800793 canvas.drawColor(0xff000000, PorterDuff.Mode.SRC);
Dianne Hackborn0f761d62010-11-30 22:06:10 -0800794 int yoff;
795 final boolean scrolling = mScroller != null
796 && mScroller.computeScrollOffset();
797 if (scrolling) {
798 yoff = mScroller.getCurrY();
799 mScroller.abortAnimation();
800 } else {
801 yoff = mScrollY;
802 }
803 canvas.translate(0, -yoff);
804 if (mTranslator != null) {
805 mTranslator.translateCanvas(canvas);
806 }
807 canvas.setScreenDensity(mAttachInfo.mScalingRequired
808 ? DisplayMetrics.DENSITY_DEVICE : 0);
809 mView.draw(canvas);
810 mResizeBitmapStartTime = SystemClock.uptimeMillis();
811 mResizeBitmapDuration = mView.getResources().getInteger(
812 com.android.internal.R.integer.config_mediumAnimTime);
813 completed = true;
814 } catch (OutOfMemoryError e) {
815 Log.w(TAG, "Not enough memory for content change anim buffer", e);
816 } finally {
817 if (!completed) {
818 mResizeBitmap = null;
819 }
820 }
821 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800822 mAttachInfo.mContentInsets.set(mPendingContentInsets);
823 host.fitSystemWindows(mAttachInfo.mContentInsets);
824 insetsChanged = true;
825 if (DEBUG_LAYOUT) Log.v(TAG, "Content insets changing to: "
826 + mAttachInfo.mContentInsets);
827 }
828 if (!mAttachInfo.mVisibleInsets.equals(mPendingVisibleInsets)) {
829 mAttachInfo.mVisibleInsets.set(mPendingVisibleInsets);
830 if (DEBUG_LAYOUT) Log.v(TAG, "Visible insets changing to: "
831 + mAttachInfo.mVisibleInsets);
832 }
833 if (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT
834 || lp.height == ViewGroup.LayoutParams.WRAP_CONTENT) {
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800835 windowSizeMayChange = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800836
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800837 DisplayMetrics packageMetrics = res.getDisplayMetrics();
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700838 desiredWindowWidth = packageMetrics.widthPixels;
839 desiredWindowHeight = packageMetrics.heightPixels;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800840 }
841 }
842
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800843 // Ask host how big it wants to be
Jeff Brownc5ed5912010-07-14 18:48:53 -0700844 if (DEBUG_ORIENTATION || DEBUG_LAYOUT) Log.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800845 "Measuring " + host + " in display " + desiredWindowWidth
846 + "x" + desiredWindowHeight + "...");
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800847
848 boolean goodMeasure = false;
849 if (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT
850 || lp.height == ViewGroup.LayoutParams.WRAP_CONTENT) {
851 // On large screens, we don't want to allow dialogs to just
852 // stretch to fill the entire width of the screen to display
853 // one line of text. First try doing the layout at a smaller
854 // size to see if it will fit.
855 final DisplayMetrics packageMetrics = res.getDisplayMetrics();
856 res.getValue(com.android.internal.R.dimen.config_prefDialogWidth, mTmpValue, true);
857 int baseSize = 0;
858 if (mTmpValue.type == TypedValue.TYPE_DIMENSION) {
859 baseSize = (int)mTmpValue.getDimension(packageMetrics);
860 }
861 if (DEBUG_DIALOG) Log.v(TAG, "Window " + mView + ": baseSize=" + baseSize);
Dianne Hackborn7d3a5bc2010-11-29 22:52:12 -0800862 if (baseSize != 0 && desiredWindowWidth > baseSize) {
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800863 childWidthMeasureSpec = getRootMeasureSpec(baseSize, lp.width);
864 childHeightMeasureSpec = getRootMeasureSpec(desiredWindowHeight, lp.height);
865 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
866 if (DEBUG_DIALOG) Log.v(TAG, "Window " + mView + ": measured ("
Dianne Hackborn189ee182010-12-02 21:48:53 -0800867 + host.getMeasuredWidth() + "," + host.getMeasuredHeight() + ")");
868 if ((host.getMeasuredWidthAndState()&View.MEASURED_STATE_TOO_SMALL) == 0) {
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800869 goodMeasure = true;
870 } else {
871 // Didn't fit in that size... try expanding a bit.
872 baseSize = (baseSize+desiredWindowWidth)/2;
873 if (DEBUG_DIALOG) Log.v(TAG, "Window " + mView + ": next baseSize="
874 + baseSize);
Dianne Hackborn189ee182010-12-02 21:48:53 -0800875 childWidthMeasureSpec = getRootMeasureSpec(baseSize, lp.width);
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800876 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
877 if (DEBUG_DIALOG) Log.v(TAG, "Window " + mView + ": measured ("
Dianne Hackborn189ee182010-12-02 21:48:53 -0800878 + host.getMeasuredWidth() + "," + host.getMeasuredHeight() + ")");
879 if ((host.getMeasuredWidthAndState()&View.MEASURED_STATE_TOO_SMALL) == 0) {
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800880 if (DEBUG_DIALOG) Log.v(TAG, "Good!");
881 goodMeasure = true;
882 }
883 }
884 }
885 }
886
887 if (!goodMeasure) {
888 childWidthMeasureSpec = getRootMeasureSpec(desiredWindowWidth, lp.width);
889 childHeightMeasureSpec = getRootMeasureSpec(desiredWindowHeight, lp.height);
890 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
Adam Powellaa0b92c2010-12-13 22:38:53 -0800891 if (mWidth != host.getMeasuredWidth() || mHeight != host.getMeasuredHeight()) {
892 windowSizeMayChange = true;
893 }
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800894 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800895
896 if (DBG) {
897 System.out.println("======================================");
898 System.out.println("performTraversals -- after measure");
899 host.debug();
900 }
901 }
902
Romain Guy6e81e572011-01-25 12:52:58 -0800903 if (attachInfo.mRecomputeGlobalAttributes && host.mAttachInfo != null) {
Joe Onorato664644d2011-01-23 17:53:23 -0800904 //Log.i(TAG, "Computing view hierarchy attributes!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800905 attachInfo.mRecomputeGlobalAttributes = false;
Joe Onorato664644d2011-01-23 17:53:23 -0800906 boolean oldScreenOn = attachInfo.mKeepScreenOn;
907 int oldVis = attachInfo.mSystemUiVisibility;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800908 attachInfo.mKeepScreenOn = false;
Joe Onorato664644d2011-01-23 17:53:23 -0800909 attachInfo.mSystemUiVisibility = 0;
910 attachInfo.mHasSystemUiListeners = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800911 host.dispatchCollectViewAttributes(0);
Joe Onorato14782f72011-01-25 19:53:17 -0800912 if (attachInfo.mKeepScreenOn != oldScreenOn
913 || attachInfo.mSystemUiVisibility != oldVis
914 || attachInfo.mHasSystemUiListeners) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800915 params = lp;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800916 }
917 }
918
919 if (mFirst || attachInfo.mViewVisibilityChanged) {
920 attachInfo.mViewVisibilityChanged = false;
921 int resizeMode = mSoftInputMode &
922 WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST;
923 // If we are in auto resize mode, then we need to determine
924 // what mode to use now.
925 if (resizeMode == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED) {
926 final int N = attachInfo.mScrollContainers.size();
927 for (int i=0; i<N; i++) {
928 if (attachInfo.mScrollContainers.get(i).isShown()) {
929 resizeMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE;
930 }
931 }
932 if (resizeMode == 0) {
933 resizeMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN;
934 }
935 if ((lp.softInputMode &
936 WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) != resizeMode) {
937 lp.softInputMode = (lp.softInputMode &
938 ~WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) |
939 resizeMode;
940 params = lp;
941 }
942 }
943 }
Romain Guy8506ab42009-06-11 17:35:47 -0700944
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800945 if (params != null && (host.mPrivateFlags & View.REQUEST_TRANSPARENT_REGIONS) != 0) {
946 if (!PixelFormat.formatHasAlpha(params.format)) {
947 params.format = PixelFormat.TRANSLUCENT;
948 }
949 }
950
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800951 boolean windowShouldResize = mLayoutRequested && windowSizeMayChange
Dianne Hackborn189ee182010-12-02 21:48:53 -0800952 && ((mWidth != host.getMeasuredWidth() || mHeight != host.getMeasuredHeight())
Romain Guy2e4f4262010-04-06 11:07:52 -0700953 || (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT &&
954 frame.width() < desiredWindowWidth && frame.width() != mWidth)
955 || (lp.height == ViewGroup.LayoutParams.WRAP_CONTENT &&
956 frame.height() < desiredWindowHeight && frame.height() != mHeight));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800957
958 final boolean computesInternalInsets =
959 attachInfo.mTreeObserver.hasComputeInternalInsetsListeners();
Romain Guy812ccbe2010-06-01 14:07:24 -0700960
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800961 boolean insetsPending = false;
962 int relayoutResult = 0;
Romain Guy812ccbe2010-06-01 14:07:24 -0700963
964 if (mFirst || windowShouldResize || insetsChanged ||
965 viewVisibilityChanged || params != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800966
967 if (viewVisibility == View.VISIBLE) {
968 // If this window is giving internal insets to the window
969 // manager, and it is being added or changing its visibility,
970 // then we want to first give the window manager "fake"
971 // insets to cause it to effectively ignore the content of
972 // the window during layout. This avoids it briefly causing
973 // other windows to resize/move based on the raw frame of the
974 // window, waiting until we can finish laying out this window
975 // and get back to the window manager with the ultimately
976 // computed insets.
Romain Guy812ccbe2010-06-01 14:07:24 -0700977 insetsPending = computesInternalInsets && (mFirst || viewVisibilityChanged);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800978 }
979
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700980 if (mSurfaceHolder != null) {
981 mSurfaceHolder.mSurfaceLock.lock();
982 mDrawingAllowed = true;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700983 }
Romain Guy812ccbe2010-06-01 14:07:24 -0700984
Romain Guyc361da82010-10-25 15:29:10 -0700985 boolean hwInitialized = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800986 boolean contentInsetsChanged = false;
Romain Guy13922e02009-05-12 17:56:14 -0700987 boolean visibleInsetsChanged;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700988 boolean hadSurface = mSurface.isValid();
Romain Guy812ccbe2010-06-01 14:07:24 -0700989
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800990 try {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800991 int fl = 0;
992 if (params != null) {
993 fl = params.flags;
994 if (attachInfo.mKeepScreenOn) {
995 params.flags |= WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
996 }
Joe Onorato14782f72011-01-25 19:53:17 -0800997 params.subtreeSystemUiVisibility = attachInfo.mSystemUiVisibility;
998 params.hasSystemUiListeners = attachInfo.mHasSystemUiListeners
999 || params.subtreeSystemUiVisibility != 0
1000 || params.systemUiVisibility != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001001 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001002 if (DEBUG_LAYOUT) {
Dianne Hackborn189ee182010-12-02 21:48:53 -08001003 Log.i(TAG, "host=w:" + host.getMeasuredWidth() + ", h:" +
1004 host.getMeasuredHeight() + ", params=" + params);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001005 }
Romain Guy2a83f002011-01-18 18:28:21 -08001006
1007 final int surfaceGenerationId = mSurface.getGenerationId();
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001008 relayoutResult = relayoutWindow(params, viewVisibility, insetsPending);
1009
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001010 if (params != null) {
1011 params.flags = fl;
1012 }
1013
1014 if (DEBUG_LAYOUT) Log.v(TAG, "relayout: frame=" + frame.toShortString()
1015 + " content=" + mPendingContentInsets.toShortString()
1016 + " visible=" + mPendingVisibleInsets.toShortString()
1017 + " surface=" + mSurface);
Romain Guy8506ab42009-06-11 17:35:47 -07001018
Dianne Hackborn694f79b2010-03-17 19:44:59 -07001019 if (mPendingConfiguration.seq != 0) {
1020 if (DEBUG_CONFIGURATION) Log.v(TAG, "Visible with new config: "
1021 + mPendingConfiguration);
1022 updateConfiguration(mPendingConfiguration, !mFirst);
1023 mPendingConfiguration.seq = 0;
1024 }
1025
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001026 contentInsetsChanged = !mPendingContentInsets.equals(
1027 mAttachInfo.mContentInsets);
1028 visibleInsetsChanged = !mPendingVisibleInsets.equals(
1029 mAttachInfo.mVisibleInsets);
1030 if (contentInsetsChanged) {
1031 mAttachInfo.mContentInsets.set(mPendingContentInsets);
1032 host.fitSystemWindows(mAttachInfo.mContentInsets);
1033 if (DEBUG_LAYOUT) Log.v(TAG, "Content insets changing to: "
1034 + mAttachInfo.mContentInsets);
1035 }
1036 if (visibleInsetsChanged) {
1037 mAttachInfo.mVisibleInsets.set(mPendingVisibleInsets);
1038 if (DEBUG_LAYOUT) Log.v(TAG, "Visible insets changing to: "
1039 + mAttachInfo.mVisibleInsets);
1040 }
1041
1042 if (!hadSurface) {
1043 if (mSurface.isValid()) {
1044 // If we are creating a new surface, then we need to
1045 // completely redraw it. Also, when we get to the
1046 // point of drawing it we will hold off and schedule
1047 // a new traversal instead. This is so we can tell the
1048 // window manager about all of the windows being displayed
1049 // before actually drawing them, so it can display then
1050 // all at once.
1051 newSurface = true;
1052 fullRedrawNeeded = true;
Jack Palevich61a6e682009-10-09 17:37:50 -07001053 mPreviousTransparentRegion.setEmpty();
Romain Guy8506ab42009-06-11 17:35:47 -07001054
Romain Guyb051e892010-09-28 19:09:36 -07001055 if (mAttachInfo.mHardwareRenderer != null) {
Romain Guyc361da82010-10-25 15:29:10 -07001056 hwInitialized = mAttachInfo.mHardwareRenderer.initialize(mHolder);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001057 }
1058 }
1059 } else if (!mSurface.isValid()) {
1060 // If the surface has been removed, then reset the scroll
1061 // positions.
1062 mLastScrolledFocus = null;
1063 mScrollY = mCurScrollY = 0;
1064 if (mScroller != null) {
1065 mScroller.abortAnimation();
1066 }
Dianne Hackborn0f761d62010-11-30 22:06:10 -08001067 disposeResizeBitmap();
Romain Guy2a83f002011-01-18 18:28:21 -08001068 } else if (surfaceGenerationId != mSurface.getGenerationId() &&
1069 mSurfaceHolder == null && mAttachInfo.mHardwareRenderer != null) {
Romain Guy7d7b5492011-01-24 16:33:45 -08001070 fullRedrawNeeded = true;
Romain Guy2a83f002011-01-18 18:28:21 -08001071 mAttachInfo.mHardwareRenderer.updateSurface(mHolder);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001072 }
1073 } catch (RemoteException e) {
1074 }
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001075
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001076 if (DEBUG_ORIENTATION) Log.v(
Jeff Brownc5ed5912010-07-14 18:48:53 -07001077 TAG, "Relayout returned: frame=" + frame + ", surface=" + mSurface);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001078
1079 attachInfo.mWindowLeft = frame.left;
1080 attachInfo.mWindowTop = frame.top;
1081
1082 // !!FIXME!! This next section handles the case where we did not get the
1083 // window size we asked for. We should avoid this by getting a maximum size from
1084 // the window session beforehand.
1085 mWidth = frame.width();
1086 mHeight = frame.height();
1087
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001088 if (mSurfaceHolder != null) {
1089 // The app owns the surface; tell it about what is going on.
1090 if (mSurface.isValid()) {
1091 // XXX .copyFrom() doesn't work!
1092 //mSurfaceHolder.mSurface.copyFrom(mSurface);
1093 mSurfaceHolder.mSurface = mSurface;
1094 }
Jeff Brown30bc34f2011-01-25 12:56:56 -08001095 mSurfaceHolder.setSurfaceFrameSize(mWidth, mHeight);
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001096 mSurfaceHolder.mSurfaceLock.unlock();
1097 if (mSurface.isValid()) {
1098 if (!hadSurface) {
1099 mSurfaceHolder.ungetCallbacks();
1100
1101 mIsCreating = true;
1102 mSurfaceHolderCallback.surfaceCreated(mSurfaceHolder);
1103 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
1104 if (callbacks != null) {
1105 for (SurfaceHolder.Callback c : callbacks) {
1106 c.surfaceCreated(mSurfaceHolder);
1107 }
1108 }
1109 surfaceChanged = true;
1110 }
1111 if (surfaceChanged) {
1112 mSurfaceHolderCallback.surfaceChanged(mSurfaceHolder,
1113 lp.format, mWidth, mHeight);
1114 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
1115 if (callbacks != null) {
1116 for (SurfaceHolder.Callback c : callbacks) {
1117 c.surfaceChanged(mSurfaceHolder, lp.format,
1118 mWidth, mHeight);
1119 }
1120 }
1121 }
1122 mIsCreating = false;
1123 } else if (hadSurface) {
1124 mSurfaceHolder.ungetCallbacks();
1125 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
1126 mSurfaceHolderCallback.surfaceDestroyed(mSurfaceHolder);
1127 if (callbacks != null) {
1128 for (SurfaceHolder.Callback c : callbacks) {
1129 c.surfaceDestroyed(mSurfaceHolder);
1130 }
1131 }
1132 mSurfaceHolder.mSurfaceLock.lock();
1133 // Make surface invalid.
1134 //mSurfaceHolder.mSurface.copyFrom(mSurface);
1135 mSurfaceHolder.mSurface = new Surface();
1136 mSurfaceHolder.mSurfaceLock.unlock();
1137 }
1138 }
Romain Guy53389bd2010-09-07 17:16:32 -07001139
Romain Guy6b5108b2011-01-04 16:11:10 -08001140 if (hwInitialized || ((windowShouldResize || params != null) &&
Romain Guydbf78bd2010-12-07 17:04:03 -08001141 mAttachInfo.mHardwareRenderer != null &&
1142 mAttachInfo.mHardwareRenderer.isEnabled())) {
Romain Guyb051e892010-09-28 19:09:36 -07001143 mAttachInfo.mHardwareRenderer.setup(mWidth, mHeight);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001144 }
1145
1146 boolean focusChangedDueToTouchMode = ensureTouchModeLocally(
Romain Guy2d4cff62010-04-09 15:39:00 -07001147 (relayoutResult&WindowManagerImpl.RELAYOUT_IN_TOUCH_MODE) != 0);
Dianne Hackborn189ee182010-12-02 21:48:53 -08001148 if (focusChangedDueToTouchMode || mWidth != host.getMeasuredWidth()
1149 || mHeight != host.getMeasuredHeight() || contentInsetsChanged) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001150 childWidthMeasureSpec = getRootMeasureSpec(mWidth, lp.width);
1151 childHeightMeasureSpec = getRootMeasureSpec(mHeight, lp.height);
1152
1153 if (DEBUG_LAYOUT) Log.v(TAG, "Ooops, something changed! mWidth="
Dianne Hackborn189ee182010-12-02 21:48:53 -08001154 + mWidth + " measuredWidth=" + host.getMeasuredWidth()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001155 + " mHeight=" + mHeight
Dianne Hackbornff801ec2011-01-22 18:05:38 -08001156 + " measuredHeight=" + host.getMeasuredHeight()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001157 + " coveredInsetsChanged=" + contentInsetsChanged);
Romain Guy8506ab42009-06-11 17:35:47 -07001158
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001159 // Ask host how big it wants to be
1160 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
1161
1162 // Implementation of weights from WindowManager.LayoutParams
1163 // We just grow the dimensions as needed and re-measure if
1164 // needs be
Dianne Hackborn189ee182010-12-02 21:48:53 -08001165 int width = host.getMeasuredWidth();
1166 int height = host.getMeasuredHeight();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001167 boolean measureAgain = false;
1168
1169 if (lp.horizontalWeight > 0.0f) {
1170 width += (int) ((mWidth - width) * lp.horizontalWeight);
1171 childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(width,
1172 MeasureSpec.EXACTLY);
1173 measureAgain = true;
1174 }
1175 if (lp.verticalWeight > 0.0f) {
1176 height += (int) ((mHeight - height) * lp.verticalWeight);
1177 childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(height,
1178 MeasureSpec.EXACTLY);
1179 measureAgain = true;
1180 }
1181
1182 if (measureAgain) {
1183 if (DEBUG_LAYOUT) Log.v(TAG,
1184 "And hey let's measure once more: width=" + width
1185 + " height=" + height);
1186 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
1187 }
1188
1189 mLayoutRequested = true;
1190 }
1191 }
1192
1193 final boolean didLayout = mLayoutRequested;
1194 boolean triggerGlobalLayoutListener = didLayout
1195 || attachInfo.mRecomputeGlobalAttributes;
1196 if (didLayout) {
1197 mLayoutRequested = false;
1198 mScrollMayChange = true;
1199 if (DEBUG_ORIENTATION || DEBUG_LAYOUT) Log.v(
Jeff Brownc5ed5912010-07-14 18:48:53 -07001200 TAG, "Laying out " + host + " to (" +
Dianne Hackborn189ee182010-12-02 21:48:53 -08001201 host.getMeasuredWidth() + ", " + host.getMeasuredHeight() + ")");
Romain Guy13922e02009-05-12 17:56:14 -07001202 long startTime = 0L;
Romain Guy5429e1d2010-09-07 12:38:00 -07001203 if (ViewDebug.DEBUG_PROFILE_LAYOUT) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001204 startTime = SystemClock.elapsedRealtime();
1205 }
Dianne Hackborn189ee182010-12-02 21:48:53 -08001206 host.layout(0, 0, host.getMeasuredWidth(), host.getMeasuredHeight());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001207
Romain Guy13922e02009-05-12 17:56:14 -07001208 if (Config.DEBUG && ViewDebug.consistencyCheckEnabled) {
1209 if (!host.dispatchConsistencyCheck(ViewDebug.CONSISTENCY_LAYOUT)) {
1210 throw new IllegalStateException("The view hierarchy is an inconsistent state,"
1211 + "please refer to the logs with the tag "
1212 + ViewDebug.CONSISTENCY_LOG_TAG + " for more infomation.");
1213 }
1214 }
1215
Romain Guy5429e1d2010-09-07 12:38:00 -07001216 if (ViewDebug.DEBUG_PROFILE_LAYOUT) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001217 EventLog.writeEvent(60001, SystemClock.elapsedRealtime() - startTime);
1218 }
1219
1220 // By this point all views have been sized and positionned
1221 // We can compute the transparent area
1222
1223 if ((host.mPrivateFlags & View.REQUEST_TRANSPARENT_REGIONS) != 0) {
1224 // start out transparent
1225 // TODO: AVOID THAT CALL BY CACHING THE RESULT?
1226 host.getLocationInWindow(mTmpLocation);
1227 mTransparentRegion.set(mTmpLocation[0], mTmpLocation[1],
1228 mTmpLocation[0] + host.mRight - host.mLeft,
1229 mTmpLocation[1] + host.mBottom - host.mTop);
1230
1231 host.gatherTransparentRegion(mTransparentRegion);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001232 if (mTranslator != null) {
1233 mTranslator.translateRegionInWindowToScreen(mTransparentRegion);
1234 }
1235
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001236 if (!mTransparentRegion.equals(mPreviousTransparentRegion)) {
1237 mPreviousTransparentRegion.set(mTransparentRegion);
1238 // reconfigure window manager
1239 try {
1240 sWindowSession.setTransparentRegion(mWindow, mTransparentRegion);
1241 } catch (RemoteException e) {
1242 }
1243 }
1244 }
1245
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001246 if (DBG) {
1247 System.out.println("======================================");
1248 System.out.println("performTraversals -- after setFrame");
1249 host.debug();
1250 }
1251 }
1252
1253 if (triggerGlobalLayoutListener) {
1254 attachInfo.mRecomputeGlobalAttributes = false;
1255 attachInfo.mTreeObserver.dispatchOnGlobalLayout();
1256 }
1257
1258 if (computesInternalInsets) {
Jeff Brownfbf09772011-01-16 14:06:57 -08001259 // Clear the original insets.
1260 final ViewTreeObserver.InternalInsetsInfo insets = attachInfo.mGivenInternalInsets;
1261 insets.reset();
1262
1263 // Compute new insets in place.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001264 attachInfo.mTreeObserver.dispatchOnComputeInternalInsets(insets);
Jeff Brownfbf09772011-01-16 14:06:57 -08001265
1266 // Tell the window manager.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001267 if (insetsPending || !mLastGivenInsets.equals(insets)) {
1268 mLastGivenInsets.set(insets);
Jeff Brownfbf09772011-01-16 14:06:57 -08001269
1270 // Translate insets to screen coordinates if needed.
1271 final Rect contentInsets;
1272 final Rect visibleInsets;
1273 final Region touchableRegion;
1274 if (mTranslator != null) {
1275 contentInsets = mTranslator.getTranslatedContentInsets(insets.contentInsets);
1276 visibleInsets = mTranslator.getTranslatedVisibleInsets(insets.visibleInsets);
1277 touchableRegion = mTranslator.getTranslatedTouchableArea(insets.touchableRegion);
1278 } else {
1279 contentInsets = insets.contentInsets;
1280 visibleInsets = insets.visibleInsets;
1281 touchableRegion = insets.touchableRegion;
1282 }
1283
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001284 try {
1285 sWindowSession.setInsets(mWindow, insets.mTouchableInsets,
Jeff Brownfbf09772011-01-16 14:06:57 -08001286 contentInsets, visibleInsets, touchableRegion);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001287 } catch (RemoteException e) {
1288 }
1289 }
1290 }
Romain Guy8506ab42009-06-11 17:35:47 -07001291
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001292 if (mFirst) {
1293 // handle first focus request
1294 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: mView.hasFocus()="
1295 + mView.hasFocus());
1296 if (mView != null) {
1297 if (!mView.hasFocus()) {
1298 mView.requestFocus(View.FOCUS_FORWARD);
1299 mFocusedView = mRealFocusedView = mView.findFocus();
1300 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: requested focused view="
1301 + mFocusedView);
1302 } else {
1303 mRealFocusedView = mView.findFocus();
1304 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: existing focused view="
1305 + mRealFocusedView);
1306 }
1307 }
1308 }
1309
1310 mFirst = false;
1311 mWillDrawSoon = false;
1312 mNewSurfaceNeeded = false;
1313 mViewVisibility = viewVisibility;
1314
1315 if (mAttachInfo.mHasWindowFocus) {
1316 final boolean imTarget = WindowManager.LayoutParams
1317 .mayUseInputMethod(mWindowAttributes.flags);
1318 if (imTarget != mLastWasImTarget) {
1319 mLastWasImTarget = imTarget;
1320 InputMethodManager imm = InputMethodManager.peekInstance();
1321 if (imm != null && imTarget) {
1322 imm.startGettingWindowFocus(mView);
1323 imm.onWindowFocus(mView, mView.findFocus(),
1324 mWindowAttributes.softInputMode,
1325 !mHasHadWindowFocus, mWindowAttributes.flags);
1326 }
1327 }
1328 }
Romain Guy8506ab42009-06-11 17:35:47 -07001329
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001330 boolean cancelDraw = attachInfo.mTreeObserver.dispatchOnPreDraw();
1331
1332 if (!cancelDraw && !newSurface) {
1333 mFullRedrawNeeded = false;
1334 draw(fullRedrawNeeded);
1335
1336 if ((relayoutResult&WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0
1337 || mReportNextDraw) {
1338 if (LOCAL_LOGV) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001339 Log.v(TAG, "FINISHED DRAWING: " + mWindowAttributes.getTitle());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001340 }
1341 mReportNextDraw = false;
Dianne Hackbornd76b67c2010-07-13 17:48:30 -07001342 if (mSurfaceHolder != null && mSurface.isValid()) {
1343 mSurfaceHolderCallback.surfaceRedrawNeeded(mSurfaceHolder);
1344 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
1345 if (callbacks != null) {
1346 for (SurfaceHolder.Callback c : callbacks) {
1347 if (c instanceof SurfaceHolder.Callback2) {
1348 ((SurfaceHolder.Callback2)c).surfaceRedrawNeeded(
1349 mSurfaceHolder);
1350 }
1351 }
1352 }
1353 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001354 try {
1355 sWindowSession.finishDrawing(mWindow);
1356 } catch (RemoteException e) {
1357 }
1358 }
1359 } else {
1360 // We were supposed to report when we are done drawing. Since we canceled the
1361 // draw, remember it here.
1362 if ((relayoutResult&WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0) {
1363 mReportNextDraw = true;
1364 }
1365 if (fullRedrawNeeded) {
1366 mFullRedrawNeeded = true;
1367 }
1368 // Try again
1369 scheduleTraversals();
1370 }
1371 }
1372
1373 public void requestTransparentRegion(View child) {
1374 // the test below should not fail unless someone is messing with us
1375 checkThread();
1376 if (mView == child) {
1377 mView.mPrivateFlags |= View.REQUEST_TRANSPARENT_REGIONS;
1378 // Need to make sure we re-evaluate the window attributes next
1379 // time around, to ensure the window has the correct format.
1380 mWindowAttributesChanged = true;
Mathias Agopian1bd80ad2010-11-04 17:13:39 -07001381 requestLayout();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001382 }
1383 }
1384
1385 /**
1386 * Figures out the measure spec for the root view in a window based on it's
1387 * layout params.
1388 *
1389 * @param windowSize
1390 * The available width or height of the window
1391 *
1392 * @param rootDimension
1393 * The layout params for one dimension (width or height) of the
1394 * window.
1395 *
1396 * @return The measure spec to use to measure the root view.
1397 */
1398 private int getRootMeasureSpec(int windowSize, int rootDimension) {
1399 int measureSpec;
1400 switch (rootDimension) {
1401
Romain Guy980a9382010-01-08 15:06:28 -08001402 case ViewGroup.LayoutParams.MATCH_PARENT:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001403 // Window can't resize. Force root view to be windowSize.
1404 measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.EXACTLY);
1405 break;
1406 case ViewGroup.LayoutParams.WRAP_CONTENT:
1407 // Window can resize. Set max size for root view.
1408 measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.AT_MOST);
1409 break;
1410 default:
1411 // Window wants to be an exact size. Force root view to be that size.
1412 measureSpec = MeasureSpec.makeMeasureSpec(rootDimension, MeasureSpec.EXACTLY);
1413 break;
1414 }
1415 return measureSpec;
1416 }
1417
Dianne Hackborn0f761d62010-11-30 22:06:10 -08001418 int mHardwareYOffset;
1419 int mResizeAlpha;
1420 final Paint mResizePaint = new Paint();
1421
1422 public void onHardwarePreDraw(Canvas canvas) {
1423 canvas.translate(0, -mHardwareYOffset);
1424 }
1425
1426 public void onHardwarePostDraw(Canvas canvas) {
1427 if (mResizeBitmap != null) {
1428 canvas.translate(0, mHardwareYOffset);
1429 mResizePaint.setAlpha(mResizeAlpha);
1430 canvas.drawBitmap(mResizeBitmap, 0, 0, mResizePaint);
1431 }
1432 }
1433
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001434 private void draw(boolean fullRedrawNeeded) {
1435 Surface surface = mSurface;
1436 if (surface == null || !surface.isValid()) {
1437 return;
1438 }
1439
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001440 if (!sFirstDrawComplete) {
1441 synchronized (sFirstDrawHandlers) {
1442 sFirstDrawComplete = true;
Romain Guy812ccbe2010-06-01 14:07:24 -07001443 final int count = sFirstDrawHandlers.size();
1444 for (int i = 0; i< count; i++) {
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001445 post(sFirstDrawHandlers.get(i));
1446 }
1447 }
1448 }
1449
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001450 scrollToRectOrFocus(null, false);
1451
1452 if (mAttachInfo.mViewScrollChanged) {
1453 mAttachInfo.mViewScrollChanged = false;
1454 mAttachInfo.mTreeObserver.dispatchOnScrollChanged();
1455 }
Romain Guy8506ab42009-06-11 17:35:47 -07001456
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001457 int yoff;
Dianne Hackborn0f761d62010-11-30 22:06:10 -08001458 boolean animating = mScroller != null && mScroller.computeScrollOffset();
1459 if (animating) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001460 yoff = mScroller.getCurrY();
1461 } else {
1462 yoff = mScrollY;
1463 }
1464 if (mCurScrollY != yoff) {
1465 mCurScrollY = yoff;
1466 fullRedrawNeeded = true;
1467 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001468 float appScale = mAttachInfo.mApplicationScale;
1469 boolean scalingRequired = mAttachInfo.mScalingRequired;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001470
Dianne Hackborn0f761d62010-11-30 22:06:10 -08001471 int resizeAlpha = 0;
1472 if (mResizeBitmap != null) {
1473 long deltaTime = SystemClock.uptimeMillis() - mResizeBitmapStartTime;
1474 if (deltaTime < mResizeBitmapDuration) {
1475 float amt = deltaTime/(float)mResizeBitmapDuration;
1476 amt = mResizeInterpolator.getInterpolation(amt);
1477 animating = true;
1478 resizeAlpha = 255 - (int)(amt*255);
1479 } else {
1480 disposeResizeBitmap();
1481 }
1482 }
1483
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001484 Rect dirty = mDirty;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001485 if (mSurfaceHolder != null) {
1486 // The app owns the surface, we won't draw.
1487 dirty.setEmpty();
Dianne Hackborn0f761d62010-11-30 22:06:10 -08001488 if (animating) {
1489 if (mScroller != null) {
1490 mScroller.abortAnimation();
1491 }
1492 disposeResizeBitmap();
1493 }
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001494 return;
1495 }
Romain Guy58ef7fb2010-09-13 12:52:37 -07001496
1497 if (fullRedrawNeeded) {
1498 mAttachInfo.mIgnoreDirtyState = true;
1499 dirty.union(0, 0, (int) (mWidth * appScale + 0.5f), (int) (mHeight * appScale + 0.5f));
1500 }
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001501
Romain Guyb051e892010-09-28 19:09:36 -07001502 if (mAttachInfo.mHardwareRenderer != null && mAttachInfo.mHardwareRenderer.isEnabled()) {
Romain Guyfd507262010-10-10 15:42:49 -07001503 if (!dirty.isEmpty() || mIsAnimating) {
Romain Guy101e2ae2010-10-11 12:41:21 -07001504 mIsAnimating = false;
Dianne Hackborn0f761d62010-11-30 22:06:10 -08001505 mHardwareYOffset = yoff;
1506 mResizeAlpha = resizeAlpha;
Romain Guy7d7b5492011-01-24 16:33:45 -08001507
1508 mCurrentDirty.set(dirty);
1509 mCurrentDirty.union(mPreviousDirty);
1510 mPreviousDirty.set(dirty);
1511 dirty.setEmpty();
1512
Romain Guyf90f8172011-01-25 22:53:24 -08001513 Rect currentDirty = mCurrentDirty;
1514 if (animating) {
1515 currentDirty = null;
1516 }
1517
1518 mAttachInfo.mHardwareRenderer.draw(mView, mAttachInfo, this, currentDirty);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001519 }
Romain Guy812ccbe2010-06-01 14:07:24 -07001520
Dianne Hackborn0f761d62010-11-30 22:06:10 -08001521 if (animating) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001522 mFullRedrawNeeded = true;
1523 scheduleTraversals();
1524 }
Romain Guy812ccbe2010-06-01 14:07:24 -07001525
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001526 return;
1527 }
1528
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001529 if (DEBUG_ORIENTATION || DEBUG_DRAW) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001530 Log.v(TAG, "Draw " + mView + "/"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001531 + mWindowAttributes.getTitle()
1532 + ": dirty={" + dirty.left + "," + dirty.top
1533 + "," + dirty.right + "," + dirty.bottom + "} surface="
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001534 + surface + " surface.isValid()=" + surface.isValid() + ", appScale:" +
1535 appScale + ", width=" + mWidth + ", height=" + mHeight);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001536 }
1537
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001538 if (!dirty.isEmpty() || mIsAnimating) {
1539 Canvas canvas;
1540 try {
1541 int left = dirty.left;
1542 int top = dirty.top;
1543 int right = dirty.right;
1544 int bottom = dirty.bottom;
Romain Guyfea12b82011-01-27 15:36:40 -08001545
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001546 canvas = surface.lockCanvas(dirty);
Romain Guy5bcdff42009-05-14 21:27:18 -07001547
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001548 if (left != dirty.left || top != dirty.top || right != dirty.right ||
1549 bottom != dirty.bottom) {
1550 mAttachInfo.mIgnoreDirtyState = true;
1551 }
1552
1553 // TODO: Do this in native
1554 canvas.setDensity(mDensity);
1555 } catch (Surface.OutOfResourcesException e) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001556 Log.e(TAG, "OutOfResourcesException locking surface", e);
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001557 // TODO: we should ask the window manager to do something!
1558 // for now we just do nothing
Dianne Hackborn83a6f452011-01-27 17:17:19 -08001559 mLayoutRequested = true; // ask wm for a new surface next time.
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001560 return;
1561 } catch (IllegalArgumentException e) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001562 Log.e(TAG, "IllegalArgumentException locking surface", e);
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001563 // TODO: we should ask the window manager to do something!
1564 // for now we just do nothing
Dianne Hackborn83a6f452011-01-27 17:17:19 -08001565 mLayoutRequested = true; // ask wm for a new surface next time.
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001566 return;
Romain Guy5bcdff42009-05-14 21:27:18 -07001567 }
1568
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001569 try {
1570 if (!dirty.isEmpty() || mIsAnimating) {
1571 long startTime = 0L;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001572
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001573 if (DEBUG_ORIENTATION || DEBUG_DRAW) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001574 Log.v(TAG, "Surface " + surface + " drawing to bitmap w="
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001575 + canvas.getWidth() + ", h=" + canvas.getHeight());
1576 //canvas.drawARGB(255, 255, 0, 0);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001577 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001578
Romain Guy5429e1d2010-09-07 12:38:00 -07001579 if (ViewDebug.DEBUG_PROFILE_DRAWING) {
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001580 startTime = SystemClock.elapsedRealtime();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001581 }
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001582
1583 // If this bitmap's format includes an alpha channel, we
1584 // need to clear it before drawing so that the child will
1585 // properly re-composite its drawing on a transparent
1586 // background. This automatically respects the clip/dirty region
1587 // or
1588 // If we are applying an offset, we need to clear the area
1589 // where the offset doesn't appear to avoid having garbage
1590 // left in the blank areas.
1591 if (!canvas.isOpaque() || yoff != 0) {
1592 canvas.drawColor(0, PorterDuff.Mode.CLEAR);
1593 }
1594
1595 dirty.setEmpty();
1596 mIsAnimating = false;
1597 mAttachInfo.mDrawingTime = SystemClock.uptimeMillis();
1598 mView.mPrivateFlags |= View.DRAWN;
1599
1600 if (DEBUG_DRAW) {
1601 Context cxt = mView.getContext();
1602 Log.i(TAG, "Drawing: package:" + cxt.getPackageName() +
1603 ", metrics=" + cxt.getResources().getDisplayMetrics() +
1604 ", compatibilityInfo=" + cxt.getResources().getCompatibilityInfo());
1605 }
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001606 try {
1607 canvas.translate(0, -yoff);
1608 if (mTranslator != null) {
1609 mTranslator.translateCanvas(canvas);
1610 }
1611 canvas.setScreenDensity(scalingRequired
1612 ? DisplayMetrics.DENSITY_DEVICE : 0);
1613 mView.draw(canvas);
1614 } finally {
1615 mAttachInfo.mIgnoreDirtyState = false;
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001616 }
1617
1618 if (Config.DEBUG && ViewDebug.consistencyCheckEnabled) {
1619 mView.dispatchConsistencyCheck(ViewDebug.CONSISTENCY_DRAWING);
1620 }
1621
Romain Guy5429e1d2010-09-07 12:38:00 -07001622 if (SHOW_FPS || ViewDebug.DEBUG_SHOW_FPS) {
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001623 int now = (int)SystemClock.elapsedRealtime();
1624 if (sDrawTime != 0) {
1625 nativeShowFPS(canvas, now - sDrawTime);
1626 }
1627 sDrawTime = now;
1628 }
1629
Romain Guy5429e1d2010-09-07 12:38:00 -07001630 if (ViewDebug.DEBUG_PROFILE_DRAWING) {
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001631 EventLog.writeEvent(60000, SystemClock.elapsedRealtime() - startTime);
1632 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001633 }
1634
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001635 } finally {
1636 surface.unlockCanvasAndPost(canvas);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001637 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001638 }
1639
1640 if (LOCAL_LOGV) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001641 Log.v(TAG, "Surface " + surface + " unlockCanvasAndPost");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001642 }
Romain Guy8506ab42009-06-11 17:35:47 -07001643
Dianne Hackborn0f761d62010-11-30 22:06:10 -08001644 if (animating) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001645 mFullRedrawNeeded = true;
1646 scheduleTraversals();
1647 }
1648 }
1649
1650 boolean scrollToRectOrFocus(Rect rectangle, boolean immediate) {
1651 final View.AttachInfo attachInfo = mAttachInfo;
1652 final Rect ci = attachInfo.mContentInsets;
1653 final Rect vi = attachInfo.mVisibleInsets;
1654 int scrollY = 0;
1655 boolean handled = false;
Romain Guy8506ab42009-06-11 17:35:47 -07001656
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001657 if (vi.left > ci.left || vi.top > ci.top
1658 || vi.right > ci.right || vi.bottom > ci.bottom) {
1659 // We'll assume that we aren't going to change the scroll
1660 // offset, since we want to avoid that unless it is actually
1661 // going to make the focus visible... otherwise we scroll
1662 // all over the place.
1663 scrollY = mScrollY;
1664 // We can be called for two different situations: during a draw,
1665 // to update the scroll position if the focus has changed (in which
1666 // case 'rectangle' is null), or in response to a
1667 // requestChildRectangleOnScreen() call (in which case 'rectangle'
1668 // is non-null and we just want to scroll to whatever that
1669 // rectangle is).
1670 View focus = mRealFocusedView;
Romain Guye8b16522009-07-14 13:06:42 -07001671
1672 // When in touch mode, focus points to the previously focused view,
1673 // which may have been removed from the view hierarchy. The following
Joe Onoratob71193b2009-11-24 18:34:42 -05001674 // line checks whether the view is still in our hierarchy.
1675 if (focus == null || focus.mAttachInfo != mAttachInfo) {
Romain Guye8b16522009-07-14 13:06:42 -07001676 mRealFocusedView = null;
1677 return false;
1678 }
1679
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001680 if (focus != mLastScrolledFocus) {
1681 // If the focus has changed, then ignore any requests to scroll
1682 // to a rectangle; first we want to make sure the entire focus
1683 // view is visible.
1684 rectangle = null;
1685 }
1686 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Eval scroll: focus=" + focus
1687 + " rectangle=" + rectangle + " ci=" + ci
1688 + " vi=" + vi);
1689 if (focus == mLastScrolledFocus && !mScrollMayChange
1690 && rectangle == null) {
1691 // Optimization: if the focus hasn't changed since last
1692 // time, and no layout has happened, then just leave things
1693 // as they are.
1694 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Keeping scroll y="
1695 + mScrollY + " vi=" + vi.toShortString());
1696 } else if (focus != null) {
1697 // We need to determine if the currently focused view is
1698 // within the visible part of the window and, if not, apply
1699 // a pan so it can be seen.
1700 mLastScrolledFocus = focus;
1701 mScrollMayChange = false;
1702 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Need to scroll?");
1703 // Try to find the rectangle from the focus view.
1704 if (focus.getGlobalVisibleRect(mVisRect, null)) {
1705 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Root w="
1706 + mView.getWidth() + " h=" + mView.getHeight()
1707 + " ci=" + ci.toShortString()
1708 + " vi=" + vi.toShortString());
1709 if (rectangle == null) {
1710 focus.getFocusedRect(mTempRect);
1711 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Focus " + focus
1712 + ": focusRect=" + mTempRect.toShortString());
Dianne Hackborn1c6a8942010-03-23 16:34:20 -07001713 if (mView instanceof ViewGroup) {
1714 ((ViewGroup) mView).offsetDescendantRectToMyCoords(
1715 focus, mTempRect);
1716 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001717 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1718 "Focus in window: focusRect="
1719 + mTempRect.toShortString()
1720 + " visRect=" + mVisRect.toShortString());
1721 } else {
1722 mTempRect.set(rectangle);
1723 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1724 "Request scroll to rect: "
1725 + mTempRect.toShortString()
1726 + " visRect=" + mVisRect.toShortString());
1727 }
1728 if (mTempRect.intersect(mVisRect)) {
1729 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1730 "Focus window visible rect: "
1731 + mTempRect.toShortString());
1732 if (mTempRect.height() >
1733 (mView.getHeight()-vi.top-vi.bottom)) {
1734 // If the focus simply is not going to fit, then
1735 // best is probably just to leave things as-is.
1736 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1737 "Too tall; leaving scrollY=" + scrollY);
1738 } else if ((mTempRect.top-scrollY) < vi.top) {
1739 scrollY -= vi.top - (mTempRect.top-scrollY);
1740 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1741 "Top covered; scrollY=" + scrollY);
1742 } else if ((mTempRect.bottom-scrollY)
1743 > (mView.getHeight()-vi.bottom)) {
1744 scrollY += (mTempRect.bottom-scrollY)
1745 - (mView.getHeight()-vi.bottom);
1746 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1747 "Bottom covered; scrollY=" + scrollY);
1748 }
1749 handled = true;
1750 }
1751 }
1752 }
1753 }
Romain Guy8506ab42009-06-11 17:35:47 -07001754
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001755 if (scrollY != mScrollY) {
1756 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Pan scroll changed: old="
1757 + mScrollY + " , new=" + scrollY);
Dianne Hackborn0f761d62010-11-30 22:06:10 -08001758 if (!immediate && mResizeBitmap == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001759 if (mScroller == null) {
1760 mScroller = new Scroller(mView.getContext());
1761 }
1762 mScroller.startScroll(0, mScrollY, 0, scrollY-mScrollY);
1763 } else if (mScroller != null) {
1764 mScroller.abortAnimation();
1765 }
1766 mScrollY = scrollY;
1767 }
Romain Guy8506ab42009-06-11 17:35:47 -07001768
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001769 return handled;
1770 }
Romain Guy8506ab42009-06-11 17:35:47 -07001771
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001772 public void requestChildFocus(View child, View focused) {
1773 checkThread();
1774 if (mFocusedView != focused) {
1775 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(mFocusedView, focused);
1776 scheduleTraversals();
1777 }
1778 mFocusedView = mRealFocusedView = focused;
1779 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Request child focus: focus now "
1780 + mFocusedView);
1781 }
1782
1783 public void clearChildFocus(View child) {
1784 checkThread();
1785
1786 View oldFocus = mFocusedView;
1787
1788 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Clearing child focus");
1789 mFocusedView = mRealFocusedView = null;
1790 if (mView != null && !mView.hasFocus()) {
1791 // If a view gets the focus, the listener will be invoked from requestChildFocus()
1792 if (!mView.requestFocus(View.FOCUS_FORWARD)) {
1793 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
1794 }
1795 } else if (oldFocus != null) {
1796 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
1797 }
1798 }
1799
1800
1801 public void focusableViewAvailable(View v) {
1802 checkThread();
1803
1804 if (mView != null && !mView.hasFocus()) {
1805 v.requestFocus();
1806 } else {
1807 // the one case where will transfer focus away from the current one
1808 // is if the current view is a view group that prefers to give focus
1809 // to its children first AND the view is a descendant of it.
1810 mFocusedView = mView.findFocus();
1811 boolean descendantsHaveDibsOnFocus =
1812 (mFocusedView instanceof ViewGroup) &&
1813 (((ViewGroup) mFocusedView).getDescendantFocusability() ==
1814 ViewGroup.FOCUS_AFTER_DESCENDANTS);
1815 if (descendantsHaveDibsOnFocus && isViewDescendantOf(v, mFocusedView)) {
1816 // If a view gets the focus, the listener will be invoked from requestChildFocus()
1817 v.requestFocus();
1818 }
1819 }
1820 }
1821
1822 public void recomputeViewAttributes(View child) {
1823 checkThread();
1824 if (mView == child) {
1825 mAttachInfo.mRecomputeGlobalAttributes = true;
1826 if (!mWillDrawSoon) {
1827 scheduleTraversals();
1828 }
1829 }
1830 }
1831
1832 void dispatchDetachedFromWindow() {
Romain Guy90fc03b2011-01-16 13:07:15 -08001833 if (mView != null && mView.mAttachInfo != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001834 mView.dispatchDetachedFromWindow();
1835 }
1836
1837 mView = null;
1838 mAttachInfo.mRootView = null;
Mathias Agopian5583dc62009-07-09 16:28:11 -07001839 mAttachInfo.mSurface = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001840
Romain Guy29d89972010-09-22 16:10:57 -07001841 destroyHardwareRenderer();
Romain Guy4caa4ed2010-08-25 14:46:24 -07001842
Dianne Hackborn0586a1b2009-09-06 21:08:27 -07001843 mSurface.release();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001844
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001845 if (mInputChannel != null) {
1846 if (mInputQueueCallback != null) {
1847 mInputQueueCallback.onInputQueueDestroyed(mInputQueue);
1848 mInputQueueCallback = null;
1849 } else {
1850 InputQueue.unregisterInputChannel(mInputChannel);
Jeff Brown46b9ac02010-04-22 18:58:52 -07001851 }
1852 }
1853
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001854 try {
1855 sWindowSession.remove(mWindow);
1856 } catch (RemoteException e) {
1857 }
Jeff Brown349703e2010-06-22 01:27:15 -07001858
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001859 // Dispose the input channel after removing the window so the Window Manager
1860 // doesn't interpret the input channel being closed as an abnormal termination.
1861 if (mInputChannel != null) {
1862 mInputChannel.dispose();
1863 mInputChannel = null;
Jeff Brown349703e2010-06-22 01:27:15 -07001864 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001865 }
Romain Guy8506ab42009-06-11 17:35:47 -07001866
Dianne Hackborn694f79b2010-03-17 19:44:59 -07001867 void updateConfiguration(Configuration config, boolean force) {
1868 if (DEBUG_CONFIGURATION) Log.v(TAG,
1869 "Applying new config to window "
1870 + mWindowAttributes.getTitle()
1871 + ": " + config);
1872 synchronized (sConfigCallbacks) {
1873 for (int i=sConfigCallbacks.size()-1; i>=0; i--) {
1874 sConfigCallbacks.get(i).onConfigurationChanged(config);
1875 }
1876 }
1877 if (mView != null) {
1878 // At this point the resources have been updated to
1879 // have the most recent config, whatever that is. Use
1880 // the on in them which may be newer.
1881 if (mView != null) {
1882 config = mView.getResources().getConfiguration();
1883 }
1884 if (force || mLastConfiguration.diff(config) != 0) {
1885 mLastConfiguration.setTo(config);
1886 mView.dispatchConfigurationChanged(config);
1887 }
1888 }
1889 }
1890
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001891 /**
1892 * Return true if child is an ancestor of parent, (or equal to the parent).
1893 */
1894 private static boolean isViewDescendantOf(View child, View parent) {
1895 if (child == parent) {
1896 return true;
1897 }
1898
1899 final ViewParent theParent = child.getParent();
1900 return (theParent instanceof ViewGroup) && isViewDescendantOf((View) theParent, parent);
1901 }
1902
Romain Guycdb86672010-03-18 18:54:50 -07001903 private static void forceLayout(View view) {
1904 view.forceLayout();
1905 if (view instanceof ViewGroup) {
1906 ViewGroup group = (ViewGroup) view;
1907 final int count = group.getChildCount();
1908 for (int i = 0; i < count; i++) {
1909 forceLayout(group.getChildAt(i));
1910 }
1911 }
1912 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001913
1914 public final static int DO_TRAVERSAL = 1000;
1915 public final static int DIE = 1001;
1916 public final static int RESIZED = 1002;
1917 public final static int RESIZED_REPORT = 1003;
1918 public final static int WINDOW_FOCUS_CHANGED = 1004;
1919 public final static int DISPATCH_KEY = 1005;
1920 public final static int DISPATCH_POINTER = 1006;
1921 public final static int DISPATCH_TRACKBALL = 1007;
1922 public final static int DISPATCH_APP_VISIBILITY = 1008;
1923 public final static int DISPATCH_GET_NEW_SURFACE = 1009;
1924 public final static int FINISHED_EVENT = 1010;
1925 public final static int DISPATCH_KEY_FROM_IME = 1011;
1926 public final static int FINISH_INPUT_CONNECTION = 1012;
1927 public final static int CHECK_FOCUS = 1013;
Dianne Hackbornffa42482009-09-23 22:20:11 -07001928 public final static int CLOSE_SYSTEM_DIALOGS = 1014;
Christopher Tatea53146c2010-09-07 11:57:52 -07001929 public final static int DISPATCH_DRAG_EVENT = 1015;
Chris Tate91e9bb32010-10-12 12:58:43 -07001930 public final static int DISPATCH_DRAG_LOCATION_EVENT = 1016;
Joe Onorato664644d2011-01-23 17:53:23 -08001931 public final static int DISPATCH_SYSTEM_UI_VISIBILITY = 1017;
Joe Onorato10f41262011-01-24 13:16:08 -08001932 public final static int DISPATCH_GENERIC_MOTION = 1018;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001933
1934 @Override
1935 public void handleMessage(Message msg) {
1936 switch (msg.what) {
1937 case View.AttachInfo.INVALIDATE_MSG:
1938 ((View) msg.obj).invalidate();
1939 break;
1940 case View.AttachInfo.INVALIDATE_RECT_MSG:
1941 final View.AttachInfo.InvalidateInfo info = (View.AttachInfo.InvalidateInfo) msg.obj;
1942 info.target.invalidate(info.left, info.top, info.right, info.bottom);
1943 info.release();
1944 break;
1945 case DO_TRAVERSAL:
1946 if (mProfile) {
1947 Debug.startMethodTracing("ViewRoot");
1948 }
1949
1950 performTraversals();
1951
1952 if (mProfile) {
1953 Debug.stopMethodTracing();
1954 mProfile = false;
1955 }
1956 break;
1957 case FINISHED_EVENT:
1958 handleFinishedEvent(msg.arg1, msg.arg2 != 0);
1959 break;
1960 case DISPATCH_KEY:
Jeff Brown92ff1dd2010-08-11 16:16:06 -07001961 deliverKeyEvent((KeyEvent)msg.obj, msg.arg1 != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001962 break;
Jeff Brown3915bb82010-11-05 15:02:16 -07001963 case DISPATCH_POINTER:
1964 deliverPointerEvent((MotionEvent) msg.obj, msg.arg1 != 0);
1965 break;
1966 case DISPATCH_TRACKBALL:
1967 deliverTrackballEvent((MotionEvent) msg.obj, msg.arg1 != 0);
1968 break;
Jeff Browncb1404e2011-01-15 18:14:15 -08001969 case DISPATCH_GENERIC_MOTION:
1970 deliverGenericMotionEvent((MotionEvent) msg.obj, msg.arg1 != 0);
1971 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001972 case DISPATCH_APP_VISIBILITY:
1973 handleAppVisibility(msg.arg1 != 0);
1974 break;
1975 case DISPATCH_GET_NEW_SURFACE:
1976 handleGetNewSurface();
1977 break;
1978 case RESIZED:
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001979 ResizedInfo ri = (ResizedInfo)msg.obj;
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001980
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001981 if (mWinFrame.width() == msg.arg1 && mWinFrame.height() == msg.arg2
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001982 && mPendingContentInsets.equals(ri.coveredInsets)
Dianne Hackbornd49258f2010-03-26 00:44:29 -07001983 && mPendingVisibleInsets.equals(ri.visibleInsets)
1984 && ((ResizedInfo)msg.obj).newConfig == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001985 break;
1986 }
1987 // fall through...
1988 case RESIZED_REPORT:
1989 if (mAdded) {
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001990 Configuration config = ((ResizedInfo)msg.obj).newConfig;
1991 if (config != null) {
Dianne Hackborn694f79b2010-03-17 19:44:59 -07001992 updateConfiguration(config, false);
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001993 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001994 mWinFrame.left = 0;
1995 mWinFrame.right = msg.arg1;
1996 mWinFrame.top = 0;
1997 mWinFrame.bottom = msg.arg2;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001998 mPendingContentInsets.set(((ResizedInfo)msg.obj).coveredInsets);
1999 mPendingVisibleInsets.set(((ResizedInfo)msg.obj).visibleInsets);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002000 if (msg.what == RESIZED_REPORT) {
2001 mReportNextDraw = true;
2002 }
Romain Guycdb86672010-03-18 18:54:50 -07002003
2004 if (mView != null) {
2005 forceLayout(mView);
2006 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002007 requestLayout();
2008 }
2009 break;
2010 case WINDOW_FOCUS_CHANGED: {
2011 if (mAdded) {
2012 boolean hasWindowFocus = msg.arg1 != 0;
2013 mAttachInfo.mHasWindowFocus = hasWindowFocus;
2014 if (hasWindowFocus) {
2015 boolean inTouchMode = msg.arg2 != 0;
Romain Guy2d4cff62010-04-09 15:39:00 -07002016 ensureTouchModeLocally(inTouchMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002017
Romain Guyc361da82010-10-25 15:29:10 -07002018 if (mAttachInfo.mHardwareRenderer != null &&
2019 mSurface != null && mSurface.isValid()) {
Romain Guy7d7b5492011-01-24 16:33:45 -08002020 mFullRedrawNeeded = true;
Romain Guyb051e892010-09-28 19:09:36 -07002021 mAttachInfo.mHardwareRenderer.initializeIfNeeded(mWidth, mHeight,
2022 mAttachInfo, mHolder);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002023 }
2024 }
Romain Guy8506ab42009-06-11 17:35:47 -07002025
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002026 mLastWasImTarget = WindowManager.LayoutParams
2027 .mayUseInputMethod(mWindowAttributes.flags);
Romain Guy8506ab42009-06-11 17:35:47 -07002028
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002029 InputMethodManager imm = InputMethodManager.peekInstance();
2030 if (mView != null) {
2031 if (hasWindowFocus && imm != null && mLastWasImTarget) {
2032 imm.startGettingWindowFocus(mView);
2033 }
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07002034 mAttachInfo.mKeyDispatchState.reset();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002035 mView.dispatchWindowFocusChanged(hasWindowFocus);
2036 }
svetoslavganov75986cf2009-05-14 22:28:01 -07002037
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002038 // Note: must be done after the focus change callbacks,
2039 // so all of the view state is set up correctly.
2040 if (hasWindowFocus) {
2041 if (imm != null && mLastWasImTarget) {
2042 imm.onWindowFocus(mView, mView.findFocus(),
2043 mWindowAttributes.softInputMode,
2044 !mHasHadWindowFocus, mWindowAttributes.flags);
2045 }
2046 // Clear the forward bit. We can just do this directly, since
2047 // the window manager doesn't care about it.
2048 mWindowAttributes.softInputMode &=
2049 ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
2050 ((WindowManager.LayoutParams)mView.getLayoutParams())
2051 .softInputMode &=
2052 ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
2053 mHasHadWindowFocus = true;
2054 }
svetoslavganov75986cf2009-05-14 22:28:01 -07002055
2056 if (hasWindowFocus && mView != null) {
2057 sendAccessibilityEvents();
2058 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002059 }
2060 } break;
2061 case DIE:
Dianne Hackborn94d69142009-09-28 22:14:42 -07002062 doDie();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002063 break;
The Android Open Source Project10592532009-03-18 17:39:46 -07002064 case DISPATCH_KEY_FROM_IME: {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002065 if (LOCAL_LOGV) Log.v(
Jeff Brownc5ed5912010-07-14 18:48:53 -07002066 TAG, "Dispatching key "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002067 + msg.obj + " from IME to " + mView);
The Android Open Source Project10592532009-03-18 17:39:46 -07002068 KeyEvent event = (KeyEvent)msg.obj;
2069 if ((event.getFlags()&KeyEvent.FLAG_FROM_SYSTEM) != 0) {
2070 // The IME is trying to say this event is from the
2071 // system! Bad bad bad!
Romain Guy812ccbe2010-06-01 14:07:24 -07002072 event = KeyEvent.changeFlags(event, event.getFlags() & ~KeyEvent.FLAG_FROM_SYSTEM);
The Android Open Source Project10592532009-03-18 17:39:46 -07002073 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002074 deliverKeyEventPostIme((KeyEvent)msg.obj, false);
The Android Open Source Project10592532009-03-18 17:39:46 -07002075 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002076 case FINISH_INPUT_CONNECTION: {
2077 InputMethodManager imm = InputMethodManager.peekInstance();
2078 if (imm != null) {
2079 imm.reportFinishInputConnection((InputConnection)msg.obj);
2080 }
2081 } break;
2082 case CHECK_FOCUS: {
2083 InputMethodManager imm = InputMethodManager.peekInstance();
2084 if (imm != null) {
2085 imm.checkFocus();
2086 }
2087 } break;
Dianne Hackbornffa42482009-09-23 22:20:11 -07002088 case CLOSE_SYSTEM_DIALOGS: {
2089 if (mView != null) {
2090 mView.onCloseSystemDialogs((String)msg.obj);
2091 }
2092 } break;
Chris Tate91e9bb32010-10-12 12:58:43 -07002093 case DISPATCH_DRAG_EVENT:
2094 case DISPATCH_DRAG_LOCATION_EVENT: {
Christopher Tate7fb8b562011-01-20 13:46:41 -08002095 DragEvent event = (DragEvent)msg.obj;
2096 event.mLocalState = mLocalDragState; // only present when this app called startDrag()
2097 handleDragEvent(event);
Christopher Tatea53146c2010-09-07 11:57:52 -07002098 } break;
Joe Onorato664644d2011-01-23 17:53:23 -08002099 case DISPATCH_SYSTEM_UI_VISIBILITY: {
2100 handleDispatchSystemUiVisibilityChanged(msg.arg1);
2101 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002102 }
2103 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002104
Jeff Brown3915bb82010-11-05 15:02:16 -07002105 private void startInputEvent(InputQueue.FinishedCallback finishedCallback) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07002106 if (mFinishedCallback != null) {
2107 Slog.w(TAG, "Received a new input event from the input queue but there is "
2108 + "already an unfinished input event in progress.");
2109 }
2110
2111 mFinishedCallback = finishedCallback;
2112 }
2113
Jeff Brown3915bb82010-11-05 15:02:16 -07002114 private void finishInputEvent(boolean handled) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07002115 if (LOCAL_LOGV) Log.v(TAG, "Telling window manager input event is finished");
Jeff Brown92ff1dd2010-08-11 16:16:06 -07002116
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002117 if (mFinishedCallback != null) {
Jeff Brown3915bb82010-11-05 15:02:16 -07002118 mFinishedCallback.finished(handled);
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002119 mFinishedCallback = null;
Jeff Brown92ff1dd2010-08-11 16:16:06 -07002120 } else {
Jeff Brown93ed4e32010-09-23 13:51:48 -07002121 Slog.w(TAG, "Attempted to tell the input queue that the current input event "
2122 + "is finished but there is no input event actually in progress.");
Jeff Brown46b9ac02010-04-22 18:58:52 -07002123 }
2124 }
2125
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002126 /**
2127 * Something in the current window tells us we need to change the touch mode. For
2128 * example, we are not in touch mode, and the user touches the screen.
2129 *
2130 * If the touch mode has changed, tell the window manager, and handle it locally.
2131 *
2132 * @param inTouchMode Whether we want to be in touch mode.
2133 * @return True if the touch mode changed and focus changed was changed as a result
2134 */
2135 boolean ensureTouchMode(boolean inTouchMode) {
2136 if (DBG) Log.d("touchmode", "ensureTouchMode(" + inTouchMode + "), current "
2137 + "touch mode is " + mAttachInfo.mInTouchMode);
2138 if (mAttachInfo.mInTouchMode == inTouchMode) return false;
2139
2140 // tell the window manager
2141 try {
2142 sWindowSession.setInTouchMode(inTouchMode);
2143 } catch (RemoteException e) {
2144 throw new RuntimeException(e);
2145 }
2146
2147 // handle the change
Romain Guy2d4cff62010-04-09 15:39:00 -07002148 return ensureTouchModeLocally(inTouchMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002149 }
2150
2151 /**
2152 * Ensure that the touch mode for this window is set, and if it is changing,
2153 * take the appropriate action.
2154 * @param inTouchMode Whether we want to be in touch mode.
2155 * @return True if the touch mode changed and focus changed was changed as a result
2156 */
Romain Guy2d4cff62010-04-09 15:39:00 -07002157 private boolean ensureTouchModeLocally(boolean inTouchMode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002158 if (DBG) Log.d("touchmode", "ensureTouchModeLocally(" + inTouchMode + "), current "
2159 + "touch mode is " + mAttachInfo.mInTouchMode);
2160
2161 if (mAttachInfo.mInTouchMode == inTouchMode) return false;
2162
2163 mAttachInfo.mInTouchMode = inTouchMode;
2164 mAttachInfo.mTreeObserver.dispatchOnTouchModeChanged(inTouchMode);
2165
Romain Guy2d4cff62010-04-09 15:39:00 -07002166 return (inTouchMode) ? enterTouchMode() : leaveTouchMode();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002167 }
2168
2169 private boolean enterTouchMode() {
2170 if (mView != null) {
2171 if (mView.hasFocus()) {
2172 // note: not relying on mFocusedView here because this could
2173 // be when the window is first being added, and mFocused isn't
2174 // set yet.
2175 final View focused = mView.findFocus();
2176 if (focused != null && !focused.isFocusableInTouchMode()) {
2177
2178 final ViewGroup ancestorToTakeFocus =
2179 findAncestorToTakeFocusInTouchMode(focused);
2180 if (ancestorToTakeFocus != null) {
2181 // there is an ancestor that wants focus after its descendants that
2182 // is focusable in touch mode.. give it focus
2183 return ancestorToTakeFocus.requestFocus();
2184 } else {
2185 // nothing appropriate to have focus in touch mode, clear it out
2186 mView.unFocus();
2187 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(focused, null);
2188 mFocusedView = null;
2189 return true;
2190 }
2191 }
2192 }
2193 }
2194 return false;
2195 }
2196
2197
2198 /**
2199 * Find an ancestor of focused that wants focus after its descendants and is
2200 * focusable in touch mode.
2201 * @param focused The currently focused view.
2202 * @return An appropriate view, or null if no such view exists.
2203 */
2204 private ViewGroup findAncestorToTakeFocusInTouchMode(View focused) {
2205 ViewParent parent = focused.getParent();
2206 while (parent instanceof ViewGroup) {
2207 final ViewGroup vgParent = (ViewGroup) parent;
2208 if (vgParent.getDescendantFocusability() == ViewGroup.FOCUS_AFTER_DESCENDANTS
2209 && vgParent.isFocusableInTouchMode()) {
2210 return vgParent;
2211 }
2212 if (vgParent.isRootNamespace()) {
2213 return null;
2214 } else {
2215 parent = vgParent.getParent();
2216 }
2217 }
2218 return null;
2219 }
2220
2221 private boolean leaveTouchMode() {
2222 if (mView != null) {
2223 if (mView.hasFocus()) {
2224 // i learned the hard way to not trust mFocusedView :)
2225 mFocusedView = mView.findFocus();
2226 if (!(mFocusedView instanceof ViewGroup)) {
2227 // some view has focus, let it keep it
2228 return false;
2229 } else if (((ViewGroup)mFocusedView).getDescendantFocusability() !=
2230 ViewGroup.FOCUS_AFTER_DESCENDANTS) {
2231 // some view group has focus, and doesn't prefer its children
2232 // over itself for focus, so let them keep it.
2233 return false;
2234 }
2235 }
2236
2237 // find the best view to give focus to in this brave new non-touch-mode
2238 // world
2239 final View focused = focusSearch(null, View.FOCUS_DOWN);
2240 if (focused != null) {
2241 return focused.requestFocus(View.FOCUS_DOWN);
2242 }
2243 }
2244 return false;
2245 }
2246
Jeff Brown3915bb82010-11-05 15:02:16 -07002247 private void deliverPointerEvent(MotionEvent event, boolean sendDone) {
2248 // If there is no view, then the event will not be handled.
2249 if (mView == null || !mAdded) {
2250 finishPointerEvent(event, sendDone, false);
2251 return;
2252 }
2253
2254 // Translate the pointer event for compatibility, if needed.
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002255 if (mTranslator != null) {
2256 mTranslator.translateEventInScreenToAppWindow(event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002257 }
2258
Jeff Brown3915bb82010-11-05 15:02:16 -07002259 // Enter touch mode on the down.
2260 boolean isDown = event.getAction() == MotionEvent.ACTION_DOWN;
2261 if (isDown) {
2262 ensureTouchMode(true);
2263 }
2264 if(Config.LOGV) {
2265 captureMotionLog("captureDispatchPointer", event);
2266 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002267
Jeff Brown3915bb82010-11-05 15:02:16 -07002268 // Offset the scroll position.
2269 if (mCurScrollY != 0) {
2270 event.offsetLocation(0, mCurScrollY);
2271 }
2272 if (MEASURE_LATENCY) {
2273 lt.sample("A Dispatching TouchEvents", System.nanoTime() - event.getEventTimeNano());
2274 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002275
Jeff Brown3915bb82010-11-05 15:02:16 -07002276 // Remember the touch position for possible drag-initiation.
2277 mLastTouchPoint.x = event.getRawX();
2278 mLastTouchPoint.y = event.getRawY();
2279
2280 // Dispatch touch to view hierarchy.
2281 boolean handled = mView.dispatchTouchEvent(event);
2282 if (MEASURE_LATENCY) {
2283 lt.sample("B Dispatched TouchEvents ", System.nanoTime() - event.getEventTimeNano());
2284 }
2285 if (handled) {
2286 finishPointerEvent(event, sendDone, true);
2287 return;
2288 }
2289
2290 // Apply edge slop and try again, if appropriate.
2291 final int edgeFlags = event.getEdgeFlags();
2292 if (edgeFlags != 0 && mView instanceof ViewGroup) {
2293 final int edgeSlop = mViewConfiguration.getScaledEdgeSlop();
2294 int direction = View.FOCUS_UP;
2295 int x = (int)event.getX();
2296 int y = (int)event.getY();
2297 final int[] deltas = new int[2];
2298
2299 if ((edgeFlags & MotionEvent.EDGE_TOP) != 0) {
2300 direction = View.FOCUS_DOWN;
2301 if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
2302 deltas[0] = edgeSlop;
2303 x += edgeSlop;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002304 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
Jeff Brown3915bb82010-11-05 15:02:16 -07002305 deltas[0] = -edgeSlop;
2306 x -= edgeSlop;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002307 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002308 } else if ((edgeFlags & MotionEvent.EDGE_BOTTOM) != 0) {
2309 direction = View.FOCUS_UP;
2310 if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
2311 deltas[0] = edgeSlop;
2312 x += edgeSlop;
2313 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
2314 deltas[0] = -edgeSlop;
2315 x -= edgeSlop;
2316 }
2317 } else if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
2318 direction = View.FOCUS_RIGHT;
2319 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
2320 direction = View.FOCUS_LEFT;
2321 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002322
Jeff Brown3915bb82010-11-05 15:02:16 -07002323 View nearest = FocusFinder.getInstance().findNearestTouchable(
2324 ((ViewGroup) mView), x, y, direction, deltas);
2325 if (nearest != null) {
2326 event.offsetLocation(deltas[0], deltas[1]);
2327 event.setEdgeFlags(0);
2328 if (mView.dispatchTouchEvent(event)) {
2329 finishPointerEvent(event, sendDone, true);
2330 return;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002331 }
2332 }
2333 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002334
2335 // Pointer event was unhandled.
2336 finishPointerEvent(event, sendDone, false);
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002337 }
2338
Jeff Brown3915bb82010-11-05 15:02:16 -07002339 private void finishPointerEvent(MotionEvent event, boolean sendDone, boolean handled) {
2340 event.recycle();
2341 if (sendDone) {
2342 finishInputEvent(handled);
2343 }
2344 if (LOCAL_LOGV || WATCH_POINTER) Log.i(TAG, "Done dispatching!");
2345 }
2346
2347 private void deliverTrackballEvent(MotionEvent event, boolean sendDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002348 if (DEBUG_TRACKBALL) Log.v(TAG, "Motion event:" + event);
2349
Jeff Brown3915bb82010-11-05 15:02:16 -07002350 // If there is no view, then the event will not be handled.
2351 if (mView == null || !mAdded) {
2352 finishTrackballEvent(event, sendDone, false);
2353 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002354 }
2355
Jeff Brown3915bb82010-11-05 15:02:16 -07002356 // Deliver the trackball event to the view.
2357 if (mView.dispatchTrackballEvent(event)) {
2358 // If we reach this, we delivered a trackball event to mView and
2359 // mView consumed it. Because we will not translate the trackball
2360 // event into a key event, touch mode will not exit, so we exit
2361 // touch mode here.
2362 ensureTouchMode(false);
2363
2364 finishTrackballEvent(event, sendDone, true);
2365 mLastTrackballTime = Integer.MIN_VALUE;
2366 return;
2367 }
2368
2369 // Translate the trackball event into DPAD keys and try to deliver those.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002370 final TrackballAxis x = mTrackballAxisX;
2371 final TrackballAxis y = mTrackballAxisY;
2372
2373 long curTime = SystemClock.uptimeMillis();
Jeff Brown3915bb82010-11-05 15:02:16 -07002374 if ((mLastTrackballTime + MAX_TRACKBALL_DELAY) < curTime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002375 // It has been too long since the last movement,
2376 // so restart at the beginning.
2377 x.reset(0);
2378 y.reset(0);
2379 mLastTrackballTime = curTime;
2380 }
2381
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002382 final int action = event.getAction();
Jeff Brown49ed71d2010-12-06 17:13:33 -08002383 final int metaState = event.getMetaState();
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002384 switch (action) {
2385 case MotionEvent.ACTION_DOWN:
2386 x.reset(2);
2387 y.reset(2);
2388 deliverKeyEvent(new KeyEvent(curTime, curTime,
Jeff Brown49ed71d2010-12-06 17:13:33 -08002389 KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_CENTER, 0, metaState,
2390 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
2391 InputDevice.SOURCE_KEYBOARD), false);
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002392 break;
2393 case MotionEvent.ACTION_UP:
2394 x.reset(2);
2395 y.reset(2);
2396 deliverKeyEvent(new KeyEvent(curTime, curTime,
Jeff Brown49ed71d2010-12-06 17:13:33 -08002397 KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_CENTER, 0, metaState,
2398 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
2399 InputDevice.SOURCE_KEYBOARD), false);
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002400 break;
2401 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002402
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002403 if (DEBUG_TRACKBALL) Log.v(TAG, "TB X=" + x.position + " step="
2404 + x.step + " dir=" + x.dir + " acc=" + x.acceleration
2405 + " move=" + event.getX()
2406 + " / Y=" + y.position + " step="
2407 + y.step + " dir=" + y.dir + " acc=" + y.acceleration
2408 + " move=" + event.getY());
2409 final float xOff = x.collect(event.getX(), event.getEventTime(), "X");
2410 final float yOff = y.collect(event.getY(), event.getEventTime(), "Y");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002411
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002412 // Generate DPAD events based on the trackball movement.
2413 // We pick the axis that has moved the most as the direction of
2414 // the DPAD. When we generate DPAD events for one axis, then the
2415 // other axis is reset -- we don't want to perform DPAD jumps due
2416 // to slight movements in the trackball when making major movements
2417 // along the other axis.
2418 int keycode = 0;
2419 int movement = 0;
2420 float accel = 1;
2421 if (xOff > yOff) {
2422 movement = x.generate((2/event.getXPrecision()));
2423 if (movement != 0) {
2424 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_RIGHT
2425 : KeyEvent.KEYCODE_DPAD_LEFT;
2426 accel = x.acceleration;
2427 y.reset(2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002428 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002429 } else if (yOff > 0) {
2430 movement = y.generate((2/event.getYPrecision()));
2431 if (movement != 0) {
2432 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_DOWN
2433 : KeyEvent.KEYCODE_DPAD_UP;
2434 accel = y.acceleration;
2435 x.reset(2);
2436 }
2437 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002438
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002439 if (keycode != 0) {
2440 if (movement < 0) movement = -movement;
2441 int accelMovement = (int)(movement * accel);
2442 if (DEBUG_TRACKBALL) Log.v(TAG, "Move: movement=" + movement
2443 + " accelMovement=" + accelMovement
2444 + " accel=" + accel);
2445 if (accelMovement > movement) {
2446 if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: "
2447 + keycode);
2448 movement--;
Jeff Brown49ed71d2010-12-06 17:13:33 -08002449 int repeatCount = accelMovement - movement;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002450 deliverKeyEvent(new KeyEvent(curTime, curTime,
Jeff Brown49ed71d2010-12-06 17:13:33 -08002451 KeyEvent.ACTION_MULTIPLE, keycode, repeatCount, metaState,
2452 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
2453 InputDevice.SOURCE_KEYBOARD), false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002454 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002455 while (movement > 0) {
2456 if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: "
2457 + keycode);
2458 movement--;
2459 curTime = SystemClock.uptimeMillis();
2460 deliverKeyEvent(new KeyEvent(curTime, curTime,
Jeff Brown49ed71d2010-12-06 17:13:33 -08002461 KeyEvent.ACTION_DOWN, keycode, 0, metaState,
2462 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
2463 InputDevice.SOURCE_KEYBOARD), false);
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002464 deliverKeyEvent(new KeyEvent(curTime, curTime,
Jeff Brown49ed71d2010-12-06 17:13:33 -08002465 KeyEvent.ACTION_UP, keycode, 0, metaState,
2466 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
2467 InputDevice.SOURCE_KEYBOARD), false);
2468 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002469 mLastTrackballTime = curTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002470 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002471
2472 // Unfortunately we can't tell whether the application consumed the keys, so
2473 // we always consider the trackball event handled.
2474 finishTrackballEvent(event, sendDone, true);
2475 }
2476
2477 private void finishTrackballEvent(MotionEvent event, boolean sendDone, boolean handled) {
2478 event.recycle();
2479 if (sendDone) {
2480 finishInputEvent(handled);
2481 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002482 }
2483
Jeff Browncb1404e2011-01-15 18:14:15 -08002484 private void deliverGenericMotionEvent(MotionEvent event, boolean sendDone) {
2485 final int source = event.getSource();
2486 final boolean isJoystick = (source & InputDevice.SOURCE_CLASS_JOYSTICK) != 0;
2487
2488 // If there is no view, then the event will not be handled.
2489 if (mView == null || !mAdded) {
2490 if (isJoystick) {
2491 updateJoystickDirection(event, false);
2492 }
2493 finishGenericMotionEvent(event, sendDone, false);
2494 return;
2495 }
2496
2497 // Deliver the event to the view.
2498 if (mView.dispatchGenericMotionEvent(event)) {
Jeff Browncb1404e2011-01-15 18:14:15 -08002499 if (isJoystick) {
2500 updateJoystickDirection(event, false);
2501 }
2502 finishGenericMotionEvent(event, sendDone, true);
2503 return;
2504 }
2505
2506 if (isJoystick) {
2507 // Translate the joystick event into DPAD keys and try to deliver those.
2508 updateJoystickDirection(event, true);
2509 finishGenericMotionEvent(event, sendDone, true);
2510 } else {
2511 finishGenericMotionEvent(event, sendDone, false);
2512 }
2513 }
2514
2515 private void finishGenericMotionEvent(MotionEvent event, boolean sendDone, boolean handled) {
2516 event.recycle();
2517 if (sendDone) {
2518 finishInputEvent(handled);
2519 }
2520 }
2521
2522 private void updateJoystickDirection(MotionEvent event, boolean synthesizeNewKeys) {
2523 final long time = event.getEventTime();
2524 final int metaState = event.getMetaState();
2525 final int deviceId = event.getDeviceId();
2526 final int source = event.getSource();
Jeff Brown6f2fba42011-02-19 01:08:02 -08002527
2528 int xDirection = joystickAxisValueToDirection(event.getAxisValue(MotionEvent.AXIS_HAT_X));
2529 if (xDirection == 0) {
2530 xDirection = joystickAxisValueToDirection(event.getX());
2531 }
2532
2533 int yDirection = joystickAxisValueToDirection(event.getAxisValue(MotionEvent.AXIS_HAT_Y));
2534 if (yDirection == 0) {
2535 yDirection = joystickAxisValueToDirection(event.getY());
2536 }
Jeff Browncb1404e2011-01-15 18:14:15 -08002537
2538 if (xDirection != mLastJoystickXDirection) {
2539 if (mLastJoystickXKeyCode != 0) {
2540 deliverKeyEvent(new KeyEvent(time, time,
2541 KeyEvent.ACTION_UP, mLastJoystickXKeyCode, 0, metaState,
2542 deviceId, 0, KeyEvent.FLAG_FALLBACK, source), false);
2543 mLastJoystickXKeyCode = 0;
2544 }
2545
2546 mLastJoystickXDirection = xDirection;
2547
2548 if (xDirection != 0 && synthesizeNewKeys) {
2549 mLastJoystickXKeyCode = xDirection > 0
2550 ? KeyEvent.KEYCODE_DPAD_RIGHT : KeyEvent.KEYCODE_DPAD_LEFT;
2551 deliverKeyEvent(new KeyEvent(time, time,
2552 KeyEvent.ACTION_DOWN, mLastJoystickXKeyCode, 0, metaState,
2553 deviceId, 0, KeyEvent.FLAG_FALLBACK, source), false);
2554 }
2555 }
2556
2557 if (yDirection != mLastJoystickYDirection) {
2558 if (mLastJoystickYKeyCode != 0) {
2559 deliverKeyEvent(new KeyEvent(time, time,
2560 KeyEvent.ACTION_UP, mLastJoystickYKeyCode, 0, metaState,
2561 deviceId, 0, KeyEvent.FLAG_FALLBACK, source), false);
2562 mLastJoystickYKeyCode = 0;
2563 }
2564
2565 mLastJoystickYDirection = yDirection;
2566
2567 if (yDirection != 0 && synthesizeNewKeys) {
2568 mLastJoystickYKeyCode = yDirection > 0
2569 ? KeyEvent.KEYCODE_DPAD_DOWN : KeyEvent.KEYCODE_DPAD_UP;
2570 deliverKeyEvent(new KeyEvent(time, time,
2571 KeyEvent.ACTION_DOWN, mLastJoystickYKeyCode, 0, metaState,
2572 deviceId, 0, KeyEvent.FLAG_FALLBACK, source), false);
2573 }
2574 }
2575 }
2576
2577 private static int joystickAxisValueToDirection(float value) {
2578 if (value >= 0.5f) {
2579 return 1;
2580 } else if (value <= -0.5f) {
2581 return -1;
2582 } else {
2583 return 0;
2584 }
2585 }
2586
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002587 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08002588 * Returns true if the key is used for keyboard navigation.
2589 * @param keyEvent The key event.
2590 * @return True if the key is used for keyboard navigation.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002591 */
Jeff Brown4e6319b2010-12-13 10:36:51 -08002592 private static boolean isNavigationKey(KeyEvent keyEvent) {
2593 switch (keyEvent.getKeyCode()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002594 case KeyEvent.KEYCODE_DPAD_LEFT:
2595 case KeyEvent.KEYCODE_DPAD_RIGHT:
2596 case KeyEvent.KEYCODE_DPAD_UP:
2597 case KeyEvent.KEYCODE_DPAD_DOWN:
Jeff Brown4e6319b2010-12-13 10:36:51 -08002598 case KeyEvent.KEYCODE_DPAD_CENTER:
2599 case KeyEvent.KEYCODE_PAGE_UP:
2600 case KeyEvent.KEYCODE_PAGE_DOWN:
2601 case KeyEvent.KEYCODE_MOVE_HOME:
2602 case KeyEvent.KEYCODE_MOVE_END:
2603 case KeyEvent.KEYCODE_TAB:
2604 case KeyEvent.KEYCODE_SPACE:
2605 case KeyEvent.KEYCODE_ENTER:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002606 return true;
2607 }
2608 return false;
2609 }
2610
2611 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08002612 * Returns true if the key is used for typing.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002613 * @param keyEvent The key event.
Jeff Brown4e6319b2010-12-13 10:36:51 -08002614 * @return True if the key is used for typing.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002615 */
Jeff Brown4e6319b2010-12-13 10:36:51 -08002616 private static boolean isTypingKey(KeyEvent keyEvent) {
2617 return keyEvent.getUnicodeChar() > 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002618 }
2619
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002620 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08002621 * See if the key event means we should leave touch mode (and leave touch mode if so).
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002622 * @param event The key event.
2623 * @return Whether this key event should be consumed (meaning the act of
2624 * leaving touch mode alone is considered the event).
2625 */
2626 private boolean checkForLeavingTouchModeAndConsume(KeyEvent event) {
Jeff Brown4e6319b2010-12-13 10:36:51 -08002627 // Only relevant in touch mode.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002628 if (!mAttachInfo.mInTouchMode) {
2629 return false;
2630 }
2631
Jeff Brown4e6319b2010-12-13 10:36:51 -08002632 // Only consider leaving touch mode on DOWN or MULTIPLE actions, never on UP.
2633 final int action = event.getAction();
2634 if (action != KeyEvent.ACTION_DOWN && action != KeyEvent.ACTION_MULTIPLE) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002635 return false;
2636 }
2637
Jeff Brown4e6319b2010-12-13 10:36:51 -08002638 // Don't leave touch mode if the IME told us not to.
2639 if ((event.getFlags() & KeyEvent.FLAG_KEEP_TOUCH_MODE) != 0) {
2640 return false;
2641 }
2642
2643 // If the key can be used for keyboard navigation then leave touch mode
2644 // and select a focused view if needed (in ensureTouchMode).
2645 // When a new focused view is selected, we consume the navigation key because
2646 // navigation doesn't make much sense unless a view already has focus so
2647 // the key's purpose is to set focus.
2648 if (isNavigationKey(event)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002649 return ensureTouchMode(false);
2650 }
Jeff Brown4e6319b2010-12-13 10:36:51 -08002651
2652 // If the key can be used for typing then leave touch mode
2653 // and select a focused view if needed (in ensureTouchMode).
2654 // Always allow the view to process the typing key.
2655 if (isTypingKey(event)) {
2656 ensureTouchMode(false);
2657 return false;
2658 }
2659
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002660 return false;
2661 }
2662
2663 /**
Romain Guy8506ab42009-06-11 17:35:47 -07002664 * log motion events
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002665 */
2666 private static void captureMotionLog(String subTag, MotionEvent ev) {
Romain Guy8506ab42009-06-11 17:35:47 -07002667 //check dynamic switch
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002668 if (ev == null ||
2669 SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_EVENT, 0) == 0) {
2670 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002671 }
Romain Guy8506ab42009-06-11 17:35:47 -07002672
2673 StringBuilder sb = new StringBuilder(subTag + ": ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002674 sb.append(ev.getDownTime()).append(',');
2675 sb.append(ev.getEventTime()).append(',');
2676 sb.append(ev.getAction()).append(',');
Romain Guy8506ab42009-06-11 17:35:47 -07002677 sb.append(ev.getX()).append(',');
2678 sb.append(ev.getY()).append(',');
2679 sb.append(ev.getPressure()).append(',');
2680 sb.append(ev.getSize()).append(',');
2681 sb.append(ev.getMetaState()).append(',');
2682 sb.append(ev.getXPrecision()).append(',');
2683 sb.append(ev.getYPrecision()).append(',');
2684 sb.append(ev.getDeviceId()).append(',');
2685 sb.append(ev.getEdgeFlags());
2686 Log.d(TAG, sb.toString());
2687 }
2688 /**
2689 * log motion events
2690 */
2691 private static void captureKeyLog(String subTag, KeyEvent ev) {
2692 //check dynamic switch
2693 if (ev == null ||
2694 SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_EVENT, 0) == 0) {
2695 return;
2696 }
2697 StringBuilder sb = new StringBuilder(subTag + ": ");
2698 sb.append(ev.getDownTime()).append(',');
2699 sb.append(ev.getEventTime()).append(',');
2700 sb.append(ev.getAction()).append(',');
2701 sb.append(ev.getKeyCode()).append(',');
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002702 sb.append(ev.getRepeatCount()).append(',');
2703 sb.append(ev.getMetaState()).append(',');
2704 sb.append(ev.getDeviceId()).append(',');
2705 sb.append(ev.getScanCode());
Romain Guy8506ab42009-06-11 17:35:47 -07002706 Log.d(TAG, sb.toString());
2707 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002708
2709 int enqueuePendingEvent(Object event, boolean sendDone) {
2710 int seq = mPendingEventSeq+1;
2711 if (seq < 0) seq = 0;
2712 mPendingEventSeq = seq;
2713 mPendingEvents.put(seq, event);
2714 return sendDone ? seq : -seq;
2715 }
2716
2717 Object retrievePendingEvent(int seq) {
2718 if (seq < 0) seq = -seq;
2719 Object event = mPendingEvents.get(seq);
2720 if (event != null) {
2721 mPendingEvents.remove(seq);
2722 }
2723 return event;
2724 }
Romain Guy8506ab42009-06-11 17:35:47 -07002725
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002726 private void deliverKeyEvent(KeyEvent event, boolean sendDone) {
Jeff Brown3915bb82010-11-05 15:02:16 -07002727 // If there is no view, then the event will not be handled.
2728 if (mView == null || !mAdded) {
2729 finishKeyEvent(event, sendDone, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002730 return;
2731 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002732
2733 if (LOCAL_LOGV) Log.v(TAG, "Dispatching key " + event + " to " + mView);
2734
2735 // Perform predispatching before the IME.
2736 if (mView.dispatchKeyEventPreIme(event)) {
2737 finishKeyEvent(event, sendDone, true);
2738 return;
2739 }
2740
2741 // Dispatch to the IME before propagating down the view hierarchy.
2742 // The IME will eventually call back into handleFinishedEvent.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002743 if (mLastWasImTarget) {
2744 InputMethodManager imm = InputMethodManager.peekInstance();
Jeff Brown3915bb82010-11-05 15:02:16 -07002745 if (imm != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002746 int seq = enqueuePendingEvent(event, sendDone);
2747 if (DEBUG_IMF) Log.v(TAG, "Sending key event to IME: seq="
2748 + seq + " event=" + event);
Jeff Brown3915bb82010-11-05 15:02:16 -07002749 imm.dispatchKeyEvent(mView.getContext(), seq, event, mInputMethodCallback);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002750 return;
2751 }
2752 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002753
2754 // Not dispatching to IME, continue with post IME actions.
2755 deliverKeyEventPostIme(event, sendDone);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002756 }
2757
Jeff Brown3915bb82010-11-05 15:02:16 -07002758 private void handleFinishedEvent(int seq, boolean handled) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002759 final KeyEvent event = (KeyEvent)retrievePendingEvent(seq);
2760 if (DEBUG_IMF) Log.v(TAG, "IME finished event: seq=" + seq
2761 + " handled=" + handled + " event=" + event);
2762 if (event != null) {
2763 final boolean sendDone = seq >= 0;
Jeff Brown3915bb82010-11-05 15:02:16 -07002764 if (handled) {
2765 finishKeyEvent(event, sendDone, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002766 } else {
Jeff Brown3915bb82010-11-05 15:02:16 -07002767 deliverKeyEventPostIme(event, sendDone);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002768 }
2769 }
2770 }
Romain Guy8506ab42009-06-11 17:35:47 -07002771
Jeff Brown3915bb82010-11-05 15:02:16 -07002772 private void deliverKeyEventPostIme(KeyEvent event, boolean sendDone) {
2773 // If the view went away, then the event will not be handled.
2774 if (mView == null || !mAdded) {
2775 finishKeyEvent(event, sendDone, false);
2776 return;
2777 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002778
Jeff Brown3915bb82010-11-05 15:02:16 -07002779 // If the key's purpose is to exit touch mode then we consume it and consider it handled.
2780 if (checkForLeavingTouchModeAndConsume(event)) {
2781 finishKeyEvent(event, sendDone, true);
2782 return;
2783 }
Romain Guy8506ab42009-06-11 17:35:47 -07002784
Jeff Brown3915bb82010-11-05 15:02:16 -07002785 if (Config.LOGV) {
2786 captureKeyLog("captureDispatchKeyEvent", event);
2787 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002788
Jeff Brown90655042010-12-02 13:50:46 -08002789 // Make sure the fallback event policy sees all keys that will be delivered to the
2790 // view hierarchy.
2791 mFallbackEventHandler.preDispatchKeyEvent(event);
2792
Jeff Brown3915bb82010-11-05 15:02:16 -07002793 // Deliver the key to the view hierarchy.
2794 if (mView.dispatchKeyEvent(event)) {
2795 finishKeyEvent(event, sendDone, true);
2796 return;
2797 }
Joe Onorato86f67862010-11-05 18:57:34 -07002798
Jeff Brownc1df9072010-12-21 16:38:50 -08002799 // If the Control modifier is held, try to interpret the key as a shortcut.
2800 if (event.getAction() == KeyEvent.ACTION_UP
2801 && event.isCtrlPressed()
2802 && !KeyEvent.isModifierKey(event.getKeyCode())) {
2803 if (mView.dispatchKeyShortcutEvent(event)) {
2804 finishKeyEvent(event, sendDone, true);
2805 return;
2806 }
2807 }
2808
Jeff Brown3915bb82010-11-05 15:02:16 -07002809 // Apply the fallback event policy.
2810 if (mFallbackEventHandler.dispatchKeyEvent(event)) {
2811 finishKeyEvent(event, sendDone, true);
2812 return;
2813 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002814
Jeff Brown3915bb82010-11-05 15:02:16 -07002815 // Handle automatic focus changes.
2816 if (event.getAction() == KeyEvent.ACTION_DOWN) {
2817 int direction = 0;
2818 switch (event.getKeyCode()) {
2819 case KeyEvent.KEYCODE_DPAD_LEFT:
Jeff Brown4e6319b2010-12-13 10:36:51 -08002820 if (event.hasNoModifiers()) {
2821 direction = View.FOCUS_LEFT;
2822 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002823 break;
2824 case KeyEvent.KEYCODE_DPAD_RIGHT:
Jeff Brown4e6319b2010-12-13 10:36:51 -08002825 if (event.hasNoModifiers()) {
2826 direction = View.FOCUS_RIGHT;
2827 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002828 break;
2829 case KeyEvent.KEYCODE_DPAD_UP:
Jeff Brown4e6319b2010-12-13 10:36:51 -08002830 if (event.hasNoModifiers()) {
2831 direction = View.FOCUS_UP;
2832 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002833 break;
2834 case KeyEvent.KEYCODE_DPAD_DOWN:
Jeff Brown4e6319b2010-12-13 10:36:51 -08002835 if (event.hasNoModifiers()) {
2836 direction = View.FOCUS_DOWN;
2837 }
2838 break;
2839 case KeyEvent.KEYCODE_TAB:
2840 if (event.hasNoModifiers()) {
2841 direction = View.FOCUS_FORWARD;
2842 } else if (event.hasModifiers(KeyEvent.META_SHIFT_ON)) {
2843 direction = View.FOCUS_BACKWARD;
2844 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002845 break;
2846 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002847
Jeff Brown3915bb82010-11-05 15:02:16 -07002848 if (direction != 0) {
2849 View focused = mView != null ? mView.findFocus() : null;
2850 if (focused != null) {
2851 View v = focused.focusSearch(direction);
2852 if (v != null && v != focused) {
2853 // do the math the get the interesting rect
2854 // of previous focused into the coord system of
2855 // newly focused view
2856 focused.getFocusedRect(mTempRect);
2857 if (mView instanceof ViewGroup) {
2858 ((ViewGroup) mView).offsetDescendantRectToMyCoords(
2859 focused, mTempRect);
2860 ((ViewGroup) mView).offsetRectIntoDescendantCoords(
2861 v, mTempRect);
2862 }
2863 if (v.requestFocus(direction, mTempRect)) {
2864 playSoundEffect(
2865 SoundEffectConstants.getContantForFocusDirection(direction));
2866 finishKeyEvent(event, sendDone, true);
2867 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002868 }
2869 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002870
2871 // Give the focused view a last chance to handle the dpad key.
2872 if (mView.dispatchUnhandledMove(focused, direction)) {
2873 finishKeyEvent(event, sendDone, true);
2874 return;
2875 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002876 }
2877 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002878 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002879
Jeff Brown3915bb82010-11-05 15:02:16 -07002880 // Key was unhandled.
2881 finishKeyEvent(event, sendDone, false);
2882 }
2883
2884 private void finishKeyEvent(KeyEvent event, boolean sendDone, boolean handled) {
2885 if (sendDone) {
2886 finishInputEvent(handled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002887 }
2888 }
2889
Christopher Tatea53146c2010-09-07 11:57:52 -07002890 /* drag/drop */
Christopher Tate407b4e92010-11-30 17:14:08 -08002891 void setLocalDragState(Object obj) {
2892 mLocalDragState = obj;
2893 }
2894
Christopher Tatea53146c2010-09-07 11:57:52 -07002895 private void handleDragEvent(DragEvent event) {
2896 // From the root, only drag start/end/location are dispatched. entered/exited
2897 // are determined and dispatched by the viewgroup hierarchy, who then report
2898 // that back here for ultimate reporting back to the framework.
2899 if (mView != null && mAdded) {
2900 final int what = event.mAction;
2901
2902 if (what == DragEvent.ACTION_DRAG_EXITED) {
2903 // A direct EXITED event means that the window manager knows we've just crossed
2904 // a window boundary, so the current drag target within this one must have
2905 // just been exited. Send it the usual notifications and then we're done
2906 // for now.
Chris Tate9d1ab882010-11-02 15:55:39 -07002907 mView.dispatchDragEvent(event);
Christopher Tatea53146c2010-09-07 11:57:52 -07002908 } else {
2909 // Cache the drag description when the operation starts, then fill it in
2910 // on subsequent calls as a convenience
2911 if (what == DragEvent.ACTION_DRAG_STARTED) {
Chris Tate9d1ab882010-11-02 15:55:39 -07002912 mCurrentDragView = null; // Start the current-recipient tracking
Christopher Tatea53146c2010-09-07 11:57:52 -07002913 mDragDescription = event.mClipDescription;
2914 } else {
2915 event.mClipDescription = mDragDescription;
2916 }
2917
2918 // For events with a [screen] location, translate into window coordinates
2919 if ((what == DragEvent.ACTION_DRAG_LOCATION) || (what == DragEvent.ACTION_DROP)) {
2920 mDragPoint.set(event.mX, event.mY);
2921 if (mTranslator != null) {
2922 mTranslator.translatePointInScreenToAppWindow(mDragPoint);
2923 }
2924
2925 if (mCurScrollY != 0) {
2926 mDragPoint.offset(0, mCurScrollY);
2927 }
2928
2929 event.mX = mDragPoint.x;
2930 event.mY = mDragPoint.y;
2931 }
2932
2933 // Remember who the current drag target is pre-dispatch
2934 final View prevDragView = mCurrentDragView;
2935
2936 // Now dispatch the drag/drop event
Chris Tated4533f12010-10-19 15:15:08 -07002937 boolean result = mView.dispatchDragEvent(event);
Christopher Tatea53146c2010-09-07 11:57:52 -07002938
2939 // If we changed apparent drag target, tell the OS about it
2940 if (prevDragView != mCurrentDragView) {
2941 try {
2942 if (prevDragView != null) {
2943 sWindowSession.dragRecipientExited(mWindow);
2944 }
2945 if (mCurrentDragView != null) {
2946 sWindowSession.dragRecipientEntered(mWindow);
2947 }
2948 } catch (RemoteException e) {
2949 Slog.e(TAG, "Unable to note drag target change");
2950 }
Christopher Tatea53146c2010-09-07 11:57:52 -07002951 }
Chris Tated4533f12010-10-19 15:15:08 -07002952
Christopher Tate407b4e92010-11-30 17:14:08 -08002953 // Report the drop result when we're done
Chris Tated4533f12010-10-19 15:15:08 -07002954 if (what == DragEvent.ACTION_DROP) {
Christopher Tate1fc014f2011-01-19 12:56:26 -08002955 mDragDescription = null;
Chris Tated4533f12010-10-19 15:15:08 -07002956 try {
2957 Log.i(TAG, "Reporting drop result: " + result);
2958 sWindowSession.reportDropResult(mWindow, result);
2959 } catch (RemoteException e) {
2960 Log.e(TAG, "Unable to report drop result");
2961 }
2962 }
Christopher Tate407b4e92010-11-30 17:14:08 -08002963
2964 // When the drag operation ends, release any local state object
2965 // that may have been in use
2966 if (what == DragEvent.ACTION_DRAG_ENDED) {
2967 setLocalDragState(null);
2968 }
Christopher Tatea53146c2010-09-07 11:57:52 -07002969 }
2970 }
2971 event.recycle();
2972 }
2973
Joe Onorato664644d2011-01-23 17:53:23 -08002974 public void handleDispatchSystemUiVisibilityChanged(int visibility) {
2975 if (mView == null) return;
Joe Onorato14782f72011-01-25 19:53:17 -08002976 if (mAttachInfo != null) {
2977 mAttachInfo.mSystemUiVisibility = visibility;
2978 }
Joe Onorato664644d2011-01-23 17:53:23 -08002979 mView.dispatchSystemUiVisibilityChanged(visibility);
2980 }
2981
Christopher Tate2c095f32010-10-04 14:13:40 -07002982 public void getLastTouchPoint(Point outLocation) {
2983 outLocation.x = (int) mLastTouchPoint.x;
2984 outLocation.y = (int) mLastTouchPoint.y;
2985 }
2986
Chris Tate9d1ab882010-11-02 15:55:39 -07002987 public void setDragFocus(View newDragTarget) {
Christopher Tatea53146c2010-09-07 11:57:52 -07002988 if (mCurrentDragView != newDragTarget) {
Chris Tate048691c2010-10-12 17:39:18 -07002989 mCurrentDragView = newDragTarget;
Christopher Tatea53146c2010-09-07 11:57:52 -07002990 }
Christopher Tatea53146c2010-09-07 11:57:52 -07002991 }
2992
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002993 private AudioManager getAudioManager() {
2994 if (mView == null) {
2995 throw new IllegalStateException("getAudioManager called when there is no mView");
2996 }
2997 if (mAudioManager == null) {
2998 mAudioManager = (AudioManager) mView.getContext().getSystemService(Context.AUDIO_SERVICE);
2999 }
3000 return mAudioManager;
3001 }
3002
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07003003 private int relayoutWindow(WindowManager.LayoutParams params, int viewVisibility,
3004 boolean insetsPending) throws RemoteException {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07003005
3006 float appScale = mAttachInfo.mApplicationScale;
Mitsuru Oshima3d914922009-05-13 22:29:15 -07003007 boolean restore = false;
Mitsuru Oshima64f59342009-06-21 00:03:11 -07003008 if (params != null && mTranslator != null) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07003009 restore = true;
3010 params.backup();
Mitsuru Oshima64f59342009-06-21 00:03:11 -07003011 mTranslator.translateWindowLayout(params);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07003012 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07003013 if (params != null) {
3014 if (DBG) Log.d(TAG, "WindowLayout in layoutWindow:" + params);
Mitsuru Oshima3d914922009-05-13 22:29:15 -07003015 }
Dianne Hackborn694f79b2010-03-17 19:44:59 -07003016 mPendingConfiguration.seq = 0;
Dianne Hackbornf123e492010-09-24 11:16:23 -07003017 //Log.d(TAG, ">>>>>> CALLING relayout");
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07003018 int relayoutResult = sWindowSession.relayout(
3019 mWindow, params,
Dianne Hackborn189ee182010-12-02 21:48:53 -08003020 (int) (mView.getMeasuredWidth() * appScale + 0.5f),
3021 (int) (mView.getMeasuredHeight() * appScale + 0.5f),
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07003022 viewVisibility, insetsPending, mWinFrame,
Dianne Hackborn694f79b2010-03-17 19:44:59 -07003023 mPendingContentInsets, mPendingVisibleInsets,
3024 mPendingConfiguration, mSurface);
Dianne Hackbornf123e492010-09-24 11:16:23 -07003025 //Log.d(TAG, "<<<<<< BACK FROM relayout");
Mitsuru Oshima3d914922009-05-13 22:29:15 -07003026 if (restore) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07003027 params.restore();
Mitsuru Oshima3d914922009-05-13 22:29:15 -07003028 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07003029
3030 if (mTranslator != null) {
3031 mTranslator.translateRectInScreenToAppWinFrame(mWinFrame);
3032 mTranslator.translateRectInScreenToAppWindow(mPendingContentInsets);
3033 mTranslator.translateRectInScreenToAppWindow(mPendingVisibleInsets);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07003034 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07003035 return relayoutResult;
3036 }
Romain Guy8506ab42009-06-11 17:35:47 -07003037
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07003038 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003039 * {@inheritDoc}
3040 */
3041 public void playSoundEffect(int effectId) {
3042 checkThread();
3043
Jean-Michel Trivi13b18fd2010-05-05 09:18:15 -07003044 try {
3045 final AudioManager audioManager = getAudioManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003046
Jean-Michel Trivi13b18fd2010-05-05 09:18:15 -07003047 switch (effectId) {
3048 case SoundEffectConstants.CLICK:
3049 audioManager.playSoundEffect(AudioManager.FX_KEY_CLICK);
3050 return;
3051 case SoundEffectConstants.NAVIGATION_DOWN:
3052 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_DOWN);
3053 return;
3054 case SoundEffectConstants.NAVIGATION_LEFT:
3055 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_LEFT);
3056 return;
3057 case SoundEffectConstants.NAVIGATION_RIGHT:
3058 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_RIGHT);
3059 return;
3060 case SoundEffectConstants.NAVIGATION_UP:
3061 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_UP);
3062 return;
3063 default:
3064 throw new IllegalArgumentException("unknown effect id " + effectId +
3065 " not defined in " + SoundEffectConstants.class.getCanonicalName());
3066 }
3067 } catch (IllegalStateException e) {
3068 // Exception thrown by getAudioManager() when mView is null
3069 Log.e(TAG, "FATAL EXCEPTION when attempting to play sound effect: " + e);
3070 e.printStackTrace();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003071 }
3072 }
3073
3074 /**
3075 * {@inheritDoc}
3076 */
3077 public boolean performHapticFeedback(int effectId, boolean always) {
3078 try {
3079 return sWindowSession.performHapticFeedback(mWindow, effectId, always);
3080 } catch (RemoteException e) {
3081 return false;
3082 }
3083 }
3084
3085 /**
3086 * {@inheritDoc}
3087 */
3088 public View focusSearch(View focused, int direction) {
3089 checkThread();
3090 if (!(mView instanceof ViewGroup)) {
3091 return null;
3092 }
3093 return FocusFinder.getInstance().findNextFocus((ViewGroup) mView, focused, direction);
3094 }
3095
3096 public void debug() {
3097 mView.debug();
3098 }
3099
3100 public void die(boolean immediate) {
Dianne Hackborn94d69142009-09-28 22:14:42 -07003101 if (immediate) {
3102 doDie();
3103 } else {
3104 sendEmptyMessage(DIE);
3105 }
3106 }
3107
3108 void doDie() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003109 checkThread();
Jeff Brownb75fa302010-07-15 23:47:29 -07003110 if (LOCAL_LOGV) Log.v(TAG, "DIE in " + this + " of " + mSurface);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003111 synchronized (this) {
3112 if (mAdded && !mFirst) {
Romain Guy29d89972010-09-22 16:10:57 -07003113 destroyHardwareRenderer();
3114
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003115 int viewVisibility = mView.getVisibility();
3116 boolean viewVisibilityChanged = mViewVisibility != viewVisibility;
3117 if (mWindowAttributesChanged || viewVisibilityChanged) {
3118 // If layout params have been changed, first give them
3119 // to the window manager to make sure it has the correct
3120 // animation info.
3121 try {
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07003122 if ((relayoutWindow(mWindowAttributes, viewVisibility, false)
3123 & WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003124 sWindowSession.finishDrawing(mWindow);
3125 }
3126 } catch (RemoteException e) {
3127 }
3128 }
3129
Dianne Hackborn0586a1b2009-09-06 21:08:27 -07003130 mSurface.release();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003131 }
3132 if (mAdded) {
3133 mAdded = false;
Dianne Hackborn94d69142009-09-28 22:14:42 -07003134 dispatchDetachedFromWindow();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003135 }
3136 }
3137 }
3138
Romain Guy29d89972010-09-22 16:10:57 -07003139 private void destroyHardwareRenderer() {
Romain Guyb051e892010-09-28 19:09:36 -07003140 if (mAttachInfo.mHardwareRenderer != null) {
3141 mAttachInfo.mHardwareRenderer.destroy(true);
3142 mAttachInfo.mHardwareRenderer = null;
Romain Guy29d89972010-09-22 16:10:57 -07003143 mAttachInfo.mHardwareAccelerated = false;
3144 }
3145 }
3146
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003147 public void dispatchFinishedEvent(int seq, boolean handled) {
3148 Message msg = obtainMessage(FINISHED_EVENT);
3149 msg.arg1 = seq;
3150 msg.arg2 = handled ? 1 : 0;
3151 sendMessage(msg);
3152 }
Mitsuru Oshima3d914922009-05-13 22:29:15 -07003153
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003154 public void dispatchResized(int w, int h, Rect coveredInsets,
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003155 Rect visibleInsets, boolean reportDraw, Configuration newConfig) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003156 if (DEBUG_LAYOUT) Log.v(TAG, "Resizing " + this + ": w=" + w
3157 + " h=" + h + " coveredInsets=" + coveredInsets.toShortString()
3158 + " visibleInsets=" + visibleInsets.toShortString()
3159 + " reportDraw=" + reportDraw);
3160 Message msg = obtainMessage(reportDraw ? RESIZED_REPORT :RESIZED);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07003161 if (mTranslator != null) {
3162 mTranslator.translateRectInScreenToAppWindow(coveredInsets);
3163 mTranslator.translateRectInScreenToAppWindow(visibleInsets);
3164 w *= mTranslator.applicationInvertedScale;
3165 h *= mTranslator.applicationInvertedScale;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07003166 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07003167 msg.arg1 = w;
3168 msg.arg2 = h;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003169 ResizedInfo ri = new ResizedInfo();
3170 ri.coveredInsets = new Rect(coveredInsets);
3171 ri.visibleInsets = new Rect(visibleInsets);
3172 ri.newConfig = newConfig;
3173 msg.obj = ri;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003174 sendMessage(msg);
3175 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07003176
Jeff Brown3915bb82010-11-05 15:02:16 -07003177 private InputQueue.FinishedCallback mFinishedCallback;
Jeff Brown46b9ac02010-04-22 18:58:52 -07003178
3179 private final InputHandler mInputHandler = new InputHandler() {
Jeff Brown3915bb82010-11-05 15:02:16 -07003180 public void handleKey(KeyEvent event, InputQueue.FinishedCallback finishedCallback) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07003181 startInputEvent(finishedCallback);
Jeff Brown92ff1dd2010-08-11 16:16:06 -07003182 dispatchKey(event, true);
Jeff Brown46b9ac02010-04-22 18:58:52 -07003183 }
3184
Jeff Brown3915bb82010-11-05 15:02:16 -07003185 public void handleMotion(MotionEvent event, InputQueue.FinishedCallback finishedCallback) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07003186 startInputEvent(finishedCallback);
3187 dispatchMotion(event, true);
Jeff Brown46b9ac02010-04-22 18:58:52 -07003188 }
3189 };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003190
3191 public void dispatchKey(KeyEvent event) {
Jeff Brown92ff1dd2010-08-11 16:16:06 -07003192 dispatchKey(event, false);
3193 }
3194
3195 private void dispatchKey(KeyEvent event, boolean sendDone) {
3196 //noinspection ConstantConditions
3197 if (false && event.getAction() == KeyEvent.ACTION_DOWN) {
3198 if (event.getKeyCode() == KeyEvent.KEYCODE_CAMERA) {
Romain Guy812ccbe2010-06-01 14:07:24 -07003199 if (DBG) Log.d("keydisp", "===================================================");
3200 if (DBG) Log.d("keydisp", "Focused view Hierarchy is:");
3201
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003202 debug();
3203
Romain Guy812ccbe2010-06-01 14:07:24 -07003204 if (DBG) Log.d("keydisp", "===================================================");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003205 }
3206 }
3207
3208 Message msg = obtainMessage(DISPATCH_KEY);
3209 msg.obj = event;
Jeff Brown92ff1dd2010-08-11 16:16:06 -07003210 msg.arg1 = sendDone ? 1 : 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003211
3212 if (LOCAL_LOGV) Log.v(
Jeff Brownc5ed5912010-07-14 18:48:53 -07003213 TAG, "sending key " + event + " to " + mView);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003214
3215 sendMessageAtTime(msg, event.getEventTime());
3216 }
Jeff Brownc5ed5912010-07-14 18:48:53 -07003217
3218 public void dispatchMotion(MotionEvent event) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07003219 dispatchMotion(event, false);
3220 }
3221
3222 private void dispatchMotion(MotionEvent event, boolean sendDone) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07003223 int source = event.getSource();
3224 if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07003225 dispatchPointer(event, sendDone);
Jeff Brownc5ed5912010-07-14 18:48:53 -07003226 } else if ((source & InputDevice.SOURCE_CLASS_TRACKBALL) != 0) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07003227 dispatchTrackball(event, sendDone);
Jeff Brownc5ed5912010-07-14 18:48:53 -07003228 } else {
Jeff Browncb1404e2011-01-15 18:14:15 -08003229 dispatchGenericMotion(event, sendDone);
Jeff Brownc5ed5912010-07-14 18:48:53 -07003230 }
3231 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003232
Jeff Brown00fa7bd2010-07-02 15:37:36 -07003233 public void dispatchPointer(MotionEvent event) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07003234 dispatchPointer(event, false);
3235 }
3236
3237 private void dispatchPointer(MotionEvent event, boolean sendDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003238 Message msg = obtainMessage(DISPATCH_POINTER);
3239 msg.obj = event;
Jeff Brown93ed4e32010-09-23 13:51:48 -07003240 msg.arg1 = sendDone ? 1 : 0;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07003241 sendMessageAtTime(msg, event.getEventTime());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003242 }
3243
Jeff Brown00fa7bd2010-07-02 15:37:36 -07003244 public void dispatchTrackball(MotionEvent event) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07003245 dispatchTrackball(event, false);
3246 }
3247
3248 private void dispatchTrackball(MotionEvent event, boolean sendDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003249 Message msg = obtainMessage(DISPATCH_TRACKBALL);
3250 msg.obj = event;
Jeff Brown93ed4e32010-09-23 13:51:48 -07003251 msg.arg1 = sendDone ? 1 : 0;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07003252 sendMessageAtTime(msg, event.getEventTime());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003253 }
Jeff Browncb1404e2011-01-15 18:14:15 -08003254
3255 private void dispatchGenericMotion(MotionEvent event, boolean sendDone) {
3256 Message msg = obtainMessage(DISPATCH_GENERIC_MOTION);
3257 msg.obj = event;
3258 msg.arg1 = sendDone ? 1 : 0;
3259 sendMessageAtTime(msg, event.getEventTime());
3260 }
3261
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003262 public void dispatchAppVisibility(boolean visible) {
3263 Message msg = obtainMessage(DISPATCH_APP_VISIBILITY);
3264 msg.arg1 = visible ? 1 : 0;
3265 sendMessage(msg);
3266 }
3267
3268 public void dispatchGetNewSurface() {
3269 Message msg = obtainMessage(DISPATCH_GET_NEW_SURFACE);
3270 sendMessage(msg);
3271 }
3272
3273 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
3274 Message msg = Message.obtain();
3275 msg.what = WINDOW_FOCUS_CHANGED;
3276 msg.arg1 = hasFocus ? 1 : 0;
3277 msg.arg2 = inTouchMode ? 1 : 0;
3278 sendMessage(msg);
3279 }
3280
Dianne Hackbornffa42482009-09-23 22:20:11 -07003281 public void dispatchCloseSystemDialogs(String reason) {
3282 Message msg = Message.obtain();
3283 msg.what = CLOSE_SYSTEM_DIALOGS;
3284 msg.obj = reason;
3285 sendMessage(msg);
3286 }
Christopher Tatea53146c2010-09-07 11:57:52 -07003287
3288 public void dispatchDragEvent(DragEvent event) {
Chris Tate91e9bb32010-10-12 12:58:43 -07003289 final int what;
3290 if (event.getAction() == DragEvent.ACTION_DRAG_LOCATION) {
3291 what = DISPATCH_DRAG_LOCATION_EVENT;
3292 removeMessages(what);
3293 } else {
3294 what = DISPATCH_DRAG_EVENT;
3295 }
3296 Message msg = obtainMessage(what, event);
Christopher Tatea53146c2010-09-07 11:57:52 -07003297 sendMessage(msg);
3298 }
3299
Joe Onorato664644d2011-01-23 17:53:23 -08003300 public void dispatchSystemUiVisibilityChanged(int visibility) {
3301 sendMessage(obtainMessage(DISPATCH_SYSTEM_UI_VISIBILITY, visibility, 0));
3302 }
3303
svetoslavganov75986cf2009-05-14 22:28:01 -07003304 /**
3305 * The window is getting focus so if there is anything focused/selected
3306 * send an {@link AccessibilityEvent} to announce that.
3307 */
3308 private void sendAccessibilityEvents() {
3309 if (!AccessibilityManager.getInstance(mView.getContext()).isEnabled()) {
3310 return;
3311 }
3312 mView.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
3313 View focusedView = mView.findFocus();
3314 if (focusedView != null && focusedView != mView) {
3315 focusedView.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
3316 }
3317 }
3318
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003319 public boolean showContextMenuForChild(View originalView) {
3320 return false;
3321 }
3322
Adam Powell6e346362010-07-23 10:18:23 -07003323 public ActionMode startActionModeForChild(View originalView, ActionMode.Callback callback) {
3324 return null;
3325 }
3326
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003327 public void createContextMenu(ContextMenu menu) {
3328 }
3329
3330 public void childDrawableStateChanged(View child) {
3331 }
3332
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003333 void checkThread() {
3334 if (mThread != Thread.currentThread()) {
3335 throw new CalledFromWrongThreadException(
3336 "Only the original thread that created a view hierarchy can touch its views.");
3337 }
3338 }
3339
3340 public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
3341 // ViewRoot never intercepts touch event, so this can be a no-op
3342 }
3343
3344 public boolean requestChildRectangleOnScreen(View child, Rect rectangle,
3345 boolean immediate) {
3346 return scrollToRectOrFocus(rectangle, immediate);
3347 }
Romain Guy8506ab42009-06-11 17:35:47 -07003348
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07003349 class TakenSurfaceHolder extends BaseSurfaceHolder {
3350 @Override
3351 public boolean onAllowLockCanvas() {
3352 return mDrawingAllowed;
3353 }
3354
3355 @Override
3356 public void onRelayoutContainer() {
3357 // Not currently interesting -- from changing between fixed and layout size.
3358 }
3359
3360 public void setFormat(int format) {
3361 ((RootViewSurfaceTaker)mView).setSurfaceFormat(format);
3362 }
3363
3364 public void setType(int type) {
3365 ((RootViewSurfaceTaker)mView).setSurfaceType(type);
3366 }
3367
3368 @Override
3369 public void onUpdateSurface() {
3370 // We take care of format and type changes on our own.
3371 throw new IllegalStateException("Shouldn't be here");
3372 }
3373
3374 public boolean isCreating() {
3375 return mIsCreating;
3376 }
3377
3378 @Override
3379 public void setFixedSize(int width, int height) {
3380 throw new UnsupportedOperationException(
3381 "Currently only support sizing from layout");
3382 }
3383
3384 public void setKeepScreenOn(boolean screenOn) {
3385 ((RootViewSurfaceTaker)mView).setSurfaceKeepScreenOn(screenOn);
3386 }
3387 }
3388
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003389 static class InputMethodCallback extends IInputMethodCallback.Stub {
3390 private WeakReference<ViewRoot> mViewRoot;
3391
3392 public InputMethodCallback(ViewRoot viewRoot) {
3393 mViewRoot = new WeakReference<ViewRoot>(viewRoot);
3394 }
Romain Guy8506ab42009-06-11 17:35:47 -07003395
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003396 public void finishedEvent(int seq, boolean handled) {
3397 final ViewRoot viewRoot = mViewRoot.get();
3398 if (viewRoot != null) {
3399 viewRoot.dispatchFinishedEvent(seq, handled);
3400 }
3401 }
3402
3403 public void sessionCreated(IInputMethodSession session) throws RemoteException {
3404 // Stub -- not for use in the client.
3405 }
3406 }
Romain Guy8506ab42009-06-11 17:35:47 -07003407
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003408 static class W extends IWindow.Stub {
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07003409 private final WeakReference<ViewRoot> mViewRoot;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003410
Romain Guyfb8b7632010-08-23 21:05:08 -07003411 W(ViewRoot viewRoot) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003412 mViewRoot = new WeakReference<ViewRoot>(viewRoot);
3413 }
3414
Romain Guyfb8b7632010-08-23 21:05:08 -07003415 public void resized(int w, int h, Rect coveredInsets, Rect visibleInsets,
3416 boolean reportDraw, Configuration newConfig) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003417 final ViewRoot viewRoot = mViewRoot.get();
3418 if (viewRoot != null) {
Romain Guyfb8b7632010-08-23 21:05:08 -07003419 viewRoot.dispatchResized(w, h, coveredInsets, visibleInsets, reportDraw, newConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003420 }
3421 }
3422
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003423 public void dispatchAppVisibility(boolean visible) {
3424 final ViewRoot viewRoot = mViewRoot.get();
3425 if (viewRoot != null) {
3426 viewRoot.dispatchAppVisibility(visible);
3427 }
3428 }
3429
3430 public void dispatchGetNewSurface() {
3431 final ViewRoot viewRoot = mViewRoot.get();
3432 if (viewRoot != null) {
3433 viewRoot.dispatchGetNewSurface();
3434 }
3435 }
3436
3437 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
3438 final ViewRoot viewRoot = mViewRoot.get();
3439 if (viewRoot != null) {
3440 viewRoot.windowFocusChanged(hasFocus, inTouchMode);
3441 }
3442 }
3443
3444 private static int checkCallingPermission(String permission) {
3445 if (!Process.supportsProcesses()) {
3446 return PackageManager.PERMISSION_GRANTED;
3447 }
3448
3449 try {
3450 return ActivityManagerNative.getDefault().checkPermission(
3451 permission, Binder.getCallingPid(), Binder.getCallingUid());
3452 } catch (RemoteException e) {
3453 return PackageManager.PERMISSION_DENIED;
3454 }
3455 }
3456
3457 public void executeCommand(String command, String parameters, ParcelFileDescriptor out) {
3458 final ViewRoot viewRoot = mViewRoot.get();
3459 if (viewRoot != null) {
3460 final View view = viewRoot.mView;
3461 if (view != null) {
3462 if (checkCallingPermission(Manifest.permission.DUMP) !=
3463 PackageManager.PERMISSION_GRANTED) {
3464 throw new SecurityException("Insufficient permissions to invoke"
3465 + " executeCommand() from pid=" + Binder.getCallingPid()
3466 + ", uid=" + Binder.getCallingUid());
3467 }
3468
3469 OutputStream clientStream = null;
3470 try {
3471 clientStream = new ParcelFileDescriptor.AutoCloseOutputStream(out);
3472 ViewDebug.dispatchCommand(view, command, parameters, clientStream);
3473 } catch (IOException e) {
3474 e.printStackTrace();
3475 } finally {
3476 if (clientStream != null) {
3477 try {
3478 clientStream.close();
3479 } catch (IOException e) {
3480 e.printStackTrace();
3481 }
3482 }
3483 }
3484 }
3485 }
3486 }
Dianne Hackborn72c82ab2009-08-11 21:13:54 -07003487
Dianne Hackbornffa42482009-09-23 22:20:11 -07003488 public void closeSystemDialogs(String reason) {
3489 final ViewRoot viewRoot = mViewRoot.get();
3490 if (viewRoot != null) {
3491 viewRoot.dispatchCloseSystemDialogs(reason);
3492 }
3493 }
3494
Marco Nelissenbf6956b2009-11-09 15:21:13 -08003495 public void dispatchWallpaperOffsets(float x, float y, float xStep, float yStep,
3496 boolean sync) {
Dianne Hackborn19382ac2009-09-11 21:13:37 -07003497 if (sync) {
3498 try {
3499 sWindowSession.wallpaperOffsetsComplete(asBinder());
3500 } catch (RemoteException e) {
3501 }
3502 }
Dianne Hackborn72c82ab2009-08-11 21:13:54 -07003503 }
Dianne Hackborn75804932009-10-20 20:15:20 -07003504
3505 public void dispatchWallpaperCommand(String action, int x, int y,
3506 int z, Bundle extras, boolean sync) {
3507 if (sync) {
3508 try {
3509 sWindowSession.wallpaperCommandComplete(asBinder(), null);
3510 } catch (RemoteException e) {
3511 }
3512 }
3513 }
Christopher Tatea53146c2010-09-07 11:57:52 -07003514
3515 /* Drag/drop */
3516 public void dispatchDragEvent(DragEvent event) {
3517 final ViewRoot viewRoot = mViewRoot.get();
3518 if (viewRoot != null) {
3519 viewRoot.dispatchDragEvent(event);
3520 }
3521 }
Joe Onorato664644d2011-01-23 17:53:23 -08003522
3523 @Override
3524 public void dispatchSystemUiVisibilityChanged(int visibility) {
3525 final ViewRoot viewRoot = mViewRoot.get();
3526 if (viewRoot != null) {
3527 viewRoot.dispatchSystemUiVisibilityChanged(visibility);
3528 }
3529 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003530 }
3531
3532 /**
3533 * Maintains state information for a single trackball axis, generating
3534 * discrete (DPAD) movements based on raw trackball motion.
3535 */
3536 static final class TrackballAxis {
3537 /**
3538 * The maximum amount of acceleration we will apply.
3539 */
3540 static final float MAX_ACCELERATION = 20;
Romain Guy8506ab42009-06-11 17:35:47 -07003541
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003542 /**
3543 * The maximum amount of time (in milliseconds) between events in order
3544 * for us to consider the user to be doing fast trackball movements,
3545 * and thus apply an acceleration.
3546 */
3547 static final long FAST_MOVE_TIME = 150;
Romain Guy8506ab42009-06-11 17:35:47 -07003548
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003549 /**
3550 * Scaling factor to the time (in milliseconds) between events to how
3551 * much to multiple/divide the current acceleration. When movement
3552 * is < FAST_MOVE_TIME this multiplies the acceleration; when >
3553 * FAST_MOVE_TIME it divides it.
3554 */
3555 static final float ACCEL_MOVE_SCALING_FACTOR = (1.0f/40);
Romain Guy8506ab42009-06-11 17:35:47 -07003556
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003557 float position;
3558 float absPosition;
3559 float acceleration = 1;
3560 long lastMoveTime = 0;
3561 int step;
3562 int dir;
3563 int nonAccelMovement;
3564
3565 void reset(int _step) {
3566 position = 0;
3567 acceleration = 1;
3568 lastMoveTime = 0;
3569 step = _step;
3570 dir = 0;
3571 }
3572
3573 /**
3574 * Add trackball movement into the state. If the direction of movement
3575 * has been reversed, the state is reset before adding the
3576 * movement (so that you don't have to compensate for any previously
3577 * collected movement before see the result of the movement in the
3578 * new direction).
3579 *
3580 * @return Returns the absolute value of the amount of movement
3581 * collected so far.
3582 */
3583 float collect(float off, long time, String axis) {
3584 long normTime;
3585 if (off > 0) {
3586 normTime = (long)(off * FAST_MOVE_TIME);
3587 if (dir < 0) {
3588 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to positive!");
3589 position = 0;
3590 step = 0;
3591 acceleration = 1;
3592 lastMoveTime = 0;
3593 }
3594 dir = 1;
3595 } else if (off < 0) {
3596 normTime = (long)((-off) * FAST_MOVE_TIME);
3597 if (dir > 0) {
3598 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to negative!");
3599 position = 0;
3600 step = 0;
3601 acceleration = 1;
3602 lastMoveTime = 0;
3603 }
3604 dir = -1;
3605 } else {
3606 normTime = 0;
3607 }
Romain Guy8506ab42009-06-11 17:35:47 -07003608
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003609 // The number of milliseconds between each movement that is
3610 // considered "normal" and will not result in any acceleration
3611 // or deceleration, scaled by the offset we have here.
3612 if (normTime > 0) {
3613 long delta = time - lastMoveTime;
3614 lastMoveTime = time;
3615 float acc = acceleration;
3616 if (delta < normTime) {
3617 // The user is scrolling rapidly, so increase acceleration.
3618 float scale = (normTime-delta) * ACCEL_MOVE_SCALING_FACTOR;
3619 if (scale > 1) acc *= scale;
3620 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " accelerate: off="
3621 + off + " normTime=" + normTime + " delta=" + delta
3622 + " scale=" + scale + " acc=" + acc);
3623 acceleration = acc < MAX_ACCELERATION ? acc : MAX_ACCELERATION;
3624 } else {
3625 // The user is scrolling slowly, so decrease acceleration.
3626 float scale = (delta-normTime) * ACCEL_MOVE_SCALING_FACTOR;
3627 if (scale > 1) acc /= scale;
3628 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " deccelerate: off="
3629 + off + " normTime=" + normTime + " delta=" + delta
3630 + " scale=" + scale + " acc=" + acc);
3631 acceleration = acc > 1 ? acc : 1;
3632 }
3633 }
3634 position += off;
3635 return (absPosition = Math.abs(position));
3636 }
3637
3638 /**
3639 * Generate the number of discrete movement events appropriate for
3640 * the currently collected trackball movement.
3641 *
3642 * @param precision The minimum movement required to generate the
3643 * first discrete movement.
3644 *
3645 * @return Returns the number of discrete movements, either positive
3646 * or negative, or 0 if there is not enough trackball movement yet
3647 * for a discrete movement.
3648 */
3649 int generate(float precision) {
3650 int movement = 0;
3651 nonAccelMovement = 0;
3652 do {
3653 final int dir = position >= 0 ? 1 : -1;
3654 switch (step) {
3655 // If we are going to execute the first step, then we want
3656 // to do this as soon as possible instead of waiting for
3657 // a full movement, in order to make things look responsive.
3658 case 0:
3659 if (absPosition < precision) {
3660 return movement;
3661 }
3662 movement += dir;
3663 nonAccelMovement += dir;
3664 step = 1;
3665 break;
3666 // If we have generated the first movement, then we need
3667 // to wait for the second complete trackball motion before
3668 // generating the second discrete movement.
3669 case 1:
3670 if (absPosition < 2) {
3671 return movement;
3672 }
3673 movement += dir;
3674 nonAccelMovement += dir;
3675 position += dir > 0 ? -2 : 2;
3676 absPosition = Math.abs(position);
3677 step = 2;
3678 break;
3679 // After the first two, we generate discrete movements
3680 // consistently with the trackball, applying an acceleration
3681 // if the trackball is moving quickly. This is a simple
3682 // acceleration on top of what we already compute based
3683 // on how quickly the wheel is being turned, to apply
3684 // a longer increasing acceleration to continuous movement
3685 // in one direction.
3686 default:
3687 if (absPosition < 1) {
3688 return movement;
3689 }
3690 movement += dir;
3691 position += dir >= 0 ? -1 : 1;
3692 absPosition = Math.abs(position);
3693 float acc = acceleration;
3694 acc *= 1.1f;
3695 acceleration = acc < MAX_ACCELERATION ? acc : acceleration;
3696 break;
3697 }
3698 } while (true);
3699 }
3700 }
3701
3702 public static final class CalledFromWrongThreadException extends AndroidRuntimeException {
3703 public CalledFromWrongThreadException(String msg) {
3704 super(msg);
3705 }
3706 }
3707
3708 private SurfaceHolder mHolder = new SurfaceHolder() {
3709 // we only need a SurfaceHolder for opengl. it would be nice
3710 // to implement everything else though, especially the callback
3711 // support (opengl doesn't make use of it right now, but eventually
3712 // will).
3713 public Surface getSurface() {
3714 return mSurface;
3715 }
3716
3717 public boolean isCreating() {
3718 return false;
3719 }
3720
3721 public void addCallback(Callback callback) {
3722 }
3723
3724 public void removeCallback(Callback callback) {
3725 }
3726
3727 public void setFixedSize(int width, int height) {
3728 }
3729
3730 public void setSizeFromLayout() {
3731 }
3732
3733 public void setFormat(int format) {
3734 }
3735
3736 public void setType(int type) {
3737 }
3738
3739 public void setKeepScreenOn(boolean screenOn) {
3740 }
3741
3742 public Canvas lockCanvas() {
3743 return null;
3744 }
3745
3746 public Canvas lockCanvas(Rect dirty) {
3747 return null;
3748 }
3749
3750 public void unlockCanvasAndPost(Canvas canvas) {
3751 }
3752 public Rect getSurfaceFrame() {
3753 return null;
3754 }
3755 };
3756
3757 static RunQueue getRunQueue() {
3758 RunQueue rq = sRunQueues.get();
3759 if (rq != null) {
3760 return rq;
3761 }
3762 rq = new RunQueue();
3763 sRunQueues.set(rq);
3764 return rq;
3765 }
Romain Guy8506ab42009-06-11 17:35:47 -07003766
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003767 /**
3768 * @hide
3769 */
3770 static final class RunQueue {
3771 private final ArrayList<HandlerAction> mActions = new ArrayList<HandlerAction>();
3772
3773 void post(Runnable action) {
3774 postDelayed(action, 0);
3775 }
3776
3777 void postDelayed(Runnable action, long delayMillis) {
3778 HandlerAction handlerAction = new HandlerAction();
3779 handlerAction.action = action;
3780 handlerAction.delay = delayMillis;
3781
3782 synchronized (mActions) {
3783 mActions.add(handlerAction);
3784 }
3785 }
3786
3787 void removeCallbacks(Runnable action) {
3788 final HandlerAction handlerAction = new HandlerAction();
3789 handlerAction.action = action;
3790
3791 synchronized (mActions) {
3792 final ArrayList<HandlerAction> actions = mActions;
3793
3794 while (actions.remove(handlerAction)) {
3795 // Keep going
3796 }
3797 }
3798 }
3799
3800 void executeActions(Handler handler) {
3801 synchronized (mActions) {
3802 final ArrayList<HandlerAction> actions = mActions;
3803 final int count = actions.size();
3804
3805 for (int i = 0; i < count; i++) {
3806 final HandlerAction handlerAction = actions.get(i);
3807 handler.postDelayed(handlerAction.action, handlerAction.delay);
3808 }
3809
Romain Guy15df6702009-08-17 20:17:30 -07003810 actions.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003811 }
3812 }
3813
3814 private static class HandlerAction {
3815 Runnable action;
3816 long delay;
3817
3818 @Override
3819 public boolean equals(Object o) {
3820 if (this == o) return true;
3821 if (o == null || getClass() != o.getClass()) return false;
3822
3823 HandlerAction that = (HandlerAction) o;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003824 return !(action != null ? !action.equals(that.action) : that.action != null);
3825
3826 }
3827
3828 @Override
3829 public int hashCode() {
3830 int result = action != null ? action.hashCode() : 0;
3831 result = 31 * result + (int) (delay ^ (delay >>> 32));
3832 return result;
3833 }
3834 }
3835 }
3836
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003837 private static native void nativeShowFPS(Canvas canvas, int durationMillis);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003838}