blob: ec1a373397aecd9d2c7a0fe0df34ca9fbce6478f [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)) {
2499 ensureTouchMode(false);
2500 if (isJoystick) {
2501 updateJoystickDirection(event, false);
2502 }
2503 finishGenericMotionEvent(event, sendDone, true);
2504 return;
2505 }
2506
2507 if (isJoystick) {
2508 // Translate the joystick event into DPAD keys and try to deliver those.
2509 updateJoystickDirection(event, true);
2510 finishGenericMotionEvent(event, sendDone, true);
2511 } else {
2512 finishGenericMotionEvent(event, sendDone, false);
2513 }
2514 }
2515
2516 private void finishGenericMotionEvent(MotionEvent event, boolean sendDone, boolean handled) {
2517 event.recycle();
2518 if (sendDone) {
2519 finishInputEvent(handled);
2520 }
2521 }
2522
2523 private void updateJoystickDirection(MotionEvent event, boolean synthesizeNewKeys) {
2524 final long time = event.getEventTime();
2525 final int metaState = event.getMetaState();
2526 final int deviceId = event.getDeviceId();
2527 final int source = event.getSource();
2528 final int xDirection = joystickAxisValueToDirection(event.getX());
2529 final int yDirection = joystickAxisValueToDirection(event.getY());
2530
2531 if (xDirection != mLastJoystickXDirection) {
2532 if (mLastJoystickXKeyCode != 0) {
2533 deliverKeyEvent(new KeyEvent(time, time,
2534 KeyEvent.ACTION_UP, mLastJoystickXKeyCode, 0, metaState,
2535 deviceId, 0, KeyEvent.FLAG_FALLBACK, source), false);
2536 mLastJoystickXKeyCode = 0;
2537 }
2538
2539 mLastJoystickXDirection = xDirection;
2540
2541 if (xDirection != 0 && synthesizeNewKeys) {
2542 mLastJoystickXKeyCode = xDirection > 0
2543 ? KeyEvent.KEYCODE_DPAD_RIGHT : KeyEvent.KEYCODE_DPAD_LEFT;
2544 deliverKeyEvent(new KeyEvent(time, time,
2545 KeyEvent.ACTION_DOWN, mLastJoystickXKeyCode, 0, metaState,
2546 deviceId, 0, KeyEvent.FLAG_FALLBACK, source), false);
2547 }
2548 }
2549
2550 if (yDirection != mLastJoystickYDirection) {
2551 if (mLastJoystickYKeyCode != 0) {
2552 deliverKeyEvent(new KeyEvent(time, time,
2553 KeyEvent.ACTION_UP, mLastJoystickYKeyCode, 0, metaState,
2554 deviceId, 0, KeyEvent.FLAG_FALLBACK, source), false);
2555 mLastJoystickYKeyCode = 0;
2556 }
2557
2558 mLastJoystickYDirection = yDirection;
2559
2560 if (yDirection != 0 && synthesizeNewKeys) {
2561 mLastJoystickYKeyCode = yDirection > 0
2562 ? KeyEvent.KEYCODE_DPAD_DOWN : KeyEvent.KEYCODE_DPAD_UP;
2563 deliverKeyEvent(new KeyEvent(time, time,
2564 KeyEvent.ACTION_DOWN, mLastJoystickYKeyCode, 0, metaState,
2565 deviceId, 0, KeyEvent.FLAG_FALLBACK, source), false);
2566 }
2567 }
2568 }
2569
2570 private static int joystickAxisValueToDirection(float value) {
2571 if (value >= 0.5f) {
2572 return 1;
2573 } else if (value <= -0.5f) {
2574 return -1;
2575 } else {
2576 return 0;
2577 }
2578 }
2579
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002580 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08002581 * Returns true if the key is used for keyboard navigation.
2582 * @param keyEvent The key event.
2583 * @return True if the key is used for keyboard navigation.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002584 */
Jeff Brown4e6319b2010-12-13 10:36:51 -08002585 private static boolean isNavigationKey(KeyEvent keyEvent) {
2586 switch (keyEvent.getKeyCode()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002587 case KeyEvent.KEYCODE_DPAD_LEFT:
2588 case KeyEvent.KEYCODE_DPAD_RIGHT:
2589 case KeyEvent.KEYCODE_DPAD_UP:
2590 case KeyEvent.KEYCODE_DPAD_DOWN:
Jeff Brown4e6319b2010-12-13 10:36:51 -08002591 case KeyEvent.KEYCODE_DPAD_CENTER:
2592 case KeyEvent.KEYCODE_PAGE_UP:
2593 case KeyEvent.KEYCODE_PAGE_DOWN:
2594 case KeyEvent.KEYCODE_MOVE_HOME:
2595 case KeyEvent.KEYCODE_MOVE_END:
2596 case KeyEvent.KEYCODE_TAB:
2597 case KeyEvent.KEYCODE_SPACE:
2598 case KeyEvent.KEYCODE_ENTER:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002599 return true;
2600 }
2601 return false;
2602 }
2603
2604 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08002605 * Returns true if the key is used for typing.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002606 * @param keyEvent The key event.
Jeff Brown4e6319b2010-12-13 10:36:51 -08002607 * @return True if the key is used for typing.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002608 */
Jeff Brown4e6319b2010-12-13 10:36:51 -08002609 private static boolean isTypingKey(KeyEvent keyEvent) {
2610 return keyEvent.getUnicodeChar() > 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002611 }
2612
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002613 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08002614 * 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 -08002615 * @param event The key event.
2616 * @return Whether this key event should be consumed (meaning the act of
2617 * leaving touch mode alone is considered the event).
2618 */
2619 private boolean checkForLeavingTouchModeAndConsume(KeyEvent event) {
Jeff Brown4e6319b2010-12-13 10:36:51 -08002620 // Only relevant in touch mode.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002621 if (!mAttachInfo.mInTouchMode) {
2622 return false;
2623 }
2624
Jeff Brown4e6319b2010-12-13 10:36:51 -08002625 // Only consider leaving touch mode on DOWN or MULTIPLE actions, never on UP.
2626 final int action = event.getAction();
2627 if (action != KeyEvent.ACTION_DOWN && action != KeyEvent.ACTION_MULTIPLE) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002628 return false;
2629 }
2630
Jeff Brown4e6319b2010-12-13 10:36:51 -08002631 // Don't leave touch mode if the IME told us not to.
2632 if ((event.getFlags() & KeyEvent.FLAG_KEEP_TOUCH_MODE) != 0) {
2633 return false;
2634 }
2635
2636 // If the key can be used for keyboard navigation then leave touch mode
2637 // and select a focused view if needed (in ensureTouchMode).
2638 // When a new focused view is selected, we consume the navigation key because
2639 // navigation doesn't make much sense unless a view already has focus so
2640 // the key's purpose is to set focus.
2641 if (isNavigationKey(event)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002642 return ensureTouchMode(false);
2643 }
Jeff Brown4e6319b2010-12-13 10:36:51 -08002644
2645 // If the key can be used for typing then leave touch mode
2646 // and select a focused view if needed (in ensureTouchMode).
2647 // Always allow the view to process the typing key.
2648 if (isTypingKey(event)) {
2649 ensureTouchMode(false);
2650 return false;
2651 }
2652
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002653 return false;
2654 }
2655
2656 /**
Romain Guy8506ab42009-06-11 17:35:47 -07002657 * log motion events
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002658 */
2659 private static void captureMotionLog(String subTag, MotionEvent ev) {
Romain Guy8506ab42009-06-11 17:35:47 -07002660 //check dynamic switch
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002661 if (ev == null ||
2662 SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_EVENT, 0) == 0) {
2663 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002664 }
Romain Guy8506ab42009-06-11 17:35:47 -07002665
2666 StringBuilder sb = new StringBuilder(subTag + ": ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002667 sb.append(ev.getDownTime()).append(',');
2668 sb.append(ev.getEventTime()).append(',');
2669 sb.append(ev.getAction()).append(',');
Romain Guy8506ab42009-06-11 17:35:47 -07002670 sb.append(ev.getX()).append(',');
2671 sb.append(ev.getY()).append(',');
2672 sb.append(ev.getPressure()).append(',');
2673 sb.append(ev.getSize()).append(',');
2674 sb.append(ev.getMetaState()).append(',');
2675 sb.append(ev.getXPrecision()).append(',');
2676 sb.append(ev.getYPrecision()).append(',');
2677 sb.append(ev.getDeviceId()).append(',');
2678 sb.append(ev.getEdgeFlags());
2679 Log.d(TAG, sb.toString());
2680 }
2681 /**
2682 * log motion events
2683 */
2684 private static void captureKeyLog(String subTag, KeyEvent ev) {
2685 //check dynamic switch
2686 if (ev == null ||
2687 SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_EVENT, 0) == 0) {
2688 return;
2689 }
2690 StringBuilder sb = new StringBuilder(subTag + ": ");
2691 sb.append(ev.getDownTime()).append(',');
2692 sb.append(ev.getEventTime()).append(',');
2693 sb.append(ev.getAction()).append(',');
2694 sb.append(ev.getKeyCode()).append(',');
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002695 sb.append(ev.getRepeatCount()).append(',');
2696 sb.append(ev.getMetaState()).append(',');
2697 sb.append(ev.getDeviceId()).append(',');
2698 sb.append(ev.getScanCode());
Romain Guy8506ab42009-06-11 17:35:47 -07002699 Log.d(TAG, sb.toString());
2700 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002701
2702 int enqueuePendingEvent(Object event, boolean sendDone) {
2703 int seq = mPendingEventSeq+1;
2704 if (seq < 0) seq = 0;
2705 mPendingEventSeq = seq;
2706 mPendingEvents.put(seq, event);
2707 return sendDone ? seq : -seq;
2708 }
2709
2710 Object retrievePendingEvent(int seq) {
2711 if (seq < 0) seq = -seq;
2712 Object event = mPendingEvents.get(seq);
2713 if (event != null) {
2714 mPendingEvents.remove(seq);
2715 }
2716 return event;
2717 }
Romain Guy8506ab42009-06-11 17:35:47 -07002718
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002719 private void deliverKeyEvent(KeyEvent event, boolean sendDone) {
Jeff Brown3915bb82010-11-05 15:02:16 -07002720 // If there is no view, then the event will not be handled.
2721 if (mView == null || !mAdded) {
2722 finishKeyEvent(event, sendDone, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002723 return;
2724 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002725
2726 if (LOCAL_LOGV) Log.v(TAG, "Dispatching key " + event + " to " + mView);
2727
2728 // Perform predispatching before the IME.
2729 if (mView.dispatchKeyEventPreIme(event)) {
2730 finishKeyEvent(event, sendDone, true);
2731 return;
2732 }
2733
2734 // Dispatch to the IME before propagating down the view hierarchy.
2735 // The IME will eventually call back into handleFinishedEvent.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002736 if (mLastWasImTarget) {
2737 InputMethodManager imm = InputMethodManager.peekInstance();
Jeff Brown3915bb82010-11-05 15:02:16 -07002738 if (imm != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002739 int seq = enqueuePendingEvent(event, sendDone);
2740 if (DEBUG_IMF) Log.v(TAG, "Sending key event to IME: seq="
2741 + seq + " event=" + event);
Jeff Brown3915bb82010-11-05 15:02:16 -07002742 imm.dispatchKeyEvent(mView.getContext(), seq, event, mInputMethodCallback);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002743 return;
2744 }
2745 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002746
2747 // Not dispatching to IME, continue with post IME actions.
2748 deliverKeyEventPostIme(event, sendDone);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002749 }
2750
Jeff Brown3915bb82010-11-05 15:02:16 -07002751 private void handleFinishedEvent(int seq, boolean handled) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002752 final KeyEvent event = (KeyEvent)retrievePendingEvent(seq);
2753 if (DEBUG_IMF) Log.v(TAG, "IME finished event: seq=" + seq
2754 + " handled=" + handled + " event=" + event);
2755 if (event != null) {
2756 final boolean sendDone = seq >= 0;
Jeff Brown3915bb82010-11-05 15:02:16 -07002757 if (handled) {
2758 finishKeyEvent(event, sendDone, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002759 } else {
Jeff Brown3915bb82010-11-05 15:02:16 -07002760 deliverKeyEventPostIme(event, sendDone);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002761 }
2762 }
2763 }
Romain Guy8506ab42009-06-11 17:35:47 -07002764
Jeff Brown3915bb82010-11-05 15:02:16 -07002765 private void deliverKeyEventPostIme(KeyEvent event, boolean sendDone) {
2766 // If the view went away, then the event will not be handled.
2767 if (mView == null || !mAdded) {
2768 finishKeyEvent(event, sendDone, false);
2769 return;
2770 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002771
Jeff Brown3915bb82010-11-05 15:02:16 -07002772 // If the key's purpose is to exit touch mode then we consume it and consider it handled.
2773 if (checkForLeavingTouchModeAndConsume(event)) {
2774 finishKeyEvent(event, sendDone, true);
2775 return;
2776 }
Romain Guy8506ab42009-06-11 17:35:47 -07002777
Jeff Brown3915bb82010-11-05 15:02:16 -07002778 if (Config.LOGV) {
2779 captureKeyLog("captureDispatchKeyEvent", event);
2780 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002781
Jeff Brown90655042010-12-02 13:50:46 -08002782 // Make sure the fallback event policy sees all keys that will be delivered to the
2783 // view hierarchy.
2784 mFallbackEventHandler.preDispatchKeyEvent(event);
2785
Jeff Brown3915bb82010-11-05 15:02:16 -07002786 // Deliver the key to the view hierarchy.
2787 if (mView.dispatchKeyEvent(event)) {
2788 finishKeyEvent(event, sendDone, true);
2789 return;
2790 }
Joe Onorato86f67862010-11-05 18:57:34 -07002791
Jeff Brownc1df9072010-12-21 16:38:50 -08002792 // If the Control modifier is held, try to interpret the key as a shortcut.
2793 if (event.getAction() == KeyEvent.ACTION_UP
2794 && event.isCtrlPressed()
2795 && !KeyEvent.isModifierKey(event.getKeyCode())) {
2796 if (mView.dispatchKeyShortcutEvent(event)) {
2797 finishKeyEvent(event, sendDone, true);
2798 return;
2799 }
2800 }
2801
Jeff Brown3915bb82010-11-05 15:02:16 -07002802 // Apply the fallback event policy.
2803 if (mFallbackEventHandler.dispatchKeyEvent(event)) {
2804 finishKeyEvent(event, sendDone, true);
2805 return;
2806 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002807
Jeff Brown3915bb82010-11-05 15:02:16 -07002808 // Handle automatic focus changes.
2809 if (event.getAction() == KeyEvent.ACTION_DOWN) {
2810 int direction = 0;
2811 switch (event.getKeyCode()) {
2812 case KeyEvent.KEYCODE_DPAD_LEFT:
Jeff Brown4e6319b2010-12-13 10:36:51 -08002813 if (event.hasNoModifiers()) {
2814 direction = View.FOCUS_LEFT;
2815 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002816 break;
2817 case KeyEvent.KEYCODE_DPAD_RIGHT:
Jeff Brown4e6319b2010-12-13 10:36:51 -08002818 if (event.hasNoModifiers()) {
2819 direction = View.FOCUS_RIGHT;
2820 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002821 break;
2822 case KeyEvent.KEYCODE_DPAD_UP:
Jeff Brown4e6319b2010-12-13 10:36:51 -08002823 if (event.hasNoModifiers()) {
2824 direction = View.FOCUS_UP;
2825 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002826 break;
2827 case KeyEvent.KEYCODE_DPAD_DOWN:
Jeff Brown4e6319b2010-12-13 10:36:51 -08002828 if (event.hasNoModifiers()) {
2829 direction = View.FOCUS_DOWN;
2830 }
2831 break;
2832 case KeyEvent.KEYCODE_TAB:
2833 if (event.hasNoModifiers()) {
2834 direction = View.FOCUS_FORWARD;
2835 } else if (event.hasModifiers(KeyEvent.META_SHIFT_ON)) {
2836 direction = View.FOCUS_BACKWARD;
2837 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002838 break;
2839 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002840
Jeff Brown3915bb82010-11-05 15:02:16 -07002841 if (direction != 0) {
2842 View focused = mView != null ? mView.findFocus() : null;
2843 if (focused != null) {
2844 View v = focused.focusSearch(direction);
2845 if (v != null && v != focused) {
2846 // do the math the get the interesting rect
2847 // of previous focused into the coord system of
2848 // newly focused view
2849 focused.getFocusedRect(mTempRect);
2850 if (mView instanceof ViewGroup) {
2851 ((ViewGroup) mView).offsetDescendantRectToMyCoords(
2852 focused, mTempRect);
2853 ((ViewGroup) mView).offsetRectIntoDescendantCoords(
2854 v, mTempRect);
2855 }
2856 if (v.requestFocus(direction, mTempRect)) {
2857 playSoundEffect(
2858 SoundEffectConstants.getContantForFocusDirection(direction));
2859 finishKeyEvent(event, sendDone, true);
2860 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002861 }
2862 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002863
2864 // Give the focused view a last chance to handle the dpad key.
2865 if (mView.dispatchUnhandledMove(focused, direction)) {
2866 finishKeyEvent(event, sendDone, true);
2867 return;
2868 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002869 }
2870 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002871 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002872
Jeff Brown3915bb82010-11-05 15:02:16 -07002873 // Key was unhandled.
2874 finishKeyEvent(event, sendDone, false);
2875 }
2876
2877 private void finishKeyEvent(KeyEvent event, boolean sendDone, boolean handled) {
2878 if (sendDone) {
2879 finishInputEvent(handled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002880 }
2881 }
2882
Christopher Tatea53146c2010-09-07 11:57:52 -07002883 /* drag/drop */
Christopher Tate407b4e92010-11-30 17:14:08 -08002884 void setLocalDragState(Object obj) {
2885 mLocalDragState = obj;
2886 }
2887
Christopher Tatea53146c2010-09-07 11:57:52 -07002888 private void handleDragEvent(DragEvent event) {
2889 // From the root, only drag start/end/location are dispatched. entered/exited
2890 // are determined and dispatched by the viewgroup hierarchy, who then report
2891 // that back here for ultimate reporting back to the framework.
2892 if (mView != null && mAdded) {
2893 final int what = event.mAction;
2894
2895 if (what == DragEvent.ACTION_DRAG_EXITED) {
2896 // A direct EXITED event means that the window manager knows we've just crossed
2897 // a window boundary, so the current drag target within this one must have
2898 // just been exited. Send it the usual notifications and then we're done
2899 // for now.
Chris Tate9d1ab882010-11-02 15:55:39 -07002900 mView.dispatchDragEvent(event);
Christopher Tatea53146c2010-09-07 11:57:52 -07002901 } else {
2902 // Cache the drag description when the operation starts, then fill it in
2903 // on subsequent calls as a convenience
2904 if (what == DragEvent.ACTION_DRAG_STARTED) {
Chris Tate9d1ab882010-11-02 15:55:39 -07002905 mCurrentDragView = null; // Start the current-recipient tracking
Christopher Tatea53146c2010-09-07 11:57:52 -07002906 mDragDescription = event.mClipDescription;
2907 } else {
2908 event.mClipDescription = mDragDescription;
2909 }
2910
2911 // For events with a [screen] location, translate into window coordinates
2912 if ((what == DragEvent.ACTION_DRAG_LOCATION) || (what == DragEvent.ACTION_DROP)) {
2913 mDragPoint.set(event.mX, event.mY);
2914 if (mTranslator != null) {
2915 mTranslator.translatePointInScreenToAppWindow(mDragPoint);
2916 }
2917
2918 if (mCurScrollY != 0) {
2919 mDragPoint.offset(0, mCurScrollY);
2920 }
2921
2922 event.mX = mDragPoint.x;
2923 event.mY = mDragPoint.y;
2924 }
2925
2926 // Remember who the current drag target is pre-dispatch
2927 final View prevDragView = mCurrentDragView;
2928
2929 // Now dispatch the drag/drop event
Chris Tated4533f12010-10-19 15:15:08 -07002930 boolean result = mView.dispatchDragEvent(event);
Christopher Tatea53146c2010-09-07 11:57:52 -07002931
2932 // If we changed apparent drag target, tell the OS about it
2933 if (prevDragView != mCurrentDragView) {
2934 try {
2935 if (prevDragView != null) {
2936 sWindowSession.dragRecipientExited(mWindow);
2937 }
2938 if (mCurrentDragView != null) {
2939 sWindowSession.dragRecipientEntered(mWindow);
2940 }
2941 } catch (RemoteException e) {
2942 Slog.e(TAG, "Unable to note drag target change");
2943 }
Christopher Tatea53146c2010-09-07 11:57:52 -07002944 }
Chris Tated4533f12010-10-19 15:15:08 -07002945
Christopher Tate407b4e92010-11-30 17:14:08 -08002946 // Report the drop result when we're done
Chris Tated4533f12010-10-19 15:15:08 -07002947 if (what == DragEvent.ACTION_DROP) {
Christopher Tate1fc014f2011-01-19 12:56:26 -08002948 mDragDescription = null;
Chris Tated4533f12010-10-19 15:15:08 -07002949 try {
2950 Log.i(TAG, "Reporting drop result: " + result);
2951 sWindowSession.reportDropResult(mWindow, result);
2952 } catch (RemoteException e) {
2953 Log.e(TAG, "Unable to report drop result");
2954 }
2955 }
Christopher Tate407b4e92010-11-30 17:14:08 -08002956
2957 // When the drag operation ends, release any local state object
2958 // that may have been in use
2959 if (what == DragEvent.ACTION_DRAG_ENDED) {
2960 setLocalDragState(null);
2961 }
Christopher Tatea53146c2010-09-07 11:57:52 -07002962 }
2963 }
2964 event.recycle();
2965 }
2966
Joe Onorato664644d2011-01-23 17:53:23 -08002967 public void handleDispatchSystemUiVisibilityChanged(int visibility) {
2968 if (mView == null) return;
Joe Onorato14782f72011-01-25 19:53:17 -08002969 if (mAttachInfo != null) {
2970 mAttachInfo.mSystemUiVisibility = visibility;
2971 }
Joe Onorato664644d2011-01-23 17:53:23 -08002972 mView.dispatchSystemUiVisibilityChanged(visibility);
2973 }
2974
Christopher Tate2c095f32010-10-04 14:13:40 -07002975 public void getLastTouchPoint(Point outLocation) {
2976 outLocation.x = (int) mLastTouchPoint.x;
2977 outLocation.y = (int) mLastTouchPoint.y;
2978 }
2979
Chris Tate9d1ab882010-11-02 15:55:39 -07002980 public void setDragFocus(View newDragTarget) {
Christopher Tatea53146c2010-09-07 11:57:52 -07002981 if (mCurrentDragView != newDragTarget) {
Chris Tate048691c2010-10-12 17:39:18 -07002982 mCurrentDragView = newDragTarget;
Christopher Tatea53146c2010-09-07 11:57:52 -07002983 }
Christopher Tatea53146c2010-09-07 11:57:52 -07002984 }
2985
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002986 private AudioManager getAudioManager() {
2987 if (mView == null) {
2988 throw new IllegalStateException("getAudioManager called when there is no mView");
2989 }
2990 if (mAudioManager == null) {
2991 mAudioManager = (AudioManager) mView.getContext().getSystemService(Context.AUDIO_SERVICE);
2992 }
2993 return mAudioManager;
2994 }
2995
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002996 private int relayoutWindow(WindowManager.LayoutParams params, int viewVisibility,
2997 boolean insetsPending) throws RemoteException {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002998
2999 float appScale = mAttachInfo.mApplicationScale;
Mitsuru Oshima3d914922009-05-13 22:29:15 -07003000 boolean restore = false;
Mitsuru Oshima64f59342009-06-21 00:03:11 -07003001 if (params != null && mTranslator != null) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07003002 restore = true;
3003 params.backup();
Mitsuru Oshima64f59342009-06-21 00:03:11 -07003004 mTranslator.translateWindowLayout(params);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07003005 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07003006 if (params != null) {
3007 if (DBG) Log.d(TAG, "WindowLayout in layoutWindow:" + params);
Mitsuru Oshima3d914922009-05-13 22:29:15 -07003008 }
Dianne Hackborn694f79b2010-03-17 19:44:59 -07003009 mPendingConfiguration.seq = 0;
Dianne Hackbornf123e492010-09-24 11:16:23 -07003010 //Log.d(TAG, ">>>>>> CALLING relayout");
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07003011 int relayoutResult = sWindowSession.relayout(
3012 mWindow, params,
Dianne Hackborn189ee182010-12-02 21:48:53 -08003013 (int) (mView.getMeasuredWidth() * appScale + 0.5f),
3014 (int) (mView.getMeasuredHeight() * appScale + 0.5f),
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07003015 viewVisibility, insetsPending, mWinFrame,
Dianne Hackborn694f79b2010-03-17 19:44:59 -07003016 mPendingContentInsets, mPendingVisibleInsets,
3017 mPendingConfiguration, mSurface);
Dianne Hackbornf123e492010-09-24 11:16:23 -07003018 //Log.d(TAG, "<<<<<< BACK FROM relayout");
Mitsuru Oshima3d914922009-05-13 22:29:15 -07003019 if (restore) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07003020 params.restore();
Mitsuru Oshima3d914922009-05-13 22:29:15 -07003021 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07003022
3023 if (mTranslator != null) {
3024 mTranslator.translateRectInScreenToAppWinFrame(mWinFrame);
3025 mTranslator.translateRectInScreenToAppWindow(mPendingContentInsets);
3026 mTranslator.translateRectInScreenToAppWindow(mPendingVisibleInsets);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07003027 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07003028 return relayoutResult;
3029 }
Romain Guy8506ab42009-06-11 17:35:47 -07003030
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07003031 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003032 * {@inheritDoc}
3033 */
3034 public void playSoundEffect(int effectId) {
3035 checkThread();
3036
Jean-Michel Trivi13b18fd2010-05-05 09:18:15 -07003037 try {
3038 final AudioManager audioManager = getAudioManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003039
Jean-Michel Trivi13b18fd2010-05-05 09:18:15 -07003040 switch (effectId) {
3041 case SoundEffectConstants.CLICK:
3042 audioManager.playSoundEffect(AudioManager.FX_KEY_CLICK);
3043 return;
3044 case SoundEffectConstants.NAVIGATION_DOWN:
3045 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_DOWN);
3046 return;
3047 case SoundEffectConstants.NAVIGATION_LEFT:
3048 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_LEFT);
3049 return;
3050 case SoundEffectConstants.NAVIGATION_RIGHT:
3051 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_RIGHT);
3052 return;
3053 case SoundEffectConstants.NAVIGATION_UP:
3054 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_UP);
3055 return;
3056 default:
3057 throw new IllegalArgumentException("unknown effect id " + effectId +
3058 " not defined in " + SoundEffectConstants.class.getCanonicalName());
3059 }
3060 } catch (IllegalStateException e) {
3061 // Exception thrown by getAudioManager() when mView is null
3062 Log.e(TAG, "FATAL EXCEPTION when attempting to play sound effect: " + e);
3063 e.printStackTrace();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003064 }
3065 }
3066
3067 /**
3068 * {@inheritDoc}
3069 */
3070 public boolean performHapticFeedback(int effectId, boolean always) {
3071 try {
3072 return sWindowSession.performHapticFeedback(mWindow, effectId, always);
3073 } catch (RemoteException e) {
3074 return false;
3075 }
3076 }
3077
3078 /**
3079 * {@inheritDoc}
3080 */
3081 public View focusSearch(View focused, int direction) {
3082 checkThread();
3083 if (!(mView instanceof ViewGroup)) {
3084 return null;
3085 }
3086 return FocusFinder.getInstance().findNextFocus((ViewGroup) mView, focused, direction);
3087 }
3088
3089 public void debug() {
3090 mView.debug();
3091 }
3092
3093 public void die(boolean immediate) {
Dianne Hackborn94d69142009-09-28 22:14:42 -07003094 if (immediate) {
3095 doDie();
3096 } else {
3097 sendEmptyMessage(DIE);
3098 }
3099 }
3100
3101 void doDie() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003102 checkThread();
Jeff Brownb75fa302010-07-15 23:47:29 -07003103 if (LOCAL_LOGV) Log.v(TAG, "DIE in " + this + " of " + mSurface);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003104 synchronized (this) {
3105 if (mAdded && !mFirst) {
Romain Guy29d89972010-09-22 16:10:57 -07003106 destroyHardwareRenderer();
3107
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003108 int viewVisibility = mView.getVisibility();
3109 boolean viewVisibilityChanged = mViewVisibility != viewVisibility;
3110 if (mWindowAttributesChanged || viewVisibilityChanged) {
3111 // If layout params have been changed, first give them
3112 // to the window manager to make sure it has the correct
3113 // animation info.
3114 try {
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07003115 if ((relayoutWindow(mWindowAttributes, viewVisibility, false)
3116 & WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003117 sWindowSession.finishDrawing(mWindow);
3118 }
3119 } catch (RemoteException e) {
3120 }
3121 }
3122
Dianne Hackborn0586a1b2009-09-06 21:08:27 -07003123 mSurface.release();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003124 }
3125 if (mAdded) {
3126 mAdded = false;
Dianne Hackborn94d69142009-09-28 22:14:42 -07003127 dispatchDetachedFromWindow();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003128 }
3129 }
3130 }
3131
Romain Guy29d89972010-09-22 16:10:57 -07003132 private void destroyHardwareRenderer() {
Romain Guyb051e892010-09-28 19:09:36 -07003133 if (mAttachInfo.mHardwareRenderer != null) {
3134 mAttachInfo.mHardwareRenderer.destroy(true);
3135 mAttachInfo.mHardwareRenderer = null;
Romain Guy29d89972010-09-22 16:10:57 -07003136 mAttachInfo.mHardwareAccelerated = false;
3137 }
3138 }
3139
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003140 public void dispatchFinishedEvent(int seq, boolean handled) {
3141 Message msg = obtainMessage(FINISHED_EVENT);
3142 msg.arg1 = seq;
3143 msg.arg2 = handled ? 1 : 0;
3144 sendMessage(msg);
3145 }
Mitsuru Oshima3d914922009-05-13 22:29:15 -07003146
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003147 public void dispatchResized(int w, int h, Rect coveredInsets,
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003148 Rect visibleInsets, boolean reportDraw, Configuration newConfig) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003149 if (DEBUG_LAYOUT) Log.v(TAG, "Resizing " + this + ": w=" + w
3150 + " h=" + h + " coveredInsets=" + coveredInsets.toShortString()
3151 + " visibleInsets=" + visibleInsets.toShortString()
3152 + " reportDraw=" + reportDraw);
3153 Message msg = obtainMessage(reportDraw ? RESIZED_REPORT :RESIZED);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07003154 if (mTranslator != null) {
3155 mTranslator.translateRectInScreenToAppWindow(coveredInsets);
3156 mTranslator.translateRectInScreenToAppWindow(visibleInsets);
3157 w *= mTranslator.applicationInvertedScale;
3158 h *= mTranslator.applicationInvertedScale;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07003159 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07003160 msg.arg1 = w;
3161 msg.arg2 = h;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003162 ResizedInfo ri = new ResizedInfo();
3163 ri.coveredInsets = new Rect(coveredInsets);
3164 ri.visibleInsets = new Rect(visibleInsets);
3165 ri.newConfig = newConfig;
3166 msg.obj = ri;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003167 sendMessage(msg);
3168 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07003169
Jeff Brown3915bb82010-11-05 15:02:16 -07003170 private InputQueue.FinishedCallback mFinishedCallback;
Jeff Brown46b9ac02010-04-22 18:58:52 -07003171
3172 private final InputHandler mInputHandler = new InputHandler() {
Jeff Brown3915bb82010-11-05 15:02:16 -07003173 public void handleKey(KeyEvent event, InputQueue.FinishedCallback finishedCallback) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07003174 startInputEvent(finishedCallback);
Jeff Brown92ff1dd2010-08-11 16:16:06 -07003175 dispatchKey(event, true);
Jeff Brown46b9ac02010-04-22 18:58:52 -07003176 }
3177
Jeff Brown3915bb82010-11-05 15:02:16 -07003178 public void handleMotion(MotionEvent event, InputQueue.FinishedCallback finishedCallback) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07003179 startInputEvent(finishedCallback);
3180 dispatchMotion(event, true);
Jeff Brown46b9ac02010-04-22 18:58:52 -07003181 }
3182 };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003183
3184 public void dispatchKey(KeyEvent event) {
Jeff Brown92ff1dd2010-08-11 16:16:06 -07003185 dispatchKey(event, false);
3186 }
3187
3188 private void dispatchKey(KeyEvent event, boolean sendDone) {
3189 //noinspection ConstantConditions
3190 if (false && event.getAction() == KeyEvent.ACTION_DOWN) {
3191 if (event.getKeyCode() == KeyEvent.KEYCODE_CAMERA) {
Romain Guy812ccbe2010-06-01 14:07:24 -07003192 if (DBG) Log.d("keydisp", "===================================================");
3193 if (DBG) Log.d("keydisp", "Focused view Hierarchy is:");
3194
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003195 debug();
3196
Romain Guy812ccbe2010-06-01 14:07:24 -07003197 if (DBG) Log.d("keydisp", "===================================================");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003198 }
3199 }
3200
3201 Message msg = obtainMessage(DISPATCH_KEY);
3202 msg.obj = event;
Jeff Brown92ff1dd2010-08-11 16:16:06 -07003203 msg.arg1 = sendDone ? 1 : 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003204
3205 if (LOCAL_LOGV) Log.v(
Jeff Brownc5ed5912010-07-14 18:48:53 -07003206 TAG, "sending key " + event + " to " + mView);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003207
3208 sendMessageAtTime(msg, event.getEventTime());
3209 }
Jeff Brownc5ed5912010-07-14 18:48:53 -07003210
3211 public void dispatchMotion(MotionEvent event) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07003212 dispatchMotion(event, false);
3213 }
3214
3215 private void dispatchMotion(MotionEvent event, boolean sendDone) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07003216 int source = event.getSource();
3217 if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07003218 dispatchPointer(event, sendDone);
Jeff Brownc5ed5912010-07-14 18:48:53 -07003219 } else if ((source & InputDevice.SOURCE_CLASS_TRACKBALL) != 0) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07003220 dispatchTrackball(event, sendDone);
Jeff Brownc5ed5912010-07-14 18:48:53 -07003221 } else {
Jeff Browncb1404e2011-01-15 18:14:15 -08003222 dispatchGenericMotion(event, sendDone);
Jeff Brownc5ed5912010-07-14 18:48:53 -07003223 }
3224 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003225
Jeff Brown00fa7bd2010-07-02 15:37:36 -07003226 public void dispatchPointer(MotionEvent event) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07003227 dispatchPointer(event, false);
3228 }
3229
3230 private void dispatchPointer(MotionEvent event, boolean sendDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003231 Message msg = obtainMessage(DISPATCH_POINTER);
3232 msg.obj = event;
Jeff Brown93ed4e32010-09-23 13:51:48 -07003233 msg.arg1 = sendDone ? 1 : 0;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07003234 sendMessageAtTime(msg, event.getEventTime());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003235 }
3236
Jeff Brown00fa7bd2010-07-02 15:37:36 -07003237 public void dispatchTrackball(MotionEvent event) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07003238 dispatchTrackball(event, false);
3239 }
3240
3241 private void dispatchTrackball(MotionEvent event, boolean sendDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003242 Message msg = obtainMessage(DISPATCH_TRACKBALL);
3243 msg.obj = event;
Jeff Brown93ed4e32010-09-23 13:51:48 -07003244 msg.arg1 = sendDone ? 1 : 0;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07003245 sendMessageAtTime(msg, event.getEventTime());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003246 }
Jeff Browncb1404e2011-01-15 18:14:15 -08003247
3248 private void dispatchGenericMotion(MotionEvent event, boolean sendDone) {
3249 Message msg = obtainMessage(DISPATCH_GENERIC_MOTION);
3250 msg.obj = event;
3251 msg.arg1 = sendDone ? 1 : 0;
3252 sendMessageAtTime(msg, event.getEventTime());
3253 }
3254
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003255 public void dispatchAppVisibility(boolean visible) {
3256 Message msg = obtainMessage(DISPATCH_APP_VISIBILITY);
3257 msg.arg1 = visible ? 1 : 0;
3258 sendMessage(msg);
3259 }
3260
3261 public void dispatchGetNewSurface() {
3262 Message msg = obtainMessage(DISPATCH_GET_NEW_SURFACE);
3263 sendMessage(msg);
3264 }
3265
3266 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
3267 Message msg = Message.obtain();
3268 msg.what = WINDOW_FOCUS_CHANGED;
3269 msg.arg1 = hasFocus ? 1 : 0;
3270 msg.arg2 = inTouchMode ? 1 : 0;
3271 sendMessage(msg);
3272 }
3273
Dianne Hackbornffa42482009-09-23 22:20:11 -07003274 public void dispatchCloseSystemDialogs(String reason) {
3275 Message msg = Message.obtain();
3276 msg.what = CLOSE_SYSTEM_DIALOGS;
3277 msg.obj = reason;
3278 sendMessage(msg);
3279 }
Christopher Tatea53146c2010-09-07 11:57:52 -07003280
3281 public void dispatchDragEvent(DragEvent event) {
Chris Tate91e9bb32010-10-12 12:58:43 -07003282 final int what;
3283 if (event.getAction() == DragEvent.ACTION_DRAG_LOCATION) {
3284 what = DISPATCH_DRAG_LOCATION_EVENT;
3285 removeMessages(what);
3286 } else {
3287 what = DISPATCH_DRAG_EVENT;
3288 }
3289 Message msg = obtainMessage(what, event);
Christopher Tatea53146c2010-09-07 11:57:52 -07003290 sendMessage(msg);
3291 }
3292
Joe Onorato664644d2011-01-23 17:53:23 -08003293 public void dispatchSystemUiVisibilityChanged(int visibility) {
3294 sendMessage(obtainMessage(DISPATCH_SYSTEM_UI_VISIBILITY, visibility, 0));
3295 }
3296
svetoslavganov75986cf2009-05-14 22:28:01 -07003297 /**
3298 * The window is getting focus so if there is anything focused/selected
3299 * send an {@link AccessibilityEvent} to announce that.
3300 */
3301 private void sendAccessibilityEvents() {
3302 if (!AccessibilityManager.getInstance(mView.getContext()).isEnabled()) {
3303 return;
3304 }
3305 mView.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
3306 View focusedView = mView.findFocus();
3307 if (focusedView != null && focusedView != mView) {
3308 focusedView.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
3309 }
3310 }
3311
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003312 public boolean showContextMenuForChild(View originalView) {
3313 return false;
3314 }
3315
Adam Powell6e346362010-07-23 10:18:23 -07003316 public ActionMode startActionModeForChild(View originalView, ActionMode.Callback callback) {
3317 return null;
3318 }
3319
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003320 public void createContextMenu(ContextMenu menu) {
3321 }
3322
3323 public void childDrawableStateChanged(View child) {
3324 }
3325
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003326 void checkThread() {
3327 if (mThread != Thread.currentThread()) {
3328 throw new CalledFromWrongThreadException(
3329 "Only the original thread that created a view hierarchy can touch its views.");
3330 }
3331 }
3332
3333 public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
3334 // ViewRoot never intercepts touch event, so this can be a no-op
3335 }
3336
3337 public boolean requestChildRectangleOnScreen(View child, Rect rectangle,
3338 boolean immediate) {
3339 return scrollToRectOrFocus(rectangle, immediate);
3340 }
Romain Guy8506ab42009-06-11 17:35:47 -07003341
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07003342 class TakenSurfaceHolder extends BaseSurfaceHolder {
3343 @Override
3344 public boolean onAllowLockCanvas() {
3345 return mDrawingAllowed;
3346 }
3347
3348 @Override
3349 public void onRelayoutContainer() {
3350 // Not currently interesting -- from changing between fixed and layout size.
3351 }
3352
3353 public void setFormat(int format) {
3354 ((RootViewSurfaceTaker)mView).setSurfaceFormat(format);
3355 }
3356
3357 public void setType(int type) {
3358 ((RootViewSurfaceTaker)mView).setSurfaceType(type);
3359 }
3360
3361 @Override
3362 public void onUpdateSurface() {
3363 // We take care of format and type changes on our own.
3364 throw new IllegalStateException("Shouldn't be here");
3365 }
3366
3367 public boolean isCreating() {
3368 return mIsCreating;
3369 }
3370
3371 @Override
3372 public void setFixedSize(int width, int height) {
3373 throw new UnsupportedOperationException(
3374 "Currently only support sizing from layout");
3375 }
3376
3377 public void setKeepScreenOn(boolean screenOn) {
3378 ((RootViewSurfaceTaker)mView).setSurfaceKeepScreenOn(screenOn);
3379 }
3380 }
3381
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003382 static class InputMethodCallback extends IInputMethodCallback.Stub {
3383 private WeakReference<ViewRoot> mViewRoot;
3384
3385 public InputMethodCallback(ViewRoot viewRoot) {
3386 mViewRoot = new WeakReference<ViewRoot>(viewRoot);
3387 }
Romain Guy8506ab42009-06-11 17:35:47 -07003388
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003389 public void finishedEvent(int seq, boolean handled) {
3390 final ViewRoot viewRoot = mViewRoot.get();
3391 if (viewRoot != null) {
3392 viewRoot.dispatchFinishedEvent(seq, handled);
3393 }
3394 }
3395
3396 public void sessionCreated(IInputMethodSession session) throws RemoteException {
3397 // Stub -- not for use in the client.
3398 }
3399 }
Romain Guy8506ab42009-06-11 17:35:47 -07003400
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003401 static class W extends IWindow.Stub {
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07003402 private final WeakReference<ViewRoot> mViewRoot;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003403
Romain Guyfb8b7632010-08-23 21:05:08 -07003404 W(ViewRoot viewRoot) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003405 mViewRoot = new WeakReference<ViewRoot>(viewRoot);
3406 }
3407
Romain Guyfb8b7632010-08-23 21:05:08 -07003408 public void resized(int w, int h, Rect coveredInsets, Rect visibleInsets,
3409 boolean reportDraw, Configuration newConfig) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003410 final ViewRoot viewRoot = mViewRoot.get();
3411 if (viewRoot != null) {
Romain Guyfb8b7632010-08-23 21:05:08 -07003412 viewRoot.dispatchResized(w, h, coveredInsets, visibleInsets, reportDraw, newConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003413 }
3414 }
3415
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003416 public void dispatchAppVisibility(boolean visible) {
3417 final ViewRoot viewRoot = mViewRoot.get();
3418 if (viewRoot != null) {
3419 viewRoot.dispatchAppVisibility(visible);
3420 }
3421 }
3422
3423 public void dispatchGetNewSurface() {
3424 final ViewRoot viewRoot = mViewRoot.get();
3425 if (viewRoot != null) {
3426 viewRoot.dispatchGetNewSurface();
3427 }
3428 }
3429
3430 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
3431 final ViewRoot viewRoot = mViewRoot.get();
3432 if (viewRoot != null) {
3433 viewRoot.windowFocusChanged(hasFocus, inTouchMode);
3434 }
3435 }
3436
3437 private static int checkCallingPermission(String permission) {
3438 if (!Process.supportsProcesses()) {
3439 return PackageManager.PERMISSION_GRANTED;
3440 }
3441
3442 try {
3443 return ActivityManagerNative.getDefault().checkPermission(
3444 permission, Binder.getCallingPid(), Binder.getCallingUid());
3445 } catch (RemoteException e) {
3446 return PackageManager.PERMISSION_DENIED;
3447 }
3448 }
3449
3450 public void executeCommand(String command, String parameters, ParcelFileDescriptor out) {
3451 final ViewRoot viewRoot = mViewRoot.get();
3452 if (viewRoot != null) {
3453 final View view = viewRoot.mView;
3454 if (view != null) {
3455 if (checkCallingPermission(Manifest.permission.DUMP) !=
3456 PackageManager.PERMISSION_GRANTED) {
3457 throw new SecurityException("Insufficient permissions to invoke"
3458 + " executeCommand() from pid=" + Binder.getCallingPid()
3459 + ", uid=" + Binder.getCallingUid());
3460 }
3461
3462 OutputStream clientStream = null;
3463 try {
3464 clientStream = new ParcelFileDescriptor.AutoCloseOutputStream(out);
3465 ViewDebug.dispatchCommand(view, command, parameters, clientStream);
3466 } catch (IOException e) {
3467 e.printStackTrace();
3468 } finally {
3469 if (clientStream != null) {
3470 try {
3471 clientStream.close();
3472 } catch (IOException e) {
3473 e.printStackTrace();
3474 }
3475 }
3476 }
3477 }
3478 }
3479 }
Dianne Hackborn72c82ab2009-08-11 21:13:54 -07003480
Dianne Hackbornffa42482009-09-23 22:20:11 -07003481 public void closeSystemDialogs(String reason) {
3482 final ViewRoot viewRoot = mViewRoot.get();
3483 if (viewRoot != null) {
3484 viewRoot.dispatchCloseSystemDialogs(reason);
3485 }
3486 }
3487
Marco Nelissenbf6956b2009-11-09 15:21:13 -08003488 public void dispatchWallpaperOffsets(float x, float y, float xStep, float yStep,
3489 boolean sync) {
Dianne Hackborn19382ac2009-09-11 21:13:37 -07003490 if (sync) {
3491 try {
3492 sWindowSession.wallpaperOffsetsComplete(asBinder());
3493 } catch (RemoteException e) {
3494 }
3495 }
Dianne Hackborn72c82ab2009-08-11 21:13:54 -07003496 }
Dianne Hackborn75804932009-10-20 20:15:20 -07003497
3498 public void dispatchWallpaperCommand(String action, int x, int y,
3499 int z, Bundle extras, boolean sync) {
3500 if (sync) {
3501 try {
3502 sWindowSession.wallpaperCommandComplete(asBinder(), null);
3503 } catch (RemoteException e) {
3504 }
3505 }
3506 }
Christopher Tatea53146c2010-09-07 11:57:52 -07003507
3508 /* Drag/drop */
3509 public void dispatchDragEvent(DragEvent event) {
3510 final ViewRoot viewRoot = mViewRoot.get();
3511 if (viewRoot != null) {
3512 viewRoot.dispatchDragEvent(event);
3513 }
3514 }
Joe Onorato664644d2011-01-23 17:53:23 -08003515
3516 @Override
3517 public void dispatchSystemUiVisibilityChanged(int visibility) {
3518 final ViewRoot viewRoot = mViewRoot.get();
3519 if (viewRoot != null) {
3520 viewRoot.dispatchSystemUiVisibilityChanged(visibility);
3521 }
3522 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003523 }
3524
3525 /**
3526 * Maintains state information for a single trackball axis, generating
3527 * discrete (DPAD) movements based on raw trackball motion.
3528 */
3529 static final class TrackballAxis {
3530 /**
3531 * The maximum amount of acceleration we will apply.
3532 */
3533 static final float MAX_ACCELERATION = 20;
Romain Guy8506ab42009-06-11 17:35:47 -07003534
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003535 /**
3536 * The maximum amount of time (in milliseconds) between events in order
3537 * for us to consider the user to be doing fast trackball movements,
3538 * and thus apply an acceleration.
3539 */
3540 static final long FAST_MOVE_TIME = 150;
Romain Guy8506ab42009-06-11 17:35:47 -07003541
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003542 /**
3543 * Scaling factor to the time (in milliseconds) between events to how
3544 * much to multiple/divide the current acceleration. When movement
3545 * is < FAST_MOVE_TIME this multiplies the acceleration; when >
3546 * FAST_MOVE_TIME it divides it.
3547 */
3548 static final float ACCEL_MOVE_SCALING_FACTOR = (1.0f/40);
Romain Guy8506ab42009-06-11 17:35:47 -07003549
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003550 float position;
3551 float absPosition;
3552 float acceleration = 1;
3553 long lastMoveTime = 0;
3554 int step;
3555 int dir;
3556 int nonAccelMovement;
3557
3558 void reset(int _step) {
3559 position = 0;
3560 acceleration = 1;
3561 lastMoveTime = 0;
3562 step = _step;
3563 dir = 0;
3564 }
3565
3566 /**
3567 * Add trackball movement into the state. If the direction of movement
3568 * has been reversed, the state is reset before adding the
3569 * movement (so that you don't have to compensate for any previously
3570 * collected movement before see the result of the movement in the
3571 * new direction).
3572 *
3573 * @return Returns the absolute value of the amount of movement
3574 * collected so far.
3575 */
3576 float collect(float off, long time, String axis) {
3577 long normTime;
3578 if (off > 0) {
3579 normTime = (long)(off * FAST_MOVE_TIME);
3580 if (dir < 0) {
3581 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to positive!");
3582 position = 0;
3583 step = 0;
3584 acceleration = 1;
3585 lastMoveTime = 0;
3586 }
3587 dir = 1;
3588 } else if (off < 0) {
3589 normTime = (long)((-off) * FAST_MOVE_TIME);
3590 if (dir > 0) {
3591 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to negative!");
3592 position = 0;
3593 step = 0;
3594 acceleration = 1;
3595 lastMoveTime = 0;
3596 }
3597 dir = -1;
3598 } else {
3599 normTime = 0;
3600 }
Romain Guy8506ab42009-06-11 17:35:47 -07003601
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003602 // The number of milliseconds between each movement that is
3603 // considered "normal" and will not result in any acceleration
3604 // or deceleration, scaled by the offset we have here.
3605 if (normTime > 0) {
3606 long delta = time - lastMoveTime;
3607 lastMoveTime = time;
3608 float acc = acceleration;
3609 if (delta < normTime) {
3610 // The user is scrolling rapidly, so increase acceleration.
3611 float scale = (normTime-delta) * ACCEL_MOVE_SCALING_FACTOR;
3612 if (scale > 1) acc *= scale;
3613 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " accelerate: off="
3614 + off + " normTime=" + normTime + " delta=" + delta
3615 + " scale=" + scale + " acc=" + acc);
3616 acceleration = acc < MAX_ACCELERATION ? acc : MAX_ACCELERATION;
3617 } else {
3618 // The user is scrolling slowly, so decrease acceleration.
3619 float scale = (delta-normTime) * ACCEL_MOVE_SCALING_FACTOR;
3620 if (scale > 1) acc /= scale;
3621 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " deccelerate: off="
3622 + off + " normTime=" + normTime + " delta=" + delta
3623 + " scale=" + scale + " acc=" + acc);
3624 acceleration = acc > 1 ? acc : 1;
3625 }
3626 }
3627 position += off;
3628 return (absPosition = Math.abs(position));
3629 }
3630
3631 /**
3632 * Generate the number of discrete movement events appropriate for
3633 * the currently collected trackball movement.
3634 *
3635 * @param precision The minimum movement required to generate the
3636 * first discrete movement.
3637 *
3638 * @return Returns the number of discrete movements, either positive
3639 * or negative, or 0 if there is not enough trackball movement yet
3640 * for a discrete movement.
3641 */
3642 int generate(float precision) {
3643 int movement = 0;
3644 nonAccelMovement = 0;
3645 do {
3646 final int dir = position >= 0 ? 1 : -1;
3647 switch (step) {
3648 // If we are going to execute the first step, then we want
3649 // to do this as soon as possible instead of waiting for
3650 // a full movement, in order to make things look responsive.
3651 case 0:
3652 if (absPosition < precision) {
3653 return movement;
3654 }
3655 movement += dir;
3656 nonAccelMovement += dir;
3657 step = 1;
3658 break;
3659 // If we have generated the first movement, then we need
3660 // to wait for the second complete trackball motion before
3661 // generating the second discrete movement.
3662 case 1:
3663 if (absPosition < 2) {
3664 return movement;
3665 }
3666 movement += dir;
3667 nonAccelMovement += dir;
3668 position += dir > 0 ? -2 : 2;
3669 absPosition = Math.abs(position);
3670 step = 2;
3671 break;
3672 // After the first two, we generate discrete movements
3673 // consistently with the trackball, applying an acceleration
3674 // if the trackball is moving quickly. This is a simple
3675 // acceleration on top of what we already compute based
3676 // on how quickly the wheel is being turned, to apply
3677 // a longer increasing acceleration to continuous movement
3678 // in one direction.
3679 default:
3680 if (absPosition < 1) {
3681 return movement;
3682 }
3683 movement += dir;
3684 position += dir >= 0 ? -1 : 1;
3685 absPosition = Math.abs(position);
3686 float acc = acceleration;
3687 acc *= 1.1f;
3688 acceleration = acc < MAX_ACCELERATION ? acc : acceleration;
3689 break;
3690 }
3691 } while (true);
3692 }
3693 }
3694
3695 public static final class CalledFromWrongThreadException extends AndroidRuntimeException {
3696 public CalledFromWrongThreadException(String msg) {
3697 super(msg);
3698 }
3699 }
3700
3701 private SurfaceHolder mHolder = new SurfaceHolder() {
3702 // we only need a SurfaceHolder for opengl. it would be nice
3703 // to implement everything else though, especially the callback
3704 // support (opengl doesn't make use of it right now, but eventually
3705 // will).
3706 public Surface getSurface() {
3707 return mSurface;
3708 }
3709
3710 public boolean isCreating() {
3711 return false;
3712 }
3713
3714 public void addCallback(Callback callback) {
3715 }
3716
3717 public void removeCallback(Callback callback) {
3718 }
3719
3720 public void setFixedSize(int width, int height) {
3721 }
3722
3723 public void setSizeFromLayout() {
3724 }
3725
3726 public void setFormat(int format) {
3727 }
3728
3729 public void setType(int type) {
3730 }
3731
3732 public void setKeepScreenOn(boolean screenOn) {
3733 }
3734
3735 public Canvas lockCanvas() {
3736 return null;
3737 }
3738
3739 public Canvas lockCanvas(Rect dirty) {
3740 return null;
3741 }
3742
3743 public void unlockCanvasAndPost(Canvas canvas) {
3744 }
3745 public Rect getSurfaceFrame() {
3746 return null;
3747 }
3748 };
3749
3750 static RunQueue getRunQueue() {
3751 RunQueue rq = sRunQueues.get();
3752 if (rq != null) {
3753 return rq;
3754 }
3755 rq = new RunQueue();
3756 sRunQueues.set(rq);
3757 return rq;
3758 }
Romain Guy8506ab42009-06-11 17:35:47 -07003759
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003760 /**
3761 * @hide
3762 */
3763 static final class RunQueue {
3764 private final ArrayList<HandlerAction> mActions = new ArrayList<HandlerAction>();
3765
3766 void post(Runnable action) {
3767 postDelayed(action, 0);
3768 }
3769
3770 void postDelayed(Runnable action, long delayMillis) {
3771 HandlerAction handlerAction = new HandlerAction();
3772 handlerAction.action = action;
3773 handlerAction.delay = delayMillis;
3774
3775 synchronized (mActions) {
3776 mActions.add(handlerAction);
3777 }
3778 }
3779
3780 void removeCallbacks(Runnable action) {
3781 final HandlerAction handlerAction = new HandlerAction();
3782 handlerAction.action = action;
3783
3784 synchronized (mActions) {
3785 final ArrayList<HandlerAction> actions = mActions;
3786
3787 while (actions.remove(handlerAction)) {
3788 // Keep going
3789 }
3790 }
3791 }
3792
3793 void executeActions(Handler handler) {
3794 synchronized (mActions) {
3795 final ArrayList<HandlerAction> actions = mActions;
3796 final int count = actions.size();
3797
3798 for (int i = 0; i < count; i++) {
3799 final HandlerAction handlerAction = actions.get(i);
3800 handler.postDelayed(handlerAction.action, handlerAction.delay);
3801 }
3802
Romain Guy15df6702009-08-17 20:17:30 -07003803 actions.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003804 }
3805 }
3806
3807 private static class HandlerAction {
3808 Runnable action;
3809 long delay;
3810
3811 @Override
3812 public boolean equals(Object o) {
3813 if (this == o) return true;
3814 if (o == null || getClass() != o.getClass()) return false;
3815
3816 HandlerAction that = (HandlerAction) o;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003817 return !(action != null ? !action.equals(that.action) : that.action != null);
3818
3819 }
3820
3821 @Override
3822 public int hashCode() {
3823 int result = action != null ? action.hashCode() : 0;
3824 result = 31 * result + (int) (delay ^ (delay >>> 32));
3825 return result;
3826 }
3827 }
3828 }
3829
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003830 private static native void nativeShowFPS(Canvas canvas, int durationMillis);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003831}