blob: 6bc5e8a9289ef3969e1736a8a8daecf086197baa [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;
168 Rect mDirty; // will be a graphics.Region soon
Romain Guybb93d552009-03-24 21:04:15 -0700169 boolean mIsAnimating;
Romain Guy8506ab42009-06-11 17:35:47 -0700170
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700171 CompatibilityInfo.Translator mTranslator;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800172
173 final View.AttachInfo mAttachInfo;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700174 InputChannel mInputChannel;
Dianne Hackborn1e4b9f32010-06-23 14:10:57 -0700175 InputQueue.Callback mInputQueueCallback;
176 InputQueue mInputQueue;
Joe Onorato86f67862010-11-05 18:57:34 -0700177 FallbackEventHandler mFallbackEventHandler;
Dianne Hackborna95e4cb2010-06-18 18:09:33 -0700178
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800179 final Rect mTempRect; // used in the transaction to not thrash the heap.
180 final Rect mVisRect; // used to retrieve visible rect of focused view.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800181
182 boolean mTraversalScheduled;
183 boolean mWillDrawSoon;
184 boolean mLayoutRequested;
185 boolean mFirst;
186 boolean mReportNextDraw;
187 boolean mFullRedrawNeeded;
188 boolean mNewSurfaceNeeded;
189 boolean mHasHadWindowFocus;
190 boolean mLastWasImTarget;
191
192 boolean mWindowAttributesChanged = false;
193
194 // These can be accessed by any thread, must be protected with a lock.
Mathias Agopian5583dc62009-07-09 16:28:11 -0700195 // Surface can never be reassigned or cleared (use Surface.clear()).
196 private final Surface mSurface = new Surface();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800197
198 boolean mAdded;
199 boolean mAddedTouchMode;
200
201 /*package*/ int mAddNesting;
202
203 // These are accessed by multiple threads.
204 final Rect mWinFrame; // frame given by window manager.
205
206 final Rect mPendingVisibleInsets = new Rect();
207 final Rect mPendingContentInsets = new Rect();
208 final ViewTreeObserver.InternalInsetsInfo mLastGivenInsets
209 = new ViewTreeObserver.InternalInsetsInfo();
210
Dianne Hackborn694f79b2010-03-17 19:44:59 -0700211 final Configuration mLastConfiguration = new Configuration();
212 final Configuration mPendingConfiguration = new Configuration();
213
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800214 class ResizedInfo {
215 Rect coveredInsets;
216 Rect visibleInsets;
217 Configuration newConfig;
218 }
219
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800220 boolean mScrollMayChange;
221 int mSoftInputMode;
222 View mLastScrolledFocus;
223 int mScrollY;
224 int mCurScrollY;
225 Scroller mScroller;
Dianne Hackborn0f761d62010-11-30 22:06:10 -0800226 Bitmap mResizeBitmap;
227 long mResizeBitmapStartTime;
228 int mResizeBitmapDuration;
229 static final Interpolator mResizeInterpolator = new AccelerateDecelerateInterpolator();
Romain Guy8506ab42009-06-11 17:35:47 -0700230
Romain Guy8506ab42009-06-11 17:35:47 -0700231 final ViewConfiguration mViewConfiguration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800232
Christopher Tatea53146c2010-09-07 11:57:52 -0700233 /* Drag/drop */
234 ClipDescription mDragDescription;
235 View mCurrentDragView;
Christopher Tate7fb8b562011-01-20 13:46:41 -0800236 volatile Object mLocalDragState;
Christopher Tatea53146c2010-09-07 11:57:52 -0700237 final PointF mDragPoint = new PointF();
Christopher Tate2c095f32010-10-04 14:13:40 -0700238 final PointF mLastTouchPoint = new PointF();
Christopher Tatea53146c2010-09-07 11:57:52 -0700239
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800240 /**
241 * see {@link #playSoundEffect(int)}
242 */
243 AudioManager mAudioManager;
244
Dianne Hackborn11ea3342009-07-22 21:48:55 -0700245 private final int mDensity;
Adam Powellb08013c2010-09-16 16:28:11 -0700246
Dianne Hackborn4c62fc02009-08-08 20:40:27 -0700247 public static IWindowSession getWindowSession(Looper mainLooper) {
248 synchronized (mStaticInit) {
249 if (!mInitialized) {
250 try {
251 InputMethodManager imm = InputMethodManager.getInstance(mainLooper);
252 sWindowSession = IWindowManager.Stub.asInterface(
253 ServiceManager.getService("window"))
254 .openSession(imm.getClient(), imm.getInputContext());
255 mInitialized = true;
256 } catch (RemoteException e) {
257 }
258 }
259 return sWindowSession;
260 }
261 }
262
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800263 public ViewRoot(Context context) {
264 super();
265
Romain Guy812ccbe2010-06-01 14:07:24 -0700266 if (MEASURE_LATENCY) {
267 if (lt == null) {
268 lt = new LatencyTimer(100, 1000);
269 }
Michael Chan53071d62009-05-13 17:29:48 -0700270 }
271
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800272 // Initialize the statics when this class is first instantiated. This is
273 // done here instead of in the static block because Zygote does not
274 // allow the spawning of threads.
Dianne Hackborn4c62fc02009-08-08 20:40:27 -0700275 getWindowSession(context.getMainLooper());
276
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800277 mThread = Thread.currentThread();
278 mLocation = new WindowLeaked(null);
279 mLocation.fillInStackTrace();
280 mWidth = -1;
281 mHeight = -1;
282 mDirty = new Rect();
283 mTempRect = new Rect();
284 mVisRect = new Rect();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800285 mWinFrame = new Rect();
Romain Guyfb8b7632010-08-23 21:05:08 -0700286 mWindow = new W(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800287 mInputMethodCallback = new InputMethodCallback(this);
288 mViewVisibility = View.GONE;
289 mTransparentRegion = new Region();
290 mPreviousTransparentRegion = new Region();
291 mFirst = true; // true for the first time the view is added
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800292 mAdded = false;
293 mAttachInfo = new View.AttachInfo(sWindowSession, mWindow, this, this);
294 mViewConfiguration = ViewConfiguration.get(context);
Dianne Hackborn11ea3342009-07-22 21:48:55 -0700295 mDensity = context.getResources().getDisplayMetrics().densityDpi;
Joe Onorato86f67862010-11-05 18:57:34 -0700296 mFallbackEventHandler = PolicyManager.makeNewFallbackEventHandler(context);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800297 }
298
Dianne Hackborn2a9094d2010-02-03 19:20:09 -0800299 public static void addFirstDrawHandler(Runnable callback) {
300 synchronized (sFirstDrawHandlers) {
301 if (!sFirstDrawComplete) {
302 sFirstDrawHandlers.add(callback);
303 }
304 }
305 }
306
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800307 public static void addConfigCallback(ComponentCallbacks callback) {
308 synchronized (sConfigCallbacks) {
309 sConfigCallbacks.add(callback);
310 }
311 }
312
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800313 // FIXME for perf testing only
314 private boolean mProfile = false;
315
316 /**
317 * Call this to profile the next traversal call.
318 * FIXME for perf testing only. Remove eventually
319 */
320 public void profile() {
321 mProfile = true;
322 }
323
324 /**
325 * Indicates whether we are in touch mode. Calling this method triggers an IPC
326 * call and should be avoided whenever possible.
327 *
328 * @return True, if the device is in touch mode, false otherwise.
329 *
330 * @hide
331 */
332 static boolean isInTouchMode() {
333 if (mInitialized) {
334 try {
335 return sWindowSession.getInTouchMode();
336 } catch (RemoteException e) {
337 }
338 }
339 return false;
340 }
341
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800342 /**
343 * We have one child
344 */
Romain Guye4d01122010-06-16 18:44:05 -0700345 public void setView(View view, WindowManager.LayoutParams attrs, View panelParentView) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800346 synchronized (this) {
347 if (mView == null) {
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700348 mView = view;
Joe Onorato86f67862010-11-05 18:57:34 -0700349 mFallbackEventHandler.setView(view);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700350 mWindowAttributes.copyFrom(attrs);
Mitsuru Oshima1ecf5d22009-07-06 17:20:38 -0700351 attrs = mWindowAttributes;
Romain Guye4d01122010-06-16 18:44:05 -0700352
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700353 if (view instanceof RootViewSurfaceTaker) {
354 mSurfaceHolderCallback =
355 ((RootViewSurfaceTaker)view).willYouTakeTheSurface();
356 if (mSurfaceHolderCallback != null) {
357 mSurfaceHolder = new TakenSurfaceHolder();
Dianne Hackborn289b9b62010-07-09 11:44:11 -0700358 mSurfaceHolder.setFormat(PixelFormat.UNKNOWN);
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700359 }
360 }
Romain Guy1aec9a22011-01-05 09:37:12 -0800361
362 // If the application owns the surface, don't enable hardware acceleration
363 if (mSurfaceHolder == null) {
364 enableHardwareAcceleration(attrs);
365 }
366
Mitsuru Oshima38ed7d772009-07-21 14:39:34 -0700367 Resources resources = mView.getContext().getResources();
368 CompatibilityInfo compatibilityInfo = resources.getCompatibilityInfo();
Mitsuru Oshima589cebe2009-07-22 20:38:58 -0700369 mTranslator = compatibilityInfo.getTranslator();
Mitsuru Oshima38ed7d772009-07-21 14:39:34 -0700370
371 if (mTranslator != null || !compatibilityInfo.supportsScreen()) {
Mitsuru Oshima240f8a72009-07-22 20:39:14 -0700372 mSurface.setCompatibleDisplayMetrics(resources.getDisplayMetrics(),
373 mTranslator);
Mitsuru Oshima38ed7d772009-07-21 14:39:34 -0700374 }
375
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -0700376 boolean restore = false;
Romain Guy35b38ce2009-10-07 13:38:55 -0700377 if (mTranslator != null) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -0700378 restore = true;
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700379 attrs.backup();
380 mTranslator.translateWindowLayout(attrs);
Mitsuru Oshima3d914922009-05-13 22:29:15 -0700381 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700382 if (DEBUG_LAYOUT) Log.d(TAG, "WindowLayout in setView:" + attrs);
383
Mitsuru Oshima1ecf5d22009-07-06 17:20:38 -0700384 if (!compatibilityInfo.supportsScreen()) {
385 attrs.flags |= WindowManager.LayoutParams.FLAG_COMPATIBLE_WINDOW;
386 }
387
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800388 mSoftInputMode = attrs.softInputMode;
389 mWindowAttributesChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800390 mAttachInfo.mRootView = view;
Romain Guy35b38ce2009-10-07 13:38:55 -0700391 mAttachInfo.mScalingRequired = mTranslator != null;
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700392 mAttachInfo.mApplicationScale =
393 mTranslator == null ? 1.0f : mTranslator.applicationScale;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800394 if (panelParentView != null) {
395 mAttachInfo.mPanelParentWindowToken
396 = panelParentView.getApplicationWindowToken();
397 }
398 mAdded = true;
399 int res; /* = WindowManagerImpl.ADD_OKAY; */
Romain Guy8506ab42009-06-11 17:35:47 -0700400
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800401 // Schedule the first layout -before- adding to the window
402 // manager, to make sure we do the relayout before receiving
403 // any other events from the system.
404 requestLayout();
Jeff Brown46b9ac02010-04-22 18:58:52 -0700405 mInputChannel = new InputChannel();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800406 try {
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700407 res = sWindowSession.add(mWindow, mWindowAttributes,
Jeff Brown46b9ac02010-04-22 18:58:52 -0700408 getHostVisibility(), mAttachInfo.mContentInsets,
409 mInputChannel);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800410 } catch (RemoteException e) {
411 mAdded = false;
412 mView = null;
413 mAttachInfo.mRootView = null;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700414 mInputChannel = null;
Joe Onorato86f67862010-11-05 18:57:34 -0700415 mFallbackEventHandler.setView(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800416 unscheduleTraversals();
417 throw new RuntimeException("Adding window failed", e);
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700418 } finally {
419 if (restore) {
420 attrs.restore();
421 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800422 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700423
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700424 if (mTranslator != null) {
425 mTranslator.translateRectInScreenToAppWindow(mAttachInfo.mContentInsets);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700426 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800427 mPendingContentInsets.set(mAttachInfo.mContentInsets);
428 mPendingVisibleInsets.set(0, 0, 0, 0);
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800429 if (DEBUG_LAYOUT) Log.v(TAG, "Added window " + mWindow);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800430 if (res < WindowManagerImpl.ADD_OKAY) {
431 mView = null;
432 mAttachInfo.mRootView = null;
433 mAdded = false;
Joe Onorato86f67862010-11-05 18:57:34 -0700434 mFallbackEventHandler.setView(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800435 unscheduleTraversals();
436 switch (res) {
437 case WindowManagerImpl.ADD_BAD_APP_TOKEN:
438 case WindowManagerImpl.ADD_BAD_SUBWINDOW_TOKEN:
439 throw new WindowManagerImpl.BadTokenException(
440 "Unable to add window -- token " + attrs.token
441 + " is not valid; is your activity running?");
442 case WindowManagerImpl.ADD_NOT_APP_TOKEN:
443 throw new WindowManagerImpl.BadTokenException(
444 "Unable to add window -- token " + attrs.token
445 + " is not for an application");
446 case WindowManagerImpl.ADD_APP_EXITING:
447 throw new WindowManagerImpl.BadTokenException(
448 "Unable to add window -- app for token " + attrs.token
449 + " is exiting");
450 case WindowManagerImpl.ADD_DUPLICATE_ADD:
451 throw new WindowManagerImpl.BadTokenException(
452 "Unable to add window -- window " + mWindow
453 + " has already been added");
454 case WindowManagerImpl.ADD_STARTING_NOT_NEEDED:
455 // Silently ignore -- we would have just removed it
456 // right away, anyway.
457 return;
458 case WindowManagerImpl.ADD_MULTIPLE_SINGLETON:
459 throw new WindowManagerImpl.BadTokenException(
460 "Unable to add window " + mWindow +
461 " -- another window of this type already exists");
462 case WindowManagerImpl.ADD_PERMISSION_DENIED:
463 throw new WindowManagerImpl.BadTokenException(
464 "Unable to add window " + mWindow +
465 " -- permission denied for this window type");
466 }
467 throw new RuntimeException(
468 "Unable to add window -- unknown error code " + res);
469 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700470
Jeff Brown00fa7bd2010-07-02 15:37:36 -0700471 if (view instanceof RootViewSurfaceTaker) {
472 mInputQueueCallback =
473 ((RootViewSurfaceTaker)view).willYouTakeTheInputQueue();
474 }
475 if (mInputQueueCallback != null) {
476 mInputQueue = new InputQueue(mInputChannel);
477 mInputQueueCallback.onInputQueueCreated(mInputQueue);
478 } else {
479 InputQueue.registerInputChannel(mInputChannel, mInputHandler,
480 Looper.myQueue());
Jeff Brown46b9ac02010-04-22 18:58:52 -0700481 }
482
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800483 view.assignParent(this);
484 mAddedTouchMode = (res&WindowManagerImpl.ADD_FLAG_IN_TOUCH_MODE) != 0;
485 mAppVisible = (res&WindowManagerImpl.ADD_FLAG_APP_VISIBLE) != 0;
486 }
487 }
488 }
489
Romain Guy529b60a2010-08-03 18:05:47 -0700490 private void enableHardwareAcceleration(WindowManager.LayoutParams attrs) {
Dianne Hackborn7eec10e2010-11-12 18:03:47 -0800491 mAttachInfo.mHardwareAccelerated = false;
492 mAttachInfo.mHardwareAccelerationRequested = false;
Romain Guy4f6aff32011-01-12 16:21:41 -0800493
Dianne Hackborn7eec10e2010-11-12 18:03:47 -0800494 // Try to enable hardware acceleration if requested
495 if (attrs != null &&
496 (attrs.flags & WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED) != 0) {
497 // Only enable hardware acceleration if we are not in the system process
498 // The window manager creates ViewRoots to display animated preview windows
499 // of launching apps and we don't want those to be hardware accelerated
500 if (!HardwareRenderer.sRendererDisabled) {
Romain Guyff26a0c2011-01-20 11:35:46 -0800501 // Don't enable hardware acceleration when we're not on the main thread
502 if (Looper.getMainLooper() != Looper.myLooper()) {
503 Log.w(HardwareRenderer.LOG_TAG, "Attempting to initialize hardware "
504 + "acceleration outside of the main thread, aborting");
505 return;
506 }
507
Romain Guye4d01122010-06-16 18:44:05 -0700508 final boolean translucent = attrs.format != PixelFormat.OPAQUE;
Romain Guyb051e892010-09-28 19:09:36 -0700509 if (mAttachInfo.mHardwareRenderer != null) {
510 mAttachInfo.mHardwareRenderer.destroy(true);
Romain Guy4caa4ed2010-08-25 14:46:24 -0700511 }
Romain Guyb051e892010-09-28 19:09:36 -0700512 mAttachInfo.mHardwareRenderer = HardwareRenderer.createGlRenderer(2, translucent);
Dianne Hackborn7eec10e2010-11-12 18:03:47 -0800513 mAttachInfo.mHardwareAccelerated = mAttachInfo.mHardwareAccelerationRequested
514 = mAttachInfo.mHardwareRenderer != null;
515 } else if (HardwareRenderer.isAvailable()) {
516 mAttachInfo.mHardwareAccelerationRequested = true;
Romain Guye4d01122010-06-16 18:44:05 -0700517 }
518 }
519 }
520
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800521 public View getView() {
522 return mView;
523 }
524
525 final WindowLeaked getLocation() {
526 return mLocation;
527 }
528
529 void setLayoutParams(WindowManager.LayoutParams attrs, boolean newView) {
530 synchronized (this) {
The Android Open Source Project10592532009-03-18 17:39:46 -0700531 int oldSoftInputMode = mWindowAttributes.softInputMode;
Mitsuru Oshima5a2b91d2009-07-16 16:30:02 -0700532 // preserve compatible window flag if exists.
533 int compatibleWindowFlag =
534 mWindowAttributes.flags & WindowManager.LayoutParams.FLAG_COMPATIBLE_WINDOW;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800535 mWindowAttributes.copyFrom(attrs);
Mitsuru Oshima5a2b91d2009-07-16 16:30:02 -0700536 mWindowAttributes.flags |= compatibleWindowFlag;
537
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800538 if (newView) {
539 mSoftInputMode = attrs.softInputMode;
540 requestLayout();
541 }
The Android Open Source Project10592532009-03-18 17:39:46 -0700542 // Don't lose the mode we last auto-computed.
543 if ((attrs.softInputMode&WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST)
544 == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED) {
545 mWindowAttributes.softInputMode = (mWindowAttributes.softInputMode
546 & ~WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST)
547 | (oldSoftInputMode
548 & WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST);
549 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800550 mWindowAttributesChanged = true;
551 scheduleTraversals();
552 }
553 }
554
555 void handleAppVisibility(boolean visible) {
556 if (mAppVisible != visible) {
557 mAppVisible = visible;
558 scheduleTraversals();
559 }
560 }
561
562 void handleGetNewSurface() {
563 mNewSurfaceNeeded = true;
564 mFullRedrawNeeded = true;
565 scheduleTraversals();
566 }
567
568 /**
569 * {@inheritDoc}
570 */
571 public void requestLayout() {
572 checkThread();
573 mLayoutRequested = true;
574 scheduleTraversals();
575 }
576
577 /**
578 * {@inheritDoc}
579 */
580 public boolean isLayoutRequested() {
581 return mLayoutRequested;
582 }
583
584 public void invalidateChild(View child, Rect dirty) {
585 checkThread();
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700586 if (DEBUG_DRAW) Log.v(TAG, "Invalidate child: " + dirty);
Chet Haase70d4ba12010-10-06 09:46:45 -0700587 if (dirty == null) {
588 // Fast invalidation for GL-enabled applications; GL must redraw everything
589 invalidate();
590 return;
591 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700592 if (mCurScrollY != 0 || mTranslator != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800593 mTempRect.set(dirty);
Romain Guy1e095972009-07-07 11:22:45 -0700594 dirty = mTempRect;
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700595 if (mCurScrollY != 0) {
Romain Guy1e095972009-07-07 11:22:45 -0700596 dirty.offset(0, -mCurScrollY);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700597 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700598 if (mTranslator != null) {
Romain Guy1e095972009-07-07 11:22:45 -0700599 mTranslator.translateRectInAppWindowToScreen(dirty);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700600 }
Romain Guy1e095972009-07-07 11:22:45 -0700601 if (mAttachInfo.mScalingRequired) {
602 dirty.inset(-1, -1);
603 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800604 }
Romain Guy7d695942010-12-01 17:22:29 -0800605 if (!mDirty.isEmpty()) {
606 mAttachInfo.mIgnoreDirtyState = true;
607 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800608 mDirty.union(dirty);
609 if (!mWillDrawSoon) {
610 scheduleTraversals();
611 }
612 }
Romain Guy0d9275e2010-10-26 14:22:30 -0700613
614 void invalidate() {
615 mDirty.set(0, 0, mWidth, mHeight);
616 scheduleTraversals();
617 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800618
619 public ViewParent getParent() {
620 return null;
621 }
622
623 public ViewParent invalidateChildInParent(final int[] location, final Rect dirty) {
624 invalidateChild(null, dirty);
625 return null;
626 }
627
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700628 public boolean getChildVisibleRect(View child, Rect r, android.graphics.Point offset) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800629 if (child != mView) {
630 throw new RuntimeException("child is not mine, honest!");
631 }
632 // Note: don't apply scroll offset, because we want to know its
633 // visibility in the virtual canvas being given to the view hierarchy.
634 return r.intersect(0, 0, mWidth, mHeight);
635 }
636
637 public void bringChildToFront(View child) {
638 }
639
640 public void scheduleTraversals() {
641 if (!mTraversalScheduled) {
642 mTraversalScheduled = true;
643 sendEmptyMessage(DO_TRAVERSAL);
644 }
645 }
646
647 public void unscheduleTraversals() {
648 if (mTraversalScheduled) {
649 mTraversalScheduled = false;
650 removeMessages(DO_TRAVERSAL);
651 }
652 }
653
654 int getHostVisibility() {
655 return mAppVisible ? mView.getVisibility() : View.GONE;
656 }
Romain Guy8506ab42009-06-11 17:35:47 -0700657
Dianne Hackborn0f761d62010-11-30 22:06:10 -0800658 void disposeResizeBitmap() {
659 if (mResizeBitmap != null) {
660 mResizeBitmap.recycle();
661 mResizeBitmap = null;
662 }
663 }
664
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800665 private void performTraversals() {
666 // cache mView since it is used so much below...
667 final View host = mView;
668
669 if (DBG) {
670 System.out.println("======================================");
671 System.out.println("performTraversals");
672 host.debug();
673 }
674
675 if (host == null || !mAdded)
676 return;
677
678 mTraversalScheduled = false;
679 mWillDrawSoon = true;
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800680 boolean windowSizeMayChange = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800681 boolean fullRedrawNeeded = mFullRedrawNeeded;
682 boolean newSurface = false;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700683 boolean surfaceChanged = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800684 WindowManager.LayoutParams lp = mWindowAttributes;
685
686 int desiredWindowWidth;
687 int desiredWindowHeight;
688 int childWidthMeasureSpec;
689 int childHeightMeasureSpec;
690
691 final View.AttachInfo attachInfo = mAttachInfo;
692
693 final int viewVisibility = getHostVisibility();
694 boolean viewVisibilityChanged = mViewVisibility != viewVisibility
695 || mNewSurfaceNeeded;
696
697 WindowManager.LayoutParams params = null;
698 if (mWindowAttributesChanged) {
699 mWindowAttributesChanged = false;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700700 surfaceChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800701 params = lp;
702 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700703 Rect frame = mWinFrame;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800704 if (mFirst) {
705 fullRedrawNeeded = true;
706 mLayoutRequested = true;
707
Romain Guy8506ab42009-06-11 17:35:47 -0700708 DisplayMetrics packageMetrics =
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700709 mView.getContext().getResources().getDisplayMetrics();
710 desiredWindowWidth = packageMetrics.widthPixels;
711 desiredWindowHeight = packageMetrics.heightPixels;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800712
713 // For the very first time, tell the view hierarchy that it
714 // is attached to the window. Note that at this point the surface
715 // object is not initialized to its backing store, but soon it
716 // will be (assuming the window is visible).
717 attachInfo.mSurface = mSurface;
Romain Guyc5d55862011-01-21 19:01:46 -0800718 // We used to use the following condition to choose 32 bits drawing caches:
719 // PixelFormat.hasAlpha(lp.format) || lp.format == PixelFormat.RGBX_8888
720 // However, windows are now always 32 bits by default, so choose 32 bits
721 attachInfo.mUse32BitDrawingCache = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800722 attachInfo.mHasWindowFocus = false;
723 attachInfo.mWindowVisibility = viewVisibility;
724 attachInfo.mRecomputeGlobalAttributes = false;
725 attachInfo.mKeepScreenOn = false;
Joe Onorato664644d2011-01-23 17:53:23 -0800726 attachInfo.mSystemUiVisibility = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800727 viewVisibilityChanged = false;
Dianne Hackborn694f79b2010-03-17 19:44:59 -0700728 mLastConfiguration.setTo(host.getResources().getConfiguration());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800729 host.dispatchAttachedToWindow(attachInfo, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800730 //Log.i(TAG, "Screen on initialized: " + attachInfo.mKeepScreenOn);
svetoslavganov75986cf2009-05-14 22:28:01 -0700731
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800732 } else {
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700733 desiredWindowWidth = frame.width();
734 desiredWindowHeight = frame.height();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800735 if (desiredWindowWidth != mWidth || desiredWindowHeight != mHeight) {
Jeff Brownc5ed5912010-07-14 18:48:53 -0700736 if (DEBUG_ORIENTATION) Log.v(TAG,
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700737 "View " + host + " resized to: " + frame);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800738 fullRedrawNeeded = true;
739 mLayoutRequested = true;
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800740 windowSizeMayChange = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800741 }
742 }
743
744 if (viewVisibilityChanged) {
745 attachInfo.mWindowVisibility = viewVisibility;
746 host.dispatchWindowVisibilityChanged(viewVisibility);
747 if (viewVisibility != View.VISIBLE || mNewSurfaceNeeded) {
Romain Guyb051e892010-09-28 19:09:36 -0700748 if (mAttachInfo.mHardwareRenderer != null) {
749 mAttachInfo.mHardwareRenderer.destroy(false);
Romain Guy4caa4ed2010-08-25 14:46:24 -0700750 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800751 }
752 if (viewVisibility == View.GONE) {
753 // After making a window gone, we will count it as being
754 // shown for the first time the next time it gets focus.
755 mHasHadWindowFocus = false;
756 }
757 }
758
759 boolean insetsChanged = false;
Romain Guy8506ab42009-06-11 17:35:47 -0700760
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800761 if (mLayoutRequested) {
Romain Guy15df6702009-08-17 20:17:30 -0700762 // Execute enqueued actions on every layout in case a view that was detached
763 // enqueued an action after being detached
764 getRunQueue().executeActions(attachInfo.mHandler);
765
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800766 final Resources res = mView.getContext().getResources();
767
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800768 if (mFirst) {
769 host.fitSystemWindows(mAttachInfo.mContentInsets);
770 // make sure touch mode code executes by setting cached value
771 // to opposite of the added touch mode.
772 mAttachInfo.mInTouchMode = !mAddedTouchMode;
Romain Guy2d4cff62010-04-09 15:39:00 -0700773 ensureTouchModeLocally(mAddedTouchMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800774 } else {
775 if (!mAttachInfo.mContentInsets.equals(mPendingContentInsets)) {
Dianne Hackborn0f761d62010-11-30 22:06:10 -0800776 if (mWidth > 0 && mHeight > 0 &&
777 mSurface != null && mSurface.isValid() &&
778 mAttachInfo.mHardwareRenderer != null &&
779 mAttachInfo.mHardwareRenderer.isEnabled() &&
780 lp != null && !PixelFormat.formatHasAlpha(lp.format)) {
781
782 disposeResizeBitmap();
783
784 boolean completed = false;
785 try {
786 mResizeBitmap = Bitmap.createBitmap(mWidth, mHeight,
787 Bitmap.Config.ARGB_8888);
788 mResizeBitmap.setHasAlpha(false);
789 Canvas canvas = new Canvas(mResizeBitmap);
790 int yoff;
791 final boolean scrolling = mScroller != null
792 && mScroller.computeScrollOffset();
793 if (scrolling) {
794 yoff = mScroller.getCurrY();
795 mScroller.abortAnimation();
796 } else {
797 yoff = mScrollY;
798 }
799 canvas.translate(0, -yoff);
800 if (mTranslator != null) {
801 mTranslator.translateCanvas(canvas);
802 }
803 canvas.setScreenDensity(mAttachInfo.mScalingRequired
804 ? DisplayMetrics.DENSITY_DEVICE : 0);
805 mView.draw(canvas);
806 mResizeBitmapStartTime = SystemClock.uptimeMillis();
807 mResizeBitmapDuration = mView.getResources().getInteger(
808 com.android.internal.R.integer.config_mediumAnimTime);
809 completed = true;
810 } catch (OutOfMemoryError e) {
811 Log.w(TAG, "Not enough memory for content change anim buffer", e);
812 } finally {
813 if (!completed) {
814 mResizeBitmap = null;
815 }
816 }
817 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800818 mAttachInfo.mContentInsets.set(mPendingContentInsets);
819 host.fitSystemWindows(mAttachInfo.mContentInsets);
820 insetsChanged = true;
821 if (DEBUG_LAYOUT) Log.v(TAG, "Content insets changing to: "
822 + mAttachInfo.mContentInsets);
823 }
824 if (!mAttachInfo.mVisibleInsets.equals(mPendingVisibleInsets)) {
825 mAttachInfo.mVisibleInsets.set(mPendingVisibleInsets);
826 if (DEBUG_LAYOUT) Log.v(TAG, "Visible insets changing to: "
827 + mAttachInfo.mVisibleInsets);
828 }
829 if (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT
830 || lp.height == ViewGroup.LayoutParams.WRAP_CONTENT) {
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800831 windowSizeMayChange = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800832
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800833 DisplayMetrics packageMetrics = res.getDisplayMetrics();
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700834 desiredWindowWidth = packageMetrics.widthPixels;
835 desiredWindowHeight = packageMetrics.heightPixels;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800836 }
837 }
838
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800839 // Ask host how big it wants to be
Jeff Brownc5ed5912010-07-14 18:48:53 -0700840 if (DEBUG_ORIENTATION || DEBUG_LAYOUT) Log.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800841 "Measuring " + host + " in display " + desiredWindowWidth
842 + "x" + desiredWindowHeight + "...");
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800843
844 boolean goodMeasure = false;
845 if (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT
846 || lp.height == ViewGroup.LayoutParams.WRAP_CONTENT) {
847 // On large screens, we don't want to allow dialogs to just
848 // stretch to fill the entire width of the screen to display
849 // one line of text. First try doing the layout at a smaller
850 // size to see if it will fit.
851 final DisplayMetrics packageMetrics = res.getDisplayMetrics();
852 res.getValue(com.android.internal.R.dimen.config_prefDialogWidth, mTmpValue, true);
853 int baseSize = 0;
854 if (mTmpValue.type == TypedValue.TYPE_DIMENSION) {
855 baseSize = (int)mTmpValue.getDimension(packageMetrics);
856 }
857 if (DEBUG_DIALOG) Log.v(TAG, "Window " + mView + ": baseSize=" + baseSize);
Dianne Hackborn7d3a5bc2010-11-29 22:52:12 -0800858 if (baseSize != 0 && desiredWindowWidth > baseSize) {
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800859 childWidthMeasureSpec = getRootMeasureSpec(baseSize, lp.width);
860 childHeightMeasureSpec = getRootMeasureSpec(desiredWindowHeight, lp.height);
861 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
862 if (DEBUG_DIALOG) Log.v(TAG, "Window " + mView + ": measured ("
Dianne Hackborn189ee182010-12-02 21:48:53 -0800863 + host.getMeasuredWidth() + "," + host.getMeasuredHeight() + ")");
864 if ((host.getMeasuredWidthAndState()&View.MEASURED_STATE_TOO_SMALL) == 0) {
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800865 goodMeasure = true;
866 } else {
867 // Didn't fit in that size... try expanding a bit.
868 baseSize = (baseSize+desiredWindowWidth)/2;
869 if (DEBUG_DIALOG) Log.v(TAG, "Window " + mView + ": next baseSize="
870 + baseSize);
Dianne Hackborn189ee182010-12-02 21:48:53 -0800871 childWidthMeasureSpec = getRootMeasureSpec(baseSize, lp.width);
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800872 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
873 if (DEBUG_DIALOG) Log.v(TAG, "Window " + mView + ": measured ("
Dianne Hackborn189ee182010-12-02 21:48:53 -0800874 + host.getMeasuredWidth() + "," + host.getMeasuredHeight() + ")");
875 if ((host.getMeasuredWidthAndState()&View.MEASURED_STATE_TOO_SMALL) == 0) {
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800876 if (DEBUG_DIALOG) Log.v(TAG, "Good!");
877 goodMeasure = true;
878 }
879 }
880 }
881 }
882
883 if (!goodMeasure) {
884 childWidthMeasureSpec = getRootMeasureSpec(desiredWindowWidth, lp.width);
885 childHeightMeasureSpec = getRootMeasureSpec(desiredWindowHeight, lp.height);
886 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
Adam Powellaa0b92c2010-12-13 22:38:53 -0800887 if (mWidth != host.getMeasuredWidth() || mHeight != host.getMeasuredHeight()) {
888 windowSizeMayChange = true;
889 }
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800890 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800891
892 if (DBG) {
893 System.out.println("======================================");
894 System.out.println("performTraversals -- after measure");
895 host.debug();
896 }
897 }
898
899 if (attachInfo.mRecomputeGlobalAttributes) {
Joe Onorato664644d2011-01-23 17:53:23 -0800900 //Log.i(TAG, "Computing view hierarchy attributes!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800901 attachInfo.mRecomputeGlobalAttributes = false;
Joe Onorato664644d2011-01-23 17:53:23 -0800902 boolean oldScreenOn = attachInfo.mKeepScreenOn;
903 int oldVis = attachInfo.mSystemUiVisibility;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800904 attachInfo.mKeepScreenOn = false;
Joe Onorato664644d2011-01-23 17:53:23 -0800905 attachInfo.mSystemUiVisibility = 0;
906 attachInfo.mHasSystemUiListeners = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800907 host.dispatchCollectViewAttributes(0);
Joe Onorato664644d2011-01-23 17:53:23 -0800908 if (attachInfo.mKeepScreenOn != oldScreenOn ||
909 attachInfo.mSystemUiVisibility != oldVis) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800910 params = lp;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800911 }
912 }
913
914 if (mFirst || attachInfo.mViewVisibilityChanged) {
915 attachInfo.mViewVisibilityChanged = false;
916 int resizeMode = mSoftInputMode &
917 WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST;
918 // If we are in auto resize mode, then we need to determine
919 // what mode to use now.
920 if (resizeMode == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED) {
921 final int N = attachInfo.mScrollContainers.size();
922 for (int i=0; i<N; i++) {
923 if (attachInfo.mScrollContainers.get(i).isShown()) {
924 resizeMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE;
925 }
926 }
927 if (resizeMode == 0) {
928 resizeMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN;
929 }
930 if ((lp.softInputMode &
931 WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) != resizeMode) {
932 lp.softInputMode = (lp.softInputMode &
933 ~WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) |
934 resizeMode;
935 params = lp;
936 }
937 }
938 }
Romain Guy8506ab42009-06-11 17:35:47 -0700939
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800940 if (params != null && (host.mPrivateFlags & View.REQUEST_TRANSPARENT_REGIONS) != 0) {
941 if (!PixelFormat.formatHasAlpha(params.format)) {
942 params.format = PixelFormat.TRANSLUCENT;
943 }
944 }
945
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800946 boolean windowShouldResize = mLayoutRequested && windowSizeMayChange
Dianne Hackborn189ee182010-12-02 21:48:53 -0800947 && ((mWidth != host.getMeasuredWidth() || mHeight != host.getMeasuredHeight())
Romain Guy2e4f4262010-04-06 11:07:52 -0700948 || (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT &&
949 frame.width() < desiredWindowWidth && frame.width() != mWidth)
950 || (lp.height == ViewGroup.LayoutParams.WRAP_CONTENT &&
951 frame.height() < desiredWindowHeight && frame.height() != mHeight));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800952
953 final boolean computesInternalInsets =
954 attachInfo.mTreeObserver.hasComputeInternalInsetsListeners();
Romain Guy812ccbe2010-06-01 14:07:24 -0700955
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800956 boolean insetsPending = false;
957 int relayoutResult = 0;
Romain Guy812ccbe2010-06-01 14:07:24 -0700958
959 if (mFirst || windowShouldResize || insetsChanged ||
960 viewVisibilityChanged || params != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800961
962 if (viewVisibility == View.VISIBLE) {
963 // If this window is giving internal insets to the window
964 // manager, and it is being added or changing its visibility,
965 // then we want to first give the window manager "fake"
966 // insets to cause it to effectively ignore the content of
967 // the window during layout. This avoids it briefly causing
968 // other windows to resize/move based on the raw frame of the
969 // window, waiting until we can finish laying out this window
970 // and get back to the window manager with the ultimately
971 // computed insets.
Romain Guy812ccbe2010-06-01 14:07:24 -0700972 insetsPending = computesInternalInsets && (mFirst || viewVisibilityChanged);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800973 }
974
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700975 if (mSurfaceHolder != null) {
976 mSurfaceHolder.mSurfaceLock.lock();
977 mDrawingAllowed = true;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700978 }
Romain Guy812ccbe2010-06-01 14:07:24 -0700979
Romain Guyc361da82010-10-25 15:29:10 -0700980 boolean hwInitialized = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800981 boolean contentInsetsChanged = false;
Romain Guy13922e02009-05-12 17:56:14 -0700982 boolean visibleInsetsChanged;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700983 boolean hadSurface = mSurface.isValid();
Romain Guy812ccbe2010-06-01 14:07:24 -0700984
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800985 try {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800986 int fl = 0;
987 if (params != null) {
988 fl = params.flags;
989 if (attachInfo.mKeepScreenOn) {
990 params.flags |= WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
991 }
Joe Onorato664644d2011-01-23 17:53:23 -0800992 params.systemUiVisibility = attachInfo.mSystemUiVisibility;
993 params.hasSystemUiListeners = attachInfo.mHasSystemUiListeners;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800994 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700995 if (DEBUG_LAYOUT) {
Dianne Hackborn189ee182010-12-02 21:48:53 -0800996 Log.i(TAG, "host=w:" + host.getMeasuredWidth() + ", h:" +
997 host.getMeasuredHeight() + ", params=" + params);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700998 }
Romain Guy2a83f002011-01-18 18:28:21 -0800999
1000 final int surfaceGenerationId = mSurface.getGenerationId();
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001001 relayoutResult = relayoutWindow(params, viewVisibility, insetsPending);
1002
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001003 if (params != null) {
1004 params.flags = fl;
1005 }
1006
1007 if (DEBUG_LAYOUT) Log.v(TAG, "relayout: frame=" + frame.toShortString()
1008 + " content=" + mPendingContentInsets.toShortString()
1009 + " visible=" + mPendingVisibleInsets.toShortString()
1010 + " surface=" + mSurface);
Romain Guy8506ab42009-06-11 17:35:47 -07001011
Dianne Hackborn694f79b2010-03-17 19:44:59 -07001012 if (mPendingConfiguration.seq != 0) {
1013 if (DEBUG_CONFIGURATION) Log.v(TAG, "Visible with new config: "
1014 + mPendingConfiguration);
1015 updateConfiguration(mPendingConfiguration, !mFirst);
1016 mPendingConfiguration.seq = 0;
1017 }
1018
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001019 contentInsetsChanged = !mPendingContentInsets.equals(
1020 mAttachInfo.mContentInsets);
1021 visibleInsetsChanged = !mPendingVisibleInsets.equals(
1022 mAttachInfo.mVisibleInsets);
1023 if (contentInsetsChanged) {
1024 mAttachInfo.mContentInsets.set(mPendingContentInsets);
1025 host.fitSystemWindows(mAttachInfo.mContentInsets);
1026 if (DEBUG_LAYOUT) Log.v(TAG, "Content insets changing to: "
1027 + mAttachInfo.mContentInsets);
1028 }
1029 if (visibleInsetsChanged) {
1030 mAttachInfo.mVisibleInsets.set(mPendingVisibleInsets);
1031 if (DEBUG_LAYOUT) Log.v(TAG, "Visible insets changing to: "
1032 + mAttachInfo.mVisibleInsets);
1033 }
1034
1035 if (!hadSurface) {
1036 if (mSurface.isValid()) {
1037 // If we are creating a new surface, then we need to
1038 // completely redraw it. Also, when we get to the
1039 // point of drawing it we will hold off and schedule
1040 // a new traversal instead. This is so we can tell the
1041 // window manager about all of the windows being displayed
1042 // before actually drawing them, so it can display then
1043 // all at once.
1044 newSurface = true;
1045 fullRedrawNeeded = true;
Jack Palevich61a6e682009-10-09 17:37:50 -07001046 mPreviousTransparentRegion.setEmpty();
Romain Guy8506ab42009-06-11 17:35:47 -07001047
Romain Guyb051e892010-09-28 19:09:36 -07001048 if (mAttachInfo.mHardwareRenderer != null) {
Romain Guyc361da82010-10-25 15:29:10 -07001049 hwInitialized = mAttachInfo.mHardwareRenderer.initialize(mHolder);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001050 }
1051 }
1052 } else if (!mSurface.isValid()) {
1053 // If the surface has been removed, then reset the scroll
1054 // positions.
1055 mLastScrolledFocus = null;
1056 mScrollY = mCurScrollY = 0;
1057 if (mScroller != null) {
1058 mScroller.abortAnimation();
1059 }
Dianne Hackborn0f761d62010-11-30 22:06:10 -08001060 disposeResizeBitmap();
Romain Guy2a83f002011-01-18 18:28:21 -08001061 } else if (surfaceGenerationId != mSurface.getGenerationId() &&
1062 mSurfaceHolder == null && mAttachInfo.mHardwareRenderer != null) {
1063 mAttachInfo.mHardwareRenderer.updateSurface(mHolder);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001064 }
1065 } catch (RemoteException e) {
1066 }
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001067
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001068 if (DEBUG_ORIENTATION) Log.v(
Jeff Brownc5ed5912010-07-14 18:48:53 -07001069 TAG, "Relayout returned: frame=" + frame + ", surface=" + mSurface);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001070
1071 attachInfo.mWindowLeft = frame.left;
1072 attachInfo.mWindowTop = frame.top;
1073
1074 // !!FIXME!! This next section handles the case where we did not get the
1075 // window size we asked for. We should avoid this by getting a maximum size from
1076 // the window session beforehand.
1077 mWidth = frame.width();
1078 mHeight = frame.height();
1079
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001080 if (mSurfaceHolder != null) {
1081 // The app owns the surface; tell it about what is going on.
1082 if (mSurface.isValid()) {
1083 // XXX .copyFrom() doesn't work!
1084 //mSurfaceHolder.mSurface.copyFrom(mSurface);
1085 mSurfaceHolder.mSurface = mSurface;
1086 }
1087 mSurfaceHolder.mSurfaceLock.unlock();
1088 if (mSurface.isValid()) {
1089 if (!hadSurface) {
1090 mSurfaceHolder.ungetCallbacks();
1091
1092 mIsCreating = true;
1093 mSurfaceHolderCallback.surfaceCreated(mSurfaceHolder);
1094 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
1095 if (callbacks != null) {
1096 for (SurfaceHolder.Callback c : callbacks) {
1097 c.surfaceCreated(mSurfaceHolder);
1098 }
1099 }
1100 surfaceChanged = true;
1101 }
1102 if (surfaceChanged) {
1103 mSurfaceHolderCallback.surfaceChanged(mSurfaceHolder,
1104 lp.format, mWidth, mHeight);
1105 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
1106 if (callbacks != null) {
1107 for (SurfaceHolder.Callback c : callbacks) {
1108 c.surfaceChanged(mSurfaceHolder, lp.format,
1109 mWidth, mHeight);
1110 }
1111 }
1112 }
1113 mIsCreating = false;
1114 } else if (hadSurface) {
1115 mSurfaceHolder.ungetCallbacks();
1116 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
1117 mSurfaceHolderCallback.surfaceDestroyed(mSurfaceHolder);
1118 if (callbacks != null) {
1119 for (SurfaceHolder.Callback c : callbacks) {
1120 c.surfaceDestroyed(mSurfaceHolder);
1121 }
1122 }
1123 mSurfaceHolder.mSurfaceLock.lock();
1124 // Make surface invalid.
1125 //mSurfaceHolder.mSurface.copyFrom(mSurface);
1126 mSurfaceHolder.mSurface = new Surface();
1127 mSurfaceHolder.mSurfaceLock.unlock();
1128 }
1129 }
Romain Guy53389bd2010-09-07 17:16:32 -07001130
Romain Guy6b5108b2011-01-04 16:11:10 -08001131 if (hwInitialized || ((windowShouldResize || params != null) &&
Romain Guydbf78bd2010-12-07 17:04:03 -08001132 mAttachInfo.mHardwareRenderer != null &&
1133 mAttachInfo.mHardwareRenderer.isEnabled())) {
Romain Guyb051e892010-09-28 19:09:36 -07001134 mAttachInfo.mHardwareRenderer.setup(mWidth, mHeight);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001135 }
1136
1137 boolean focusChangedDueToTouchMode = ensureTouchModeLocally(
Romain Guy2d4cff62010-04-09 15:39:00 -07001138 (relayoutResult&WindowManagerImpl.RELAYOUT_IN_TOUCH_MODE) != 0);
Dianne Hackborn189ee182010-12-02 21:48:53 -08001139 if (focusChangedDueToTouchMode || mWidth != host.getMeasuredWidth()
1140 || mHeight != host.getMeasuredHeight() || contentInsetsChanged) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001141 childWidthMeasureSpec = getRootMeasureSpec(mWidth, lp.width);
1142 childHeightMeasureSpec = getRootMeasureSpec(mHeight, lp.height);
1143
1144 if (DEBUG_LAYOUT) Log.v(TAG, "Ooops, something changed! mWidth="
Dianne Hackborn189ee182010-12-02 21:48:53 -08001145 + mWidth + " measuredWidth=" + host.getMeasuredWidth()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001146 + " mHeight=" + mHeight
Dianne Hackbornff801ec2011-01-22 18:05:38 -08001147 + " measuredHeight=" + host.getMeasuredHeight()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001148 + " coveredInsetsChanged=" + contentInsetsChanged);
Romain Guy8506ab42009-06-11 17:35:47 -07001149
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001150 // Ask host how big it wants to be
1151 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
1152
1153 // Implementation of weights from WindowManager.LayoutParams
1154 // We just grow the dimensions as needed and re-measure if
1155 // needs be
Dianne Hackborn189ee182010-12-02 21:48:53 -08001156 int width = host.getMeasuredWidth();
1157 int height = host.getMeasuredHeight();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001158 boolean measureAgain = false;
1159
1160 if (lp.horizontalWeight > 0.0f) {
1161 width += (int) ((mWidth - width) * lp.horizontalWeight);
1162 childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(width,
1163 MeasureSpec.EXACTLY);
1164 measureAgain = true;
1165 }
1166 if (lp.verticalWeight > 0.0f) {
1167 height += (int) ((mHeight - height) * lp.verticalWeight);
1168 childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(height,
1169 MeasureSpec.EXACTLY);
1170 measureAgain = true;
1171 }
1172
1173 if (measureAgain) {
1174 if (DEBUG_LAYOUT) Log.v(TAG,
1175 "And hey let's measure once more: width=" + width
1176 + " height=" + height);
1177 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
1178 }
1179
1180 mLayoutRequested = true;
1181 }
1182 }
1183
1184 final boolean didLayout = mLayoutRequested;
1185 boolean triggerGlobalLayoutListener = didLayout
1186 || attachInfo.mRecomputeGlobalAttributes;
1187 if (didLayout) {
1188 mLayoutRequested = false;
1189 mScrollMayChange = true;
1190 if (DEBUG_ORIENTATION || DEBUG_LAYOUT) Log.v(
Jeff Brownc5ed5912010-07-14 18:48:53 -07001191 TAG, "Laying out " + host + " to (" +
Dianne Hackborn189ee182010-12-02 21:48:53 -08001192 host.getMeasuredWidth() + ", " + host.getMeasuredHeight() + ")");
Romain Guy13922e02009-05-12 17:56:14 -07001193 long startTime = 0L;
Romain Guy5429e1d2010-09-07 12:38:00 -07001194 if (ViewDebug.DEBUG_PROFILE_LAYOUT) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001195 startTime = SystemClock.elapsedRealtime();
1196 }
Dianne Hackborn189ee182010-12-02 21:48:53 -08001197 host.layout(0, 0, host.getMeasuredWidth(), host.getMeasuredHeight());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001198
Romain Guy13922e02009-05-12 17:56:14 -07001199 if (Config.DEBUG && ViewDebug.consistencyCheckEnabled) {
1200 if (!host.dispatchConsistencyCheck(ViewDebug.CONSISTENCY_LAYOUT)) {
1201 throw new IllegalStateException("The view hierarchy is an inconsistent state,"
1202 + "please refer to the logs with the tag "
1203 + ViewDebug.CONSISTENCY_LOG_TAG + " for more infomation.");
1204 }
1205 }
1206
Romain Guy5429e1d2010-09-07 12:38:00 -07001207 if (ViewDebug.DEBUG_PROFILE_LAYOUT) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001208 EventLog.writeEvent(60001, SystemClock.elapsedRealtime() - startTime);
1209 }
1210
1211 // By this point all views have been sized and positionned
1212 // We can compute the transparent area
1213
1214 if ((host.mPrivateFlags & View.REQUEST_TRANSPARENT_REGIONS) != 0) {
1215 // start out transparent
1216 // TODO: AVOID THAT CALL BY CACHING THE RESULT?
1217 host.getLocationInWindow(mTmpLocation);
1218 mTransparentRegion.set(mTmpLocation[0], mTmpLocation[1],
1219 mTmpLocation[0] + host.mRight - host.mLeft,
1220 mTmpLocation[1] + host.mBottom - host.mTop);
1221
1222 host.gatherTransparentRegion(mTransparentRegion);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001223 if (mTranslator != null) {
1224 mTranslator.translateRegionInWindowToScreen(mTransparentRegion);
1225 }
1226
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001227 if (!mTransparentRegion.equals(mPreviousTransparentRegion)) {
1228 mPreviousTransparentRegion.set(mTransparentRegion);
1229 // reconfigure window manager
1230 try {
1231 sWindowSession.setTransparentRegion(mWindow, mTransparentRegion);
1232 } catch (RemoteException e) {
1233 }
1234 }
1235 }
1236
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001237 if (DBG) {
1238 System.out.println("======================================");
1239 System.out.println("performTraversals -- after setFrame");
1240 host.debug();
1241 }
1242 }
1243
1244 if (triggerGlobalLayoutListener) {
1245 attachInfo.mRecomputeGlobalAttributes = false;
1246 attachInfo.mTreeObserver.dispatchOnGlobalLayout();
1247 }
1248
1249 if (computesInternalInsets) {
Jeff Brownfbf09772011-01-16 14:06:57 -08001250 // Clear the original insets.
1251 final ViewTreeObserver.InternalInsetsInfo insets = attachInfo.mGivenInternalInsets;
1252 insets.reset();
1253
1254 // Compute new insets in place.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001255 attachInfo.mTreeObserver.dispatchOnComputeInternalInsets(insets);
Jeff Brownfbf09772011-01-16 14:06:57 -08001256
1257 // Tell the window manager.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001258 if (insetsPending || !mLastGivenInsets.equals(insets)) {
1259 mLastGivenInsets.set(insets);
Jeff Brownfbf09772011-01-16 14:06:57 -08001260
1261 // Translate insets to screen coordinates if needed.
1262 final Rect contentInsets;
1263 final Rect visibleInsets;
1264 final Region touchableRegion;
1265 if (mTranslator != null) {
1266 contentInsets = mTranslator.getTranslatedContentInsets(insets.contentInsets);
1267 visibleInsets = mTranslator.getTranslatedVisibleInsets(insets.visibleInsets);
1268 touchableRegion = mTranslator.getTranslatedTouchableArea(insets.touchableRegion);
1269 } else {
1270 contentInsets = insets.contentInsets;
1271 visibleInsets = insets.visibleInsets;
1272 touchableRegion = insets.touchableRegion;
1273 }
1274
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001275 try {
1276 sWindowSession.setInsets(mWindow, insets.mTouchableInsets,
Jeff Brownfbf09772011-01-16 14:06:57 -08001277 contentInsets, visibleInsets, touchableRegion);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001278 } catch (RemoteException e) {
1279 }
1280 }
1281 }
Romain Guy8506ab42009-06-11 17:35:47 -07001282
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001283 if (mFirst) {
1284 // handle first focus request
1285 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: mView.hasFocus()="
1286 + mView.hasFocus());
1287 if (mView != null) {
1288 if (!mView.hasFocus()) {
1289 mView.requestFocus(View.FOCUS_FORWARD);
1290 mFocusedView = mRealFocusedView = mView.findFocus();
1291 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: requested focused view="
1292 + mFocusedView);
1293 } else {
1294 mRealFocusedView = mView.findFocus();
1295 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: existing focused view="
1296 + mRealFocusedView);
1297 }
1298 }
1299 }
1300
1301 mFirst = false;
1302 mWillDrawSoon = false;
1303 mNewSurfaceNeeded = false;
1304 mViewVisibility = viewVisibility;
1305
1306 if (mAttachInfo.mHasWindowFocus) {
1307 final boolean imTarget = WindowManager.LayoutParams
1308 .mayUseInputMethod(mWindowAttributes.flags);
1309 if (imTarget != mLastWasImTarget) {
1310 mLastWasImTarget = imTarget;
1311 InputMethodManager imm = InputMethodManager.peekInstance();
1312 if (imm != null && imTarget) {
1313 imm.startGettingWindowFocus(mView);
1314 imm.onWindowFocus(mView, mView.findFocus(),
1315 mWindowAttributes.softInputMode,
1316 !mHasHadWindowFocus, mWindowAttributes.flags);
1317 }
1318 }
1319 }
Romain Guy8506ab42009-06-11 17:35:47 -07001320
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001321 boolean cancelDraw = attachInfo.mTreeObserver.dispatchOnPreDraw();
1322
1323 if (!cancelDraw && !newSurface) {
1324 mFullRedrawNeeded = false;
1325 draw(fullRedrawNeeded);
1326
1327 if ((relayoutResult&WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0
1328 || mReportNextDraw) {
1329 if (LOCAL_LOGV) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001330 Log.v(TAG, "FINISHED DRAWING: " + mWindowAttributes.getTitle());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001331 }
1332 mReportNextDraw = false;
Dianne Hackbornd76b67c2010-07-13 17:48:30 -07001333 if (mSurfaceHolder != null && mSurface.isValid()) {
1334 mSurfaceHolderCallback.surfaceRedrawNeeded(mSurfaceHolder);
1335 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
1336 if (callbacks != null) {
1337 for (SurfaceHolder.Callback c : callbacks) {
1338 if (c instanceof SurfaceHolder.Callback2) {
1339 ((SurfaceHolder.Callback2)c).surfaceRedrawNeeded(
1340 mSurfaceHolder);
1341 }
1342 }
1343 }
1344 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001345 try {
1346 sWindowSession.finishDrawing(mWindow);
1347 } catch (RemoteException e) {
1348 }
1349 }
1350 } else {
1351 // We were supposed to report when we are done drawing. Since we canceled the
1352 // draw, remember it here.
1353 if ((relayoutResult&WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0) {
1354 mReportNextDraw = true;
1355 }
1356 if (fullRedrawNeeded) {
1357 mFullRedrawNeeded = true;
1358 }
1359 // Try again
1360 scheduleTraversals();
1361 }
1362 }
1363
1364 public void requestTransparentRegion(View child) {
1365 // the test below should not fail unless someone is messing with us
1366 checkThread();
1367 if (mView == child) {
1368 mView.mPrivateFlags |= View.REQUEST_TRANSPARENT_REGIONS;
1369 // Need to make sure we re-evaluate the window attributes next
1370 // time around, to ensure the window has the correct format.
1371 mWindowAttributesChanged = true;
Mathias Agopian1bd80ad2010-11-04 17:13:39 -07001372 requestLayout();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001373 }
1374 }
1375
1376 /**
1377 * Figures out the measure spec for the root view in a window based on it's
1378 * layout params.
1379 *
1380 * @param windowSize
1381 * The available width or height of the window
1382 *
1383 * @param rootDimension
1384 * The layout params for one dimension (width or height) of the
1385 * window.
1386 *
1387 * @return The measure spec to use to measure the root view.
1388 */
1389 private int getRootMeasureSpec(int windowSize, int rootDimension) {
1390 int measureSpec;
1391 switch (rootDimension) {
1392
Romain Guy980a9382010-01-08 15:06:28 -08001393 case ViewGroup.LayoutParams.MATCH_PARENT:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001394 // Window can't resize. Force root view to be windowSize.
1395 measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.EXACTLY);
1396 break;
1397 case ViewGroup.LayoutParams.WRAP_CONTENT:
1398 // Window can resize. Set max size for root view.
1399 measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.AT_MOST);
1400 break;
1401 default:
1402 // Window wants to be an exact size. Force root view to be that size.
1403 measureSpec = MeasureSpec.makeMeasureSpec(rootDimension, MeasureSpec.EXACTLY);
1404 break;
1405 }
1406 return measureSpec;
1407 }
1408
Dianne Hackborn0f761d62010-11-30 22:06:10 -08001409 int mHardwareYOffset;
1410 int mResizeAlpha;
1411 final Paint mResizePaint = new Paint();
1412
1413 public void onHardwarePreDraw(Canvas canvas) {
1414 canvas.translate(0, -mHardwareYOffset);
1415 }
1416
1417 public void onHardwarePostDraw(Canvas canvas) {
1418 if (mResizeBitmap != null) {
1419 canvas.translate(0, mHardwareYOffset);
1420 mResizePaint.setAlpha(mResizeAlpha);
1421 canvas.drawBitmap(mResizeBitmap, 0, 0, mResizePaint);
1422 }
1423 }
1424
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001425 private void draw(boolean fullRedrawNeeded) {
1426 Surface surface = mSurface;
1427 if (surface == null || !surface.isValid()) {
1428 return;
1429 }
1430
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001431 if (!sFirstDrawComplete) {
1432 synchronized (sFirstDrawHandlers) {
1433 sFirstDrawComplete = true;
Romain Guy812ccbe2010-06-01 14:07:24 -07001434 final int count = sFirstDrawHandlers.size();
1435 for (int i = 0; i< count; i++) {
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001436 post(sFirstDrawHandlers.get(i));
1437 }
1438 }
1439 }
1440
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001441 scrollToRectOrFocus(null, false);
1442
1443 if (mAttachInfo.mViewScrollChanged) {
1444 mAttachInfo.mViewScrollChanged = false;
1445 mAttachInfo.mTreeObserver.dispatchOnScrollChanged();
1446 }
Romain Guy8506ab42009-06-11 17:35:47 -07001447
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001448 int yoff;
Dianne Hackborn0f761d62010-11-30 22:06:10 -08001449 boolean animating = mScroller != null && mScroller.computeScrollOffset();
1450 if (animating) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001451 yoff = mScroller.getCurrY();
1452 } else {
1453 yoff = mScrollY;
1454 }
1455 if (mCurScrollY != yoff) {
1456 mCurScrollY = yoff;
1457 fullRedrawNeeded = true;
1458 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001459 float appScale = mAttachInfo.mApplicationScale;
1460 boolean scalingRequired = mAttachInfo.mScalingRequired;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001461
Dianne Hackborn0f761d62010-11-30 22:06:10 -08001462 int resizeAlpha = 0;
1463 if (mResizeBitmap != null) {
1464 long deltaTime = SystemClock.uptimeMillis() - mResizeBitmapStartTime;
1465 if (deltaTime < mResizeBitmapDuration) {
1466 float amt = deltaTime/(float)mResizeBitmapDuration;
1467 amt = mResizeInterpolator.getInterpolation(amt);
1468 animating = true;
1469 resizeAlpha = 255 - (int)(amt*255);
1470 } else {
1471 disposeResizeBitmap();
1472 }
1473 }
1474
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001475 Rect dirty = mDirty;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001476 if (mSurfaceHolder != null) {
1477 // The app owns the surface, we won't draw.
1478 dirty.setEmpty();
Dianne Hackborn0f761d62010-11-30 22:06:10 -08001479 if (animating) {
1480 if (mScroller != null) {
1481 mScroller.abortAnimation();
1482 }
1483 disposeResizeBitmap();
1484 }
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001485 return;
1486 }
Romain Guy58ef7fb2010-09-13 12:52:37 -07001487
1488 if (fullRedrawNeeded) {
1489 mAttachInfo.mIgnoreDirtyState = true;
1490 dirty.union(0, 0, (int) (mWidth * appScale + 0.5f), (int) (mHeight * appScale + 0.5f));
1491 }
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001492
Romain Guyb051e892010-09-28 19:09:36 -07001493 if (mAttachInfo.mHardwareRenderer != null && mAttachInfo.mHardwareRenderer.isEnabled()) {
Romain Guyfd507262010-10-10 15:42:49 -07001494 if (!dirty.isEmpty() || mIsAnimating) {
Romain Guy101e2ae2010-10-11 12:41:21 -07001495 mIsAnimating = false;
Romain Guyfd507262010-10-10 15:42:49 -07001496 dirty.setEmpty();
Dianne Hackborn0f761d62010-11-30 22:06:10 -08001497 mHardwareYOffset = yoff;
1498 mResizeAlpha = resizeAlpha;
1499 mAttachInfo.mHardwareRenderer.draw(mView, mAttachInfo, this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001500 }
Romain Guy812ccbe2010-06-01 14:07:24 -07001501
Dianne Hackborn0f761d62010-11-30 22:06:10 -08001502 if (animating) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001503 mFullRedrawNeeded = true;
1504 scheduleTraversals();
1505 }
Romain Guy812ccbe2010-06-01 14:07:24 -07001506
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001507 return;
1508 }
1509
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001510 if (DEBUG_ORIENTATION || DEBUG_DRAW) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001511 Log.v(TAG, "Draw " + mView + "/"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001512 + mWindowAttributes.getTitle()
1513 + ": dirty={" + dirty.left + "," + dirty.top
1514 + "," + dirty.right + "," + dirty.bottom + "} surface="
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001515 + surface + " surface.isValid()=" + surface.isValid() + ", appScale:" +
1516 appScale + ", width=" + mWidth + ", height=" + mHeight);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001517 }
1518
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001519 if (!dirty.isEmpty() || mIsAnimating) {
1520 Canvas canvas;
1521 try {
1522 int left = dirty.left;
1523 int top = dirty.top;
1524 int right = dirty.right;
1525 int bottom = dirty.bottom;
1526 canvas = surface.lockCanvas(dirty);
Romain Guy5bcdff42009-05-14 21:27:18 -07001527
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001528 if (left != dirty.left || top != dirty.top || right != dirty.right ||
1529 bottom != dirty.bottom) {
1530 mAttachInfo.mIgnoreDirtyState = true;
1531 }
1532
1533 // TODO: Do this in native
1534 canvas.setDensity(mDensity);
1535 } catch (Surface.OutOfResourcesException e) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001536 Log.e(TAG, "OutOfResourcesException locking surface", e);
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001537 // TODO: we should ask the window manager to do something!
1538 // for now we just do nothing
1539 return;
1540 } catch (IllegalArgumentException e) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001541 Log.e(TAG, "IllegalArgumentException locking surface", e);
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001542 // TODO: we should ask the window manager to do something!
1543 // for now we just do nothing
1544 return;
Romain Guy5bcdff42009-05-14 21:27:18 -07001545 }
1546
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001547 try {
1548 if (!dirty.isEmpty() || mIsAnimating) {
1549 long startTime = 0L;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001550
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001551 if (DEBUG_ORIENTATION || DEBUG_DRAW) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001552 Log.v(TAG, "Surface " + surface + " drawing to bitmap w="
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001553 + canvas.getWidth() + ", h=" + canvas.getHeight());
1554 //canvas.drawARGB(255, 255, 0, 0);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001555 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001556
Romain Guy5429e1d2010-09-07 12:38:00 -07001557 if (ViewDebug.DEBUG_PROFILE_DRAWING) {
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001558 startTime = SystemClock.elapsedRealtime();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001559 }
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001560
1561 // If this bitmap's format includes an alpha channel, we
1562 // need to clear it before drawing so that the child will
1563 // properly re-composite its drawing on a transparent
1564 // background. This automatically respects the clip/dirty region
1565 // or
1566 // If we are applying an offset, we need to clear the area
1567 // where the offset doesn't appear to avoid having garbage
1568 // left in the blank areas.
1569 if (!canvas.isOpaque() || yoff != 0) {
1570 canvas.drawColor(0, PorterDuff.Mode.CLEAR);
1571 }
1572
1573 dirty.setEmpty();
1574 mIsAnimating = false;
1575 mAttachInfo.mDrawingTime = SystemClock.uptimeMillis();
1576 mView.mPrivateFlags |= View.DRAWN;
1577
1578 if (DEBUG_DRAW) {
1579 Context cxt = mView.getContext();
1580 Log.i(TAG, "Drawing: package:" + cxt.getPackageName() +
1581 ", metrics=" + cxt.getResources().getDisplayMetrics() +
1582 ", compatibilityInfo=" + cxt.getResources().getCompatibilityInfo());
1583 }
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001584 try {
1585 canvas.translate(0, -yoff);
1586 if (mTranslator != null) {
1587 mTranslator.translateCanvas(canvas);
1588 }
1589 canvas.setScreenDensity(scalingRequired
1590 ? DisplayMetrics.DENSITY_DEVICE : 0);
1591 mView.draw(canvas);
1592 } finally {
1593 mAttachInfo.mIgnoreDirtyState = false;
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001594 }
1595
1596 if (Config.DEBUG && ViewDebug.consistencyCheckEnabled) {
1597 mView.dispatchConsistencyCheck(ViewDebug.CONSISTENCY_DRAWING);
1598 }
1599
Romain Guy5429e1d2010-09-07 12:38:00 -07001600 if (SHOW_FPS || ViewDebug.DEBUG_SHOW_FPS) {
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001601 int now = (int)SystemClock.elapsedRealtime();
1602 if (sDrawTime != 0) {
1603 nativeShowFPS(canvas, now - sDrawTime);
1604 }
1605 sDrawTime = now;
1606 }
1607
Romain Guy5429e1d2010-09-07 12:38:00 -07001608 if (ViewDebug.DEBUG_PROFILE_DRAWING) {
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001609 EventLog.writeEvent(60000, SystemClock.elapsedRealtime() - startTime);
1610 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001611 }
1612
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001613 } finally {
1614 surface.unlockCanvasAndPost(canvas);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001615 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001616 }
1617
1618 if (LOCAL_LOGV) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001619 Log.v(TAG, "Surface " + surface + " unlockCanvasAndPost");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001620 }
Romain Guy8506ab42009-06-11 17:35:47 -07001621
Dianne Hackborn0f761d62010-11-30 22:06:10 -08001622 if (animating) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001623 mFullRedrawNeeded = true;
1624 scheduleTraversals();
1625 }
1626 }
1627
1628 boolean scrollToRectOrFocus(Rect rectangle, boolean immediate) {
1629 final View.AttachInfo attachInfo = mAttachInfo;
1630 final Rect ci = attachInfo.mContentInsets;
1631 final Rect vi = attachInfo.mVisibleInsets;
1632 int scrollY = 0;
1633 boolean handled = false;
Romain Guy8506ab42009-06-11 17:35:47 -07001634
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001635 if (vi.left > ci.left || vi.top > ci.top
1636 || vi.right > ci.right || vi.bottom > ci.bottom) {
1637 // We'll assume that we aren't going to change the scroll
1638 // offset, since we want to avoid that unless it is actually
1639 // going to make the focus visible... otherwise we scroll
1640 // all over the place.
1641 scrollY = mScrollY;
1642 // We can be called for two different situations: during a draw,
1643 // to update the scroll position if the focus has changed (in which
1644 // case 'rectangle' is null), or in response to a
1645 // requestChildRectangleOnScreen() call (in which case 'rectangle'
1646 // is non-null and we just want to scroll to whatever that
1647 // rectangle is).
1648 View focus = mRealFocusedView;
Romain Guye8b16522009-07-14 13:06:42 -07001649
1650 // When in touch mode, focus points to the previously focused view,
1651 // which may have been removed from the view hierarchy. The following
Joe Onoratob71193b2009-11-24 18:34:42 -05001652 // line checks whether the view is still in our hierarchy.
1653 if (focus == null || focus.mAttachInfo != mAttachInfo) {
Romain Guye8b16522009-07-14 13:06:42 -07001654 mRealFocusedView = null;
1655 return false;
1656 }
1657
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001658 if (focus != mLastScrolledFocus) {
1659 // If the focus has changed, then ignore any requests to scroll
1660 // to a rectangle; first we want to make sure the entire focus
1661 // view is visible.
1662 rectangle = null;
1663 }
1664 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Eval scroll: focus=" + focus
1665 + " rectangle=" + rectangle + " ci=" + ci
1666 + " vi=" + vi);
1667 if (focus == mLastScrolledFocus && !mScrollMayChange
1668 && rectangle == null) {
1669 // Optimization: if the focus hasn't changed since last
1670 // time, and no layout has happened, then just leave things
1671 // as they are.
1672 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Keeping scroll y="
1673 + mScrollY + " vi=" + vi.toShortString());
1674 } else if (focus != null) {
1675 // We need to determine if the currently focused view is
1676 // within the visible part of the window and, if not, apply
1677 // a pan so it can be seen.
1678 mLastScrolledFocus = focus;
1679 mScrollMayChange = false;
1680 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Need to scroll?");
1681 // Try to find the rectangle from the focus view.
1682 if (focus.getGlobalVisibleRect(mVisRect, null)) {
1683 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Root w="
1684 + mView.getWidth() + " h=" + mView.getHeight()
1685 + " ci=" + ci.toShortString()
1686 + " vi=" + vi.toShortString());
1687 if (rectangle == null) {
1688 focus.getFocusedRect(mTempRect);
1689 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Focus " + focus
1690 + ": focusRect=" + mTempRect.toShortString());
Dianne Hackborn1c6a8942010-03-23 16:34:20 -07001691 if (mView instanceof ViewGroup) {
1692 ((ViewGroup) mView).offsetDescendantRectToMyCoords(
1693 focus, mTempRect);
1694 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001695 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1696 "Focus in window: focusRect="
1697 + mTempRect.toShortString()
1698 + " visRect=" + mVisRect.toShortString());
1699 } else {
1700 mTempRect.set(rectangle);
1701 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1702 "Request scroll to rect: "
1703 + mTempRect.toShortString()
1704 + " visRect=" + mVisRect.toShortString());
1705 }
1706 if (mTempRect.intersect(mVisRect)) {
1707 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1708 "Focus window visible rect: "
1709 + mTempRect.toShortString());
1710 if (mTempRect.height() >
1711 (mView.getHeight()-vi.top-vi.bottom)) {
1712 // If the focus simply is not going to fit, then
1713 // best is probably just to leave things as-is.
1714 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1715 "Too tall; leaving scrollY=" + scrollY);
1716 } else if ((mTempRect.top-scrollY) < vi.top) {
1717 scrollY -= vi.top - (mTempRect.top-scrollY);
1718 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1719 "Top covered; scrollY=" + scrollY);
1720 } else if ((mTempRect.bottom-scrollY)
1721 > (mView.getHeight()-vi.bottom)) {
1722 scrollY += (mTempRect.bottom-scrollY)
1723 - (mView.getHeight()-vi.bottom);
1724 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1725 "Bottom covered; scrollY=" + scrollY);
1726 }
1727 handled = true;
1728 }
1729 }
1730 }
1731 }
Romain Guy8506ab42009-06-11 17:35:47 -07001732
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001733 if (scrollY != mScrollY) {
1734 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Pan scroll changed: old="
1735 + mScrollY + " , new=" + scrollY);
Dianne Hackborn0f761d62010-11-30 22:06:10 -08001736 if (!immediate && mResizeBitmap == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001737 if (mScroller == null) {
1738 mScroller = new Scroller(mView.getContext());
1739 }
1740 mScroller.startScroll(0, mScrollY, 0, scrollY-mScrollY);
1741 } else if (mScroller != null) {
1742 mScroller.abortAnimation();
1743 }
1744 mScrollY = scrollY;
1745 }
Romain Guy8506ab42009-06-11 17:35:47 -07001746
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001747 return handled;
1748 }
Romain Guy8506ab42009-06-11 17:35:47 -07001749
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001750 public void requestChildFocus(View child, View focused) {
1751 checkThread();
1752 if (mFocusedView != focused) {
1753 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(mFocusedView, focused);
1754 scheduleTraversals();
1755 }
1756 mFocusedView = mRealFocusedView = focused;
1757 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Request child focus: focus now "
1758 + mFocusedView);
1759 }
1760
1761 public void clearChildFocus(View child) {
1762 checkThread();
1763
1764 View oldFocus = mFocusedView;
1765
1766 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Clearing child focus");
1767 mFocusedView = mRealFocusedView = null;
1768 if (mView != null && !mView.hasFocus()) {
1769 // If a view gets the focus, the listener will be invoked from requestChildFocus()
1770 if (!mView.requestFocus(View.FOCUS_FORWARD)) {
1771 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
1772 }
1773 } else if (oldFocus != null) {
1774 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
1775 }
1776 }
1777
1778
1779 public void focusableViewAvailable(View v) {
1780 checkThread();
1781
1782 if (mView != null && !mView.hasFocus()) {
1783 v.requestFocus();
1784 } else {
1785 // the one case where will transfer focus away from the current one
1786 // is if the current view is a view group that prefers to give focus
1787 // to its children first AND the view is a descendant of it.
1788 mFocusedView = mView.findFocus();
1789 boolean descendantsHaveDibsOnFocus =
1790 (mFocusedView instanceof ViewGroup) &&
1791 (((ViewGroup) mFocusedView).getDescendantFocusability() ==
1792 ViewGroup.FOCUS_AFTER_DESCENDANTS);
1793 if (descendantsHaveDibsOnFocus && isViewDescendantOf(v, mFocusedView)) {
1794 // If a view gets the focus, the listener will be invoked from requestChildFocus()
1795 v.requestFocus();
1796 }
1797 }
1798 }
1799
1800 public void recomputeViewAttributes(View child) {
1801 checkThread();
1802 if (mView == child) {
1803 mAttachInfo.mRecomputeGlobalAttributes = true;
1804 if (!mWillDrawSoon) {
1805 scheduleTraversals();
1806 }
1807 }
1808 }
1809
1810 void dispatchDetachedFromWindow() {
Romain Guy90fc03b2011-01-16 13:07:15 -08001811 if (mView != null && mView.mAttachInfo != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001812 mView.dispatchDetachedFromWindow();
1813 }
1814
1815 mView = null;
1816 mAttachInfo.mRootView = null;
Mathias Agopian5583dc62009-07-09 16:28:11 -07001817 mAttachInfo.mSurface = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001818
Romain Guy29d89972010-09-22 16:10:57 -07001819 destroyHardwareRenderer();
Romain Guy4caa4ed2010-08-25 14:46:24 -07001820
Dianne Hackborn0586a1b2009-09-06 21:08:27 -07001821 mSurface.release();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001822
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001823 if (mInputChannel != null) {
1824 if (mInputQueueCallback != null) {
1825 mInputQueueCallback.onInputQueueDestroyed(mInputQueue);
1826 mInputQueueCallback = null;
1827 } else {
1828 InputQueue.unregisterInputChannel(mInputChannel);
Jeff Brown46b9ac02010-04-22 18:58:52 -07001829 }
1830 }
1831
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001832 try {
1833 sWindowSession.remove(mWindow);
1834 } catch (RemoteException e) {
1835 }
Jeff Brown349703e2010-06-22 01:27:15 -07001836
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001837 // Dispose the input channel after removing the window so the Window Manager
1838 // doesn't interpret the input channel being closed as an abnormal termination.
1839 if (mInputChannel != null) {
1840 mInputChannel.dispose();
1841 mInputChannel = null;
Jeff Brown349703e2010-06-22 01:27:15 -07001842 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001843 }
Romain Guy8506ab42009-06-11 17:35:47 -07001844
Dianne Hackborn694f79b2010-03-17 19:44:59 -07001845 void updateConfiguration(Configuration config, boolean force) {
1846 if (DEBUG_CONFIGURATION) Log.v(TAG,
1847 "Applying new config to window "
1848 + mWindowAttributes.getTitle()
1849 + ": " + config);
1850 synchronized (sConfigCallbacks) {
1851 for (int i=sConfigCallbacks.size()-1; i>=0; i--) {
1852 sConfigCallbacks.get(i).onConfigurationChanged(config);
1853 }
1854 }
1855 if (mView != null) {
1856 // At this point the resources have been updated to
1857 // have the most recent config, whatever that is. Use
1858 // the on in them which may be newer.
1859 if (mView != null) {
1860 config = mView.getResources().getConfiguration();
1861 }
1862 if (force || mLastConfiguration.diff(config) != 0) {
1863 mLastConfiguration.setTo(config);
1864 mView.dispatchConfigurationChanged(config);
1865 }
1866 }
1867 }
1868
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001869 /**
1870 * Return true if child is an ancestor of parent, (or equal to the parent).
1871 */
1872 private static boolean isViewDescendantOf(View child, View parent) {
1873 if (child == parent) {
1874 return true;
1875 }
1876
1877 final ViewParent theParent = child.getParent();
1878 return (theParent instanceof ViewGroup) && isViewDescendantOf((View) theParent, parent);
1879 }
1880
Romain Guycdb86672010-03-18 18:54:50 -07001881 private static void forceLayout(View view) {
1882 view.forceLayout();
1883 if (view instanceof ViewGroup) {
1884 ViewGroup group = (ViewGroup) view;
1885 final int count = group.getChildCount();
1886 for (int i = 0; i < count; i++) {
1887 forceLayout(group.getChildAt(i));
1888 }
1889 }
1890 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001891
1892 public final static int DO_TRAVERSAL = 1000;
1893 public final static int DIE = 1001;
1894 public final static int RESIZED = 1002;
1895 public final static int RESIZED_REPORT = 1003;
1896 public final static int WINDOW_FOCUS_CHANGED = 1004;
1897 public final static int DISPATCH_KEY = 1005;
1898 public final static int DISPATCH_POINTER = 1006;
1899 public final static int DISPATCH_TRACKBALL = 1007;
1900 public final static int DISPATCH_APP_VISIBILITY = 1008;
1901 public final static int DISPATCH_GET_NEW_SURFACE = 1009;
1902 public final static int FINISHED_EVENT = 1010;
1903 public final static int DISPATCH_KEY_FROM_IME = 1011;
1904 public final static int FINISH_INPUT_CONNECTION = 1012;
1905 public final static int CHECK_FOCUS = 1013;
Dianne Hackbornffa42482009-09-23 22:20:11 -07001906 public final static int CLOSE_SYSTEM_DIALOGS = 1014;
Christopher Tatea53146c2010-09-07 11:57:52 -07001907 public final static int DISPATCH_DRAG_EVENT = 1015;
Chris Tate91e9bb32010-10-12 12:58:43 -07001908 public final static int DISPATCH_DRAG_LOCATION_EVENT = 1016;
Joe Onorato664644d2011-01-23 17:53:23 -08001909 public final static int DISPATCH_SYSTEM_UI_VISIBILITY = 1017;
Joe Onorato10f41262011-01-24 13:16:08 -08001910 public final static int DISPATCH_GENERIC_MOTION = 1018;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001911
1912 @Override
1913 public void handleMessage(Message msg) {
1914 switch (msg.what) {
1915 case View.AttachInfo.INVALIDATE_MSG:
1916 ((View) msg.obj).invalidate();
1917 break;
1918 case View.AttachInfo.INVALIDATE_RECT_MSG:
1919 final View.AttachInfo.InvalidateInfo info = (View.AttachInfo.InvalidateInfo) msg.obj;
1920 info.target.invalidate(info.left, info.top, info.right, info.bottom);
1921 info.release();
1922 break;
1923 case DO_TRAVERSAL:
1924 if (mProfile) {
1925 Debug.startMethodTracing("ViewRoot");
1926 }
1927
1928 performTraversals();
1929
1930 if (mProfile) {
1931 Debug.stopMethodTracing();
1932 mProfile = false;
1933 }
1934 break;
1935 case FINISHED_EVENT:
1936 handleFinishedEvent(msg.arg1, msg.arg2 != 0);
1937 break;
1938 case DISPATCH_KEY:
Jeff Brown92ff1dd2010-08-11 16:16:06 -07001939 deliverKeyEvent((KeyEvent)msg.obj, msg.arg1 != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001940 break;
Jeff Brown3915bb82010-11-05 15:02:16 -07001941 case DISPATCH_POINTER:
1942 deliverPointerEvent((MotionEvent) msg.obj, msg.arg1 != 0);
1943 break;
1944 case DISPATCH_TRACKBALL:
1945 deliverTrackballEvent((MotionEvent) msg.obj, msg.arg1 != 0);
1946 break;
Jeff Browncb1404e2011-01-15 18:14:15 -08001947 case DISPATCH_GENERIC_MOTION:
1948 deliverGenericMotionEvent((MotionEvent) msg.obj, msg.arg1 != 0);
1949 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001950 case DISPATCH_APP_VISIBILITY:
1951 handleAppVisibility(msg.arg1 != 0);
1952 break;
1953 case DISPATCH_GET_NEW_SURFACE:
1954 handleGetNewSurface();
1955 break;
1956 case RESIZED:
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001957 ResizedInfo ri = (ResizedInfo)msg.obj;
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001958
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001959 if (mWinFrame.width() == msg.arg1 && mWinFrame.height() == msg.arg2
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001960 && mPendingContentInsets.equals(ri.coveredInsets)
Dianne Hackbornd49258f2010-03-26 00:44:29 -07001961 && mPendingVisibleInsets.equals(ri.visibleInsets)
1962 && ((ResizedInfo)msg.obj).newConfig == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001963 break;
1964 }
1965 // fall through...
1966 case RESIZED_REPORT:
1967 if (mAdded) {
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001968 Configuration config = ((ResizedInfo)msg.obj).newConfig;
1969 if (config != null) {
Dianne Hackborn694f79b2010-03-17 19:44:59 -07001970 updateConfiguration(config, false);
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001971 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001972 mWinFrame.left = 0;
1973 mWinFrame.right = msg.arg1;
1974 mWinFrame.top = 0;
1975 mWinFrame.bottom = msg.arg2;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001976 mPendingContentInsets.set(((ResizedInfo)msg.obj).coveredInsets);
1977 mPendingVisibleInsets.set(((ResizedInfo)msg.obj).visibleInsets);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001978 if (msg.what == RESIZED_REPORT) {
1979 mReportNextDraw = true;
1980 }
Romain Guycdb86672010-03-18 18:54:50 -07001981
1982 if (mView != null) {
1983 forceLayout(mView);
1984 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001985 requestLayout();
1986 }
1987 break;
1988 case WINDOW_FOCUS_CHANGED: {
1989 if (mAdded) {
1990 boolean hasWindowFocus = msg.arg1 != 0;
1991 mAttachInfo.mHasWindowFocus = hasWindowFocus;
1992 if (hasWindowFocus) {
1993 boolean inTouchMode = msg.arg2 != 0;
Romain Guy2d4cff62010-04-09 15:39:00 -07001994 ensureTouchModeLocally(inTouchMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001995
Romain Guyc361da82010-10-25 15:29:10 -07001996 if (mAttachInfo.mHardwareRenderer != null &&
1997 mSurface != null && mSurface.isValid()) {
Romain Guyb051e892010-09-28 19:09:36 -07001998 mAttachInfo.mHardwareRenderer.initializeIfNeeded(mWidth, mHeight,
1999 mAttachInfo, mHolder);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002000 }
2001 }
Romain Guy8506ab42009-06-11 17:35:47 -07002002
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002003 mLastWasImTarget = WindowManager.LayoutParams
2004 .mayUseInputMethod(mWindowAttributes.flags);
Romain Guy8506ab42009-06-11 17:35:47 -07002005
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002006 InputMethodManager imm = InputMethodManager.peekInstance();
2007 if (mView != null) {
2008 if (hasWindowFocus && imm != null && mLastWasImTarget) {
2009 imm.startGettingWindowFocus(mView);
2010 }
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07002011 mAttachInfo.mKeyDispatchState.reset();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002012 mView.dispatchWindowFocusChanged(hasWindowFocus);
2013 }
svetoslavganov75986cf2009-05-14 22:28:01 -07002014
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002015 // Note: must be done after the focus change callbacks,
2016 // so all of the view state is set up correctly.
2017 if (hasWindowFocus) {
2018 if (imm != null && mLastWasImTarget) {
2019 imm.onWindowFocus(mView, mView.findFocus(),
2020 mWindowAttributes.softInputMode,
2021 !mHasHadWindowFocus, mWindowAttributes.flags);
2022 }
2023 // Clear the forward bit. We can just do this directly, since
2024 // the window manager doesn't care about it.
2025 mWindowAttributes.softInputMode &=
2026 ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
2027 ((WindowManager.LayoutParams)mView.getLayoutParams())
2028 .softInputMode &=
2029 ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
2030 mHasHadWindowFocus = true;
2031 }
svetoslavganov75986cf2009-05-14 22:28:01 -07002032
2033 if (hasWindowFocus && mView != null) {
2034 sendAccessibilityEvents();
2035 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002036 }
2037 } break;
2038 case DIE:
Dianne Hackborn94d69142009-09-28 22:14:42 -07002039 doDie();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002040 break;
The Android Open Source Project10592532009-03-18 17:39:46 -07002041 case DISPATCH_KEY_FROM_IME: {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002042 if (LOCAL_LOGV) Log.v(
Jeff Brownc5ed5912010-07-14 18:48:53 -07002043 TAG, "Dispatching key "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002044 + msg.obj + " from IME to " + mView);
The Android Open Source Project10592532009-03-18 17:39:46 -07002045 KeyEvent event = (KeyEvent)msg.obj;
2046 if ((event.getFlags()&KeyEvent.FLAG_FROM_SYSTEM) != 0) {
2047 // The IME is trying to say this event is from the
2048 // system! Bad bad bad!
Romain Guy812ccbe2010-06-01 14:07:24 -07002049 event = KeyEvent.changeFlags(event, event.getFlags() & ~KeyEvent.FLAG_FROM_SYSTEM);
The Android Open Source Project10592532009-03-18 17:39:46 -07002050 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002051 deliverKeyEventPostIme((KeyEvent)msg.obj, false);
The Android Open Source Project10592532009-03-18 17:39:46 -07002052 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002053 case FINISH_INPUT_CONNECTION: {
2054 InputMethodManager imm = InputMethodManager.peekInstance();
2055 if (imm != null) {
2056 imm.reportFinishInputConnection((InputConnection)msg.obj);
2057 }
2058 } break;
2059 case CHECK_FOCUS: {
2060 InputMethodManager imm = InputMethodManager.peekInstance();
2061 if (imm != null) {
2062 imm.checkFocus();
2063 }
2064 } break;
Dianne Hackbornffa42482009-09-23 22:20:11 -07002065 case CLOSE_SYSTEM_DIALOGS: {
2066 if (mView != null) {
2067 mView.onCloseSystemDialogs((String)msg.obj);
2068 }
2069 } break;
Chris Tate91e9bb32010-10-12 12:58:43 -07002070 case DISPATCH_DRAG_EVENT:
2071 case DISPATCH_DRAG_LOCATION_EVENT: {
Christopher Tate7fb8b562011-01-20 13:46:41 -08002072 DragEvent event = (DragEvent)msg.obj;
2073 event.mLocalState = mLocalDragState; // only present when this app called startDrag()
2074 handleDragEvent(event);
Christopher Tatea53146c2010-09-07 11:57:52 -07002075 } break;
Joe Onorato664644d2011-01-23 17:53:23 -08002076 case DISPATCH_SYSTEM_UI_VISIBILITY: {
2077 handleDispatchSystemUiVisibilityChanged(msg.arg1);
2078 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002079 }
2080 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002081
Jeff Brown3915bb82010-11-05 15:02:16 -07002082 private void startInputEvent(InputQueue.FinishedCallback finishedCallback) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07002083 if (mFinishedCallback != null) {
2084 Slog.w(TAG, "Received a new input event from the input queue but there is "
2085 + "already an unfinished input event in progress.");
2086 }
2087
2088 mFinishedCallback = finishedCallback;
2089 }
2090
Jeff Brown3915bb82010-11-05 15:02:16 -07002091 private void finishInputEvent(boolean handled) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07002092 if (LOCAL_LOGV) Log.v(TAG, "Telling window manager input event is finished");
Jeff Brown92ff1dd2010-08-11 16:16:06 -07002093
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002094 if (mFinishedCallback != null) {
Jeff Brown3915bb82010-11-05 15:02:16 -07002095 mFinishedCallback.finished(handled);
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002096 mFinishedCallback = null;
Jeff Brown92ff1dd2010-08-11 16:16:06 -07002097 } else {
Jeff Brown93ed4e32010-09-23 13:51:48 -07002098 Slog.w(TAG, "Attempted to tell the input queue that the current input event "
2099 + "is finished but there is no input event actually in progress.");
Jeff Brown46b9ac02010-04-22 18:58:52 -07002100 }
2101 }
2102
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002103 /**
2104 * Something in the current window tells us we need to change the touch mode. For
2105 * example, we are not in touch mode, and the user touches the screen.
2106 *
2107 * If the touch mode has changed, tell the window manager, and handle it locally.
2108 *
2109 * @param inTouchMode Whether we want to be in touch mode.
2110 * @return True if the touch mode changed and focus changed was changed as a result
2111 */
2112 boolean ensureTouchMode(boolean inTouchMode) {
2113 if (DBG) Log.d("touchmode", "ensureTouchMode(" + inTouchMode + "), current "
2114 + "touch mode is " + mAttachInfo.mInTouchMode);
2115 if (mAttachInfo.mInTouchMode == inTouchMode) return false;
2116
2117 // tell the window manager
2118 try {
2119 sWindowSession.setInTouchMode(inTouchMode);
2120 } catch (RemoteException e) {
2121 throw new RuntimeException(e);
2122 }
2123
2124 // handle the change
Romain Guy2d4cff62010-04-09 15:39:00 -07002125 return ensureTouchModeLocally(inTouchMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002126 }
2127
2128 /**
2129 * Ensure that the touch mode for this window is set, and if it is changing,
2130 * take the appropriate action.
2131 * @param inTouchMode Whether we want to be in touch mode.
2132 * @return True if the touch mode changed and focus changed was changed as a result
2133 */
Romain Guy2d4cff62010-04-09 15:39:00 -07002134 private boolean ensureTouchModeLocally(boolean inTouchMode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002135 if (DBG) Log.d("touchmode", "ensureTouchModeLocally(" + inTouchMode + "), current "
2136 + "touch mode is " + mAttachInfo.mInTouchMode);
2137
2138 if (mAttachInfo.mInTouchMode == inTouchMode) return false;
2139
2140 mAttachInfo.mInTouchMode = inTouchMode;
2141 mAttachInfo.mTreeObserver.dispatchOnTouchModeChanged(inTouchMode);
2142
Romain Guy2d4cff62010-04-09 15:39:00 -07002143 return (inTouchMode) ? enterTouchMode() : leaveTouchMode();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002144 }
2145
2146 private boolean enterTouchMode() {
2147 if (mView != null) {
2148 if (mView.hasFocus()) {
2149 // note: not relying on mFocusedView here because this could
2150 // be when the window is first being added, and mFocused isn't
2151 // set yet.
2152 final View focused = mView.findFocus();
2153 if (focused != null && !focused.isFocusableInTouchMode()) {
2154
2155 final ViewGroup ancestorToTakeFocus =
2156 findAncestorToTakeFocusInTouchMode(focused);
2157 if (ancestorToTakeFocus != null) {
2158 // there is an ancestor that wants focus after its descendants that
2159 // is focusable in touch mode.. give it focus
2160 return ancestorToTakeFocus.requestFocus();
2161 } else {
2162 // nothing appropriate to have focus in touch mode, clear it out
2163 mView.unFocus();
2164 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(focused, null);
2165 mFocusedView = null;
2166 return true;
2167 }
2168 }
2169 }
2170 }
2171 return false;
2172 }
2173
2174
2175 /**
2176 * Find an ancestor of focused that wants focus after its descendants and is
2177 * focusable in touch mode.
2178 * @param focused The currently focused view.
2179 * @return An appropriate view, or null if no such view exists.
2180 */
2181 private ViewGroup findAncestorToTakeFocusInTouchMode(View focused) {
2182 ViewParent parent = focused.getParent();
2183 while (parent instanceof ViewGroup) {
2184 final ViewGroup vgParent = (ViewGroup) parent;
2185 if (vgParent.getDescendantFocusability() == ViewGroup.FOCUS_AFTER_DESCENDANTS
2186 && vgParent.isFocusableInTouchMode()) {
2187 return vgParent;
2188 }
2189 if (vgParent.isRootNamespace()) {
2190 return null;
2191 } else {
2192 parent = vgParent.getParent();
2193 }
2194 }
2195 return null;
2196 }
2197
2198 private boolean leaveTouchMode() {
2199 if (mView != null) {
2200 if (mView.hasFocus()) {
2201 // i learned the hard way to not trust mFocusedView :)
2202 mFocusedView = mView.findFocus();
2203 if (!(mFocusedView instanceof ViewGroup)) {
2204 // some view has focus, let it keep it
2205 return false;
2206 } else if (((ViewGroup)mFocusedView).getDescendantFocusability() !=
2207 ViewGroup.FOCUS_AFTER_DESCENDANTS) {
2208 // some view group has focus, and doesn't prefer its children
2209 // over itself for focus, so let them keep it.
2210 return false;
2211 }
2212 }
2213
2214 // find the best view to give focus to in this brave new non-touch-mode
2215 // world
2216 final View focused = focusSearch(null, View.FOCUS_DOWN);
2217 if (focused != null) {
2218 return focused.requestFocus(View.FOCUS_DOWN);
2219 }
2220 }
2221 return false;
2222 }
2223
Jeff Brown3915bb82010-11-05 15:02:16 -07002224 private void deliverPointerEvent(MotionEvent event, boolean sendDone) {
2225 // If there is no view, then the event will not be handled.
2226 if (mView == null || !mAdded) {
2227 finishPointerEvent(event, sendDone, false);
2228 return;
2229 }
2230
2231 // Translate the pointer event for compatibility, if needed.
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002232 if (mTranslator != null) {
2233 mTranslator.translateEventInScreenToAppWindow(event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002234 }
2235
Jeff Brown3915bb82010-11-05 15:02:16 -07002236 // Enter touch mode on the down.
2237 boolean isDown = event.getAction() == MotionEvent.ACTION_DOWN;
2238 if (isDown) {
2239 ensureTouchMode(true);
2240 }
2241 if(Config.LOGV) {
2242 captureMotionLog("captureDispatchPointer", event);
2243 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002244
Jeff Brown3915bb82010-11-05 15:02:16 -07002245 // Offset the scroll position.
2246 if (mCurScrollY != 0) {
2247 event.offsetLocation(0, mCurScrollY);
2248 }
2249 if (MEASURE_LATENCY) {
2250 lt.sample("A Dispatching TouchEvents", System.nanoTime() - event.getEventTimeNano());
2251 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002252
Jeff Brown3915bb82010-11-05 15:02:16 -07002253 // Remember the touch position for possible drag-initiation.
2254 mLastTouchPoint.x = event.getRawX();
2255 mLastTouchPoint.y = event.getRawY();
2256
2257 // Dispatch touch to view hierarchy.
2258 boolean handled = mView.dispatchTouchEvent(event);
2259 if (MEASURE_LATENCY) {
2260 lt.sample("B Dispatched TouchEvents ", System.nanoTime() - event.getEventTimeNano());
2261 }
2262 if (handled) {
2263 finishPointerEvent(event, sendDone, true);
2264 return;
2265 }
2266
2267 // Apply edge slop and try again, if appropriate.
2268 final int edgeFlags = event.getEdgeFlags();
2269 if (edgeFlags != 0 && mView instanceof ViewGroup) {
2270 final int edgeSlop = mViewConfiguration.getScaledEdgeSlop();
2271 int direction = View.FOCUS_UP;
2272 int x = (int)event.getX();
2273 int y = (int)event.getY();
2274 final int[] deltas = new int[2];
2275
2276 if ((edgeFlags & MotionEvent.EDGE_TOP) != 0) {
2277 direction = View.FOCUS_DOWN;
2278 if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
2279 deltas[0] = edgeSlop;
2280 x += edgeSlop;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002281 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
Jeff Brown3915bb82010-11-05 15:02:16 -07002282 deltas[0] = -edgeSlop;
2283 x -= edgeSlop;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002284 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002285 } else if ((edgeFlags & MotionEvent.EDGE_BOTTOM) != 0) {
2286 direction = View.FOCUS_UP;
2287 if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
2288 deltas[0] = edgeSlop;
2289 x += edgeSlop;
2290 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
2291 deltas[0] = -edgeSlop;
2292 x -= edgeSlop;
2293 }
2294 } else if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
2295 direction = View.FOCUS_RIGHT;
2296 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
2297 direction = View.FOCUS_LEFT;
2298 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002299
Jeff Brown3915bb82010-11-05 15:02:16 -07002300 View nearest = FocusFinder.getInstance().findNearestTouchable(
2301 ((ViewGroup) mView), x, y, direction, deltas);
2302 if (nearest != null) {
2303 event.offsetLocation(deltas[0], deltas[1]);
2304 event.setEdgeFlags(0);
2305 if (mView.dispatchTouchEvent(event)) {
2306 finishPointerEvent(event, sendDone, true);
2307 return;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002308 }
2309 }
2310 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002311
2312 // Pointer event was unhandled.
2313 finishPointerEvent(event, sendDone, false);
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002314 }
2315
Jeff Brown3915bb82010-11-05 15:02:16 -07002316 private void finishPointerEvent(MotionEvent event, boolean sendDone, boolean handled) {
2317 event.recycle();
2318 if (sendDone) {
2319 finishInputEvent(handled);
2320 }
2321 if (LOCAL_LOGV || WATCH_POINTER) Log.i(TAG, "Done dispatching!");
2322 }
2323
2324 private void deliverTrackballEvent(MotionEvent event, boolean sendDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002325 if (DEBUG_TRACKBALL) Log.v(TAG, "Motion event:" + event);
2326
Jeff Brown3915bb82010-11-05 15:02:16 -07002327 // If there is no view, then the event will not be handled.
2328 if (mView == null || !mAdded) {
2329 finishTrackballEvent(event, sendDone, false);
2330 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002331 }
2332
Jeff Brown3915bb82010-11-05 15:02:16 -07002333 // Deliver the trackball event to the view.
2334 if (mView.dispatchTrackballEvent(event)) {
2335 // If we reach this, we delivered a trackball event to mView and
2336 // mView consumed it. Because we will not translate the trackball
2337 // event into a key event, touch mode will not exit, so we exit
2338 // touch mode here.
2339 ensureTouchMode(false);
2340
2341 finishTrackballEvent(event, sendDone, true);
2342 mLastTrackballTime = Integer.MIN_VALUE;
2343 return;
2344 }
2345
2346 // Translate the trackball event into DPAD keys and try to deliver those.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002347 final TrackballAxis x = mTrackballAxisX;
2348 final TrackballAxis y = mTrackballAxisY;
2349
2350 long curTime = SystemClock.uptimeMillis();
Jeff Brown3915bb82010-11-05 15:02:16 -07002351 if ((mLastTrackballTime + MAX_TRACKBALL_DELAY) < curTime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002352 // It has been too long since the last movement,
2353 // so restart at the beginning.
2354 x.reset(0);
2355 y.reset(0);
2356 mLastTrackballTime = curTime;
2357 }
2358
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002359 final int action = event.getAction();
Jeff Brown49ed71d2010-12-06 17:13:33 -08002360 final int metaState = event.getMetaState();
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002361 switch (action) {
2362 case MotionEvent.ACTION_DOWN:
2363 x.reset(2);
2364 y.reset(2);
2365 deliverKeyEvent(new KeyEvent(curTime, curTime,
Jeff Brown49ed71d2010-12-06 17:13:33 -08002366 KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_CENTER, 0, metaState,
2367 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
2368 InputDevice.SOURCE_KEYBOARD), false);
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002369 break;
2370 case MotionEvent.ACTION_UP:
2371 x.reset(2);
2372 y.reset(2);
2373 deliverKeyEvent(new KeyEvent(curTime, curTime,
Jeff Brown49ed71d2010-12-06 17:13:33 -08002374 KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_CENTER, 0, metaState,
2375 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
2376 InputDevice.SOURCE_KEYBOARD), false);
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002377 break;
2378 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002379
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002380 if (DEBUG_TRACKBALL) Log.v(TAG, "TB X=" + x.position + " step="
2381 + x.step + " dir=" + x.dir + " acc=" + x.acceleration
2382 + " move=" + event.getX()
2383 + " / Y=" + y.position + " step="
2384 + y.step + " dir=" + y.dir + " acc=" + y.acceleration
2385 + " move=" + event.getY());
2386 final float xOff = x.collect(event.getX(), event.getEventTime(), "X");
2387 final float yOff = y.collect(event.getY(), event.getEventTime(), "Y");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002388
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002389 // Generate DPAD events based on the trackball movement.
2390 // We pick the axis that has moved the most as the direction of
2391 // the DPAD. When we generate DPAD events for one axis, then the
2392 // other axis is reset -- we don't want to perform DPAD jumps due
2393 // to slight movements in the trackball when making major movements
2394 // along the other axis.
2395 int keycode = 0;
2396 int movement = 0;
2397 float accel = 1;
2398 if (xOff > yOff) {
2399 movement = x.generate((2/event.getXPrecision()));
2400 if (movement != 0) {
2401 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_RIGHT
2402 : KeyEvent.KEYCODE_DPAD_LEFT;
2403 accel = x.acceleration;
2404 y.reset(2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002405 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002406 } else if (yOff > 0) {
2407 movement = y.generate((2/event.getYPrecision()));
2408 if (movement != 0) {
2409 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_DOWN
2410 : KeyEvent.KEYCODE_DPAD_UP;
2411 accel = y.acceleration;
2412 x.reset(2);
2413 }
2414 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002415
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002416 if (keycode != 0) {
2417 if (movement < 0) movement = -movement;
2418 int accelMovement = (int)(movement * accel);
2419 if (DEBUG_TRACKBALL) Log.v(TAG, "Move: movement=" + movement
2420 + " accelMovement=" + accelMovement
2421 + " accel=" + accel);
2422 if (accelMovement > movement) {
2423 if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: "
2424 + keycode);
2425 movement--;
Jeff Brown49ed71d2010-12-06 17:13:33 -08002426 int repeatCount = accelMovement - movement;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002427 deliverKeyEvent(new KeyEvent(curTime, curTime,
Jeff Brown49ed71d2010-12-06 17:13:33 -08002428 KeyEvent.ACTION_MULTIPLE, keycode, repeatCount, metaState,
2429 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
2430 InputDevice.SOURCE_KEYBOARD), false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002431 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002432 while (movement > 0) {
2433 if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: "
2434 + keycode);
2435 movement--;
2436 curTime = SystemClock.uptimeMillis();
2437 deliverKeyEvent(new KeyEvent(curTime, curTime,
Jeff Brown49ed71d2010-12-06 17:13:33 -08002438 KeyEvent.ACTION_DOWN, keycode, 0, metaState,
2439 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
2440 InputDevice.SOURCE_KEYBOARD), false);
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002441 deliverKeyEvent(new KeyEvent(curTime, curTime,
Jeff Brown49ed71d2010-12-06 17:13:33 -08002442 KeyEvent.ACTION_UP, keycode, 0, metaState,
2443 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
2444 InputDevice.SOURCE_KEYBOARD), false);
2445 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002446 mLastTrackballTime = curTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002447 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002448
2449 // Unfortunately we can't tell whether the application consumed the keys, so
2450 // we always consider the trackball event handled.
2451 finishTrackballEvent(event, sendDone, true);
2452 }
2453
2454 private void finishTrackballEvent(MotionEvent event, boolean sendDone, boolean handled) {
2455 event.recycle();
2456 if (sendDone) {
2457 finishInputEvent(handled);
2458 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002459 }
2460
Jeff Browncb1404e2011-01-15 18:14:15 -08002461 private void deliverGenericMotionEvent(MotionEvent event, boolean sendDone) {
2462 final int source = event.getSource();
2463 final boolean isJoystick = (source & InputDevice.SOURCE_CLASS_JOYSTICK) != 0;
2464
2465 // If there is no view, then the event will not be handled.
2466 if (mView == null || !mAdded) {
2467 if (isJoystick) {
2468 updateJoystickDirection(event, false);
2469 }
2470 finishGenericMotionEvent(event, sendDone, false);
2471 return;
2472 }
2473
2474 // Deliver the event to the view.
2475 if (mView.dispatchGenericMotionEvent(event)) {
2476 ensureTouchMode(false);
2477 if (isJoystick) {
2478 updateJoystickDirection(event, false);
2479 }
2480 finishGenericMotionEvent(event, sendDone, true);
2481 return;
2482 }
2483
2484 if (isJoystick) {
2485 // Translate the joystick event into DPAD keys and try to deliver those.
2486 updateJoystickDirection(event, true);
2487 finishGenericMotionEvent(event, sendDone, true);
2488 } else {
2489 finishGenericMotionEvent(event, sendDone, false);
2490 }
2491 }
2492
2493 private void finishGenericMotionEvent(MotionEvent event, boolean sendDone, boolean handled) {
2494 event.recycle();
2495 if (sendDone) {
2496 finishInputEvent(handled);
2497 }
2498 }
2499
2500 private void updateJoystickDirection(MotionEvent event, boolean synthesizeNewKeys) {
2501 final long time = event.getEventTime();
2502 final int metaState = event.getMetaState();
2503 final int deviceId = event.getDeviceId();
2504 final int source = event.getSource();
2505 final int xDirection = joystickAxisValueToDirection(event.getX());
2506 final int yDirection = joystickAxisValueToDirection(event.getY());
2507
2508 if (xDirection != mLastJoystickXDirection) {
2509 if (mLastJoystickXKeyCode != 0) {
2510 deliverKeyEvent(new KeyEvent(time, time,
2511 KeyEvent.ACTION_UP, mLastJoystickXKeyCode, 0, metaState,
2512 deviceId, 0, KeyEvent.FLAG_FALLBACK, source), false);
2513 mLastJoystickXKeyCode = 0;
2514 }
2515
2516 mLastJoystickXDirection = xDirection;
2517
2518 if (xDirection != 0 && synthesizeNewKeys) {
2519 mLastJoystickXKeyCode = xDirection > 0
2520 ? KeyEvent.KEYCODE_DPAD_RIGHT : KeyEvent.KEYCODE_DPAD_LEFT;
2521 deliverKeyEvent(new KeyEvent(time, time,
2522 KeyEvent.ACTION_DOWN, mLastJoystickXKeyCode, 0, metaState,
2523 deviceId, 0, KeyEvent.FLAG_FALLBACK, source), false);
2524 }
2525 }
2526
2527 if (yDirection != mLastJoystickYDirection) {
2528 if (mLastJoystickYKeyCode != 0) {
2529 deliverKeyEvent(new KeyEvent(time, time,
2530 KeyEvent.ACTION_UP, mLastJoystickYKeyCode, 0, metaState,
2531 deviceId, 0, KeyEvent.FLAG_FALLBACK, source), false);
2532 mLastJoystickYKeyCode = 0;
2533 }
2534
2535 mLastJoystickYDirection = yDirection;
2536
2537 if (yDirection != 0 && synthesizeNewKeys) {
2538 mLastJoystickYKeyCode = yDirection > 0
2539 ? KeyEvent.KEYCODE_DPAD_DOWN : KeyEvent.KEYCODE_DPAD_UP;
2540 deliverKeyEvent(new KeyEvent(time, time,
2541 KeyEvent.ACTION_DOWN, mLastJoystickYKeyCode, 0, metaState,
2542 deviceId, 0, KeyEvent.FLAG_FALLBACK, source), false);
2543 }
2544 }
2545 }
2546
2547 private static int joystickAxisValueToDirection(float value) {
2548 if (value >= 0.5f) {
2549 return 1;
2550 } else if (value <= -0.5f) {
2551 return -1;
2552 } else {
2553 return 0;
2554 }
2555 }
2556
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002557 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08002558 * Returns true if the key is used for keyboard navigation.
2559 * @param keyEvent The key event.
2560 * @return True if the key is used for keyboard navigation.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002561 */
Jeff Brown4e6319b2010-12-13 10:36:51 -08002562 private static boolean isNavigationKey(KeyEvent keyEvent) {
2563 switch (keyEvent.getKeyCode()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002564 case KeyEvent.KEYCODE_DPAD_LEFT:
2565 case KeyEvent.KEYCODE_DPAD_RIGHT:
2566 case KeyEvent.KEYCODE_DPAD_UP:
2567 case KeyEvent.KEYCODE_DPAD_DOWN:
Jeff Brown4e6319b2010-12-13 10:36:51 -08002568 case KeyEvent.KEYCODE_DPAD_CENTER:
2569 case KeyEvent.KEYCODE_PAGE_UP:
2570 case KeyEvent.KEYCODE_PAGE_DOWN:
2571 case KeyEvent.KEYCODE_MOVE_HOME:
2572 case KeyEvent.KEYCODE_MOVE_END:
2573 case KeyEvent.KEYCODE_TAB:
2574 case KeyEvent.KEYCODE_SPACE:
2575 case KeyEvent.KEYCODE_ENTER:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002576 return true;
2577 }
2578 return false;
2579 }
2580
2581 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08002582 * Returns true if the key is used for typing.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002583 * @param keyEvent The key event.
Jeff Brown4e6319b2010-12-13 10:36:51 -08002584 * @return True if the key is used for typing.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002585 */
Jeff Brown4e6319b2010-12-13 10:36:51 -08002586 private static boolean isTypingKey(KeyEvent keyEvent) {
2587 return keyEvent.getUnicodeChar() > 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002588 }
2589
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002590 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08002591 * 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 -08002592 * @param event The key event.
2593 * @return Whether this key event should be consumed (meaning the act of
2594 * leaving touch mode alone is considered the event).
2595 */
2596 private boolean checkForLeavingTouchModeAndConsume(KeyEvent event) {
Jeff Brown4e6319b2010-12-13 10:36:51 -08002597 // Only relevant in touch mode.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002598 if (!mAttachInfo.mInTouchMode) {
2599 return false;
2600 }
2601
Jeff Brown4e6319b2010-12-13 10:36:51 -08002602 // Only consider leaving touch mode on DOWN or MULTIPLE actions, never on UP.
2603 final int action = event.getAction();
2604 if (action != KeyEvent.ACTION_DOWN && action != KeyEvent.ACTION_MULTIPLE) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002605 return false;
2606 }
2607
Jeff Brown4e6319b2010-12-13 10:36:51 -08002608 // Don't leave touch mode if the IME told us not to.
2609 if ((event.getFlags() & KeyEvent.FLAG_KEEP_TOUCH_MODE) != 0) {
2610 return false;
2611 }
2612
2613 // If the key can be used for keyboard navigation then leave touch mode
2614 // and select a focused view if needed (in ensureTouchMode).
2615 // When a new focused view is selected, we consume the navigation key because
2616 // navigation doesn't make much sense unless a view already has focus so
2617 // the key's purpose is to set focus.
2618 if (isNavigationKey(event)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002619 return ensureTouchMode(false);
2620 }
Jeff Brown4e6319b2010-12-13 10:36:51 -08002621
2622 // If the key can be used for typing then leave touch mode
2623 // and select a focused view if needed (in ensureTouchMode).
2624 // Always allow the view to process the typing key.
2625 if (isTypingKey(event)) {
2626 ensureTouchMode(false);
2627 return false;
2628 }
2629
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002630 return false;
2631 }
2632
2633 /**
Romain Guy8506ab42009-06-11 17:35:47 -07002634 * log motion events
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002635 */
2636 private static void captureMotionLog(String subTag, MotionEvent ev) {
Romain Guy8506ab42009-06-11 17:35:47 -07002637 //check dynamic switch
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002638 if (ev == null ||
2639 SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_EVENT, 0) == 0) {
2640 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002641 }
Romain Guy8506ab42009-06-11 17:35:47 -07002642
2643 StringBuilder sb = new StringBuilder(subTag + ": ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002644 sb.append(ev.getDownTime()).append(',');
2645 sb.append(ev.getEventTime()).append(',');
2646 sb.append(ev.getAction()).append(',');
Romain Guy8506ab42009-06-11 17:35:47 -07002647 sb.append(ev.getX()).append(',');
2648 sb.append(ev.getY()).append(',');
2649 sb.append(ev.getPressure()).append(',');
2650 sb.append(ev.getSize()).append(',');
2651 sb.append(ev.getMetaState()).append(',');
2652 sb.append(ev.getXPrecision()).append(',');
2653 sb.append(ev.getYPrecision()).append(',');
2654 sb.append(ev.getDeviceId()).append(',');
2655 sb.append(ev.getEdgeFlags());
2656 Log.d(TAG, sb.toString());
2657 }
2658 /**
2659 * log motion events
2660 */
2661 private static void captureKeyLog(String subTag, KeyEvent ev) {
2662 //check dynamic switch
2663 if (ev == null ||
2664 SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_EVENT, 0) == 0) {
2665 return;
2666 }
2667 StringBuilder sb = new StringBuilder(subTag + ": ");
2668 sb.append(ev.getDownTime()).append(',');
2669 sb.append(ev.getEventTime()).append(',');
2670 sb.append(ev.getAction()).append(',');
2671 sb.append(ev.getKeyCode()).append(',');
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002672 sb.append(ev.getRepeatCount()).append(',');
2673 sb.append(ev.getMetaState()).append(',');
2674 sb.append(ev.getDeviceId()).append(',');
2675 sb.append(ev.getScanCode());
Romain Guy8506ab42009-06-11 17:35:47 -07002676 Log.d(TAG, sb.toString());
2677 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002678
2679 int enqueuePendingEvent(Object event, boolean sendDone) {
2680 int seq = mPendingEventSeq+1;
2681 if (seq < 0) seq = 0;
2682 mPendingEventSeq = seq;
2683 mPendingEvents.put(seq, event);
2684 return sendDone ? seq : -seq;
2685 }
2686
2687 Object retrievePendingEvent(int seq) {
2688 if (seq < 0) seq = -seq;
2689 Object event = mPendingEvents.get(seq);
2690 if (event != null) {
2691 mPendingEvents.remove(seq);
2692 }
2693 return event;
2694 }
Romain Guy8506ab42009-06-11 17:35:47 -07002695
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002696 private void deliverKeyEvent(KeyEvent event, boolean sendDone) {
Jeff Brown3915bb82010-11-05 15:02:16 -07002697 // If there is no view, then the event will not be handled.
2698 if (mView == null || !mAdded) {
2699 finishKeyEvent(event, sendDone, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002700 return;
2701 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002702
2703 if (LOCAL_LOGV) Log.v(TAG, "Dispatching key " + event + " to " + mView);
2704
2705 // Perform predispatching before the IME.
2706 if (mView.dispatchKeyEventPreIme(event)) {
2707 finishKeyEvent(event, sendDone, true);
2708 return;
2709 }
2710
2711 // Dispatch to the IME before propagating down the view hierarchy.
2712 // The IME will eventually call back into handleFinishedEvent.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002713 if (mLastWasImTarget) {
2714 InputMethodManager imm = InputMethodManager.peekInstance();
Jeff Brown3915bb82010-11-05 15:02:16 -07002715 if (imm != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002716 int seq = enqueuePendingEvent(event, sendDone);
2717 if (DEBUG_IMF) Log.v(TAG, "Sending key event to IME: seq="
2718 + seq + " event=" + event);
Jeff Brown3915bb82010-11-05 15:02:16 -07002719 imm.dispatchKeyEvent(mView.getContext(), seq, event, mInputMethodCallback);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002720 return;
2721 }
2722 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002723
2724 // Not dispatching to IME, continue with post IME actions.
2725 deliverKeyEventPostIme(event, sendDone);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002726 }
2727
Jeff Brown3915bb82010-11-05 15:02:16 -07002728 private void handleFinishedEvent(int seq, boolean handled) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002729 final KeyEvent event = (KeyEvent)retrievePendingEvent(seq);
2730 if (DEBUG_IMF) Log.v(TAG, "IME finished event: seq=" + seq
2731 + " handled=" + handled + " event=" + event);
2732 if (event != null) {
2733 final boolean sendDone = seq >= 0;
Jeff Brown3915bb82010-11-05 15:02:16 -07002734 if (handled) {
2735 finishKeyEvent(event, sendDone, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002736 } else {
Jeff Brown3915bb82010-11-05 15:02:16 -07002737 deliverKeyEventPostIme(event, sendDone);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002738 }
2739 }
2740 }
Romain Guy8506ab42009-06-11 17:35:47 -07002741
Jeff Brown3915bb82010-11-05 15:02:16 -07002742 private void deliverKeyEventPostIme(KeyEvent event, boolean sendDone) {
2743 // If the view went away, then the event will not be handled.
2744 if (mView == null || !mAdded) {
2745 finishKeyEvent(event, sendDone, false);
2746 return;
2747 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002748
Jeff Brown3915bb82010-11-05 15:02:16 -07002749 // If the key's purpose is to exit touch mode then we consume it and consider it handled.
2750 if (checkForLeavingTouchModeAndConsume(event)) {
2751 finishKeyEvent(event, sendDone, true);
2752 return;
2753 }
Romain Guy8506ab42009-06-11 17:35:47 -07002754
Jeff Brown3915bb82010-11-05 15:02:16 -07002755 if (Config.LOGV) {
2756 captureKeyLog("captureDispatchKeyEvent", event);
2757 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002758
Jeff Brown90655042010-12-02 13:50:46 -08002759 // Make sure the fallback event policy sees all keys that will be delivered to the
2760 // view hierarchy.
2761 mFallbackEventHandler.preDispatchKeyEvent(event);
2762
Jeff Brown3915bb82010-11-05 15:02:16 -07002763 // Deliver the key to the view hierarchy.
2764 if (mView.dispatchKeyEvent(event)) {
2765 finishKeyEvent(event, sendDone, true);
2766 return;
2767 }
Joe Onorato86f67862010-11-05 18:57:34 -07002768
Jeff Brownc1df9072010-12-21 16:38:50 -08002769 // If the Control modifier is held, try to interpret the key as a shortcut.
2770 if (event.getAction() == KeyEvent.ACTION_UP
2771 && event.isCtrlPressed()
2772 && !KeyEvent.isModifierKey(event.getKeyCode())) {
2773 if (mView.dispatchKeyShortcutEvent(event)) {
2774 finishKeyEvent(event, sendDone, true);
2775 return;
2776 }
2777 }
2778
Jeff Brown3915bb82010-11-05 15:02:16 -07002779 // Apply the fallback event policy.
2780 if (mFallbackEventHandler.dispatchKeyEvent(event)) {
2781 finishKeyEvent(event, sendDone, true);
2782 return;
2783 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002784
Jeff Brown3915bb82010-11-05 15:02:16 -07002785 // Handle automatic focus changes.
2786 if (event.getAction() == KeyEvent.ACTION_DOWN) {
2787 int direction = 0;
2788 switch (event.getKeyCode()) {
2789 case KeyEvent.KEYCODE_DPAD_LEFT:
Jeff Brown4e6319b2010-12-13 10:36:51 -08002790 if (event.hasNoModifiers()) {
2791 direction = View.FOCUS_LEFT;
2792 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002793 break;
2794 case KeyEvent.KEYCODE_DPAD_RIGHT:
Jeff Brown4e6319b2010-12-13 10:36:51 -08002795 if (event.hasNoModifiers()) {
2796 direction = View.FOCUS_RIGHT;
2797 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002798 break;
2799 case KeyEvent.KEYCODE_DPAD_UP:
Jeff Brown4e6319b2010-12-13 10:36:51 -08002800 if (event.hasNoModifiers()) {
2801 direction = View.FOCUS_UP;
2802 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002803 break;
2804 case KeyEvent.KEYCODE_DPAD_DOWN:
Jeff Brown4e6319b2010-12-13 10:36:51 -08002805 if (event.hasNoModifiers()) {
2806 direction = View.FOCUS_DOWN;
2807 }
2808 break;
2809 case KeyEvent.KEYCODE_TAB:
2810 if (event.hasNoModifiers()) {
2811 direction = View.FOCUS_FORWARD;
2812 } else if (event.hasModifiers(KeyEvent.META_SHIFT_ON)) {
2813 direction = View.FOCUS_BACKWARD;
2814 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002815 break;
2816 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002817
Jeff Brown3915bb82010-11-05 15:02:16 -07002818 if (direction != 0) {
2819 View focused = mView != null ? mView.findFocus() : null;
2820 if (focused != null) {
2821 View v = focused.focusSearch(direction);
2822 if (v != null && v != focused) {
2823 // do the math the get the interesting rect
2824 // of previous focused into the coord system of
2825 // newly focused view
2826 focused.getFocusedRect(mTempRect);
2827 if (mView instanceof ViewGroup) {
2828 ((ViewGroup) mView).offsetDescendantRectToMyCoords(
2829 focused, mTempRect);
2830 ((ViewGroup) mView).offsetRectIntoDescendantCoords(
2831 v, mTempRect);
2832 }
2833 if (v.requestFocus(direction, mTempRect)) {
2834 playSoundEffect(
2835 SoundEffectConstants.getContantForFocusDirection(direction));
2836 finishKeyEvent(event, sendDone, true);
2837 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002838 }
2839 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002840
2841 // Give the focused view a last chance to handle the dpad key.
2842 if (mView.dispatchUnhandledMove(focused, direction)) {
2843 finishKeyEvent(event, sendDone, true);
2844 return;
2845 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002846 }
2847 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002848 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002849
Jeff Brown3915bb82010-11-05 15:02:16 -07002850 // Key was unhandled.
2851 finishKeyEvent(event, sendDone, false);
2852 }
2853
2854 private void finishKeyEvent(KeyEvent event, boolean sendDone, boolean handled) {
2855 if (sendDone) {
2856 finishInputEvent(handled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002857 }
2858 }
2859
Christopher Tatea53146c2010-09-07 11:57:52 -07002860 /* drag/drop */
Christopher Tate407b4e92010-11-30 17:14:08 -08002861 void setLocalDragState(Object obj) {
2862 mLocalDragState = obj;
2863 }
2864
Christopher Tatea53146c2010-09-07 11:57:52 -07002865 private void handleDragEvent(DragEvent event) {
2866 // From the root, only drag start/end/location are dispatched. entered/exited
2867 // are determined and dispatched by the viewgroup hierarchy, who then report
2868 // that back here for ultimate reporting back to the framework.
2869 if (mView != null && mAdded) {
2870 final int what = event.mAction;
2871
2872 if (what == DragEvent.ACTION_DRAG_EXITED) {
2873 // A direct EXITED event means that the window manager knows we've just crossed
2874 // a window boundary, so the current drag target within this one must have
2875 // just been exited. Send it the usual notifications and then we're done
2876 // for now.
Chris Tate9d1ab882010-11-02 15:55:39 -07002877 mView.dispatchDragEvent(event);
Christopher Tatea53146c2010-09-07 11:57:52 -07002878 } else {
2879 // Cache the drag description when the operation starts, then fill it in
2880 // on subsequent calls as a convenience
2881 if (what == DragEvent.ACTION_DRAG_STARTED) {
Chris Tate9d1ab882010-11-02 15:55:39 -07002882 mCurrentDragView = null; // Start the current-recipient tracking
Christopher Tatea53146c2010-09-07 11:57:52 -07002883 mDragDescription = event.mClipDescription;
2884 } else {
2885 event.mClipDescription = mDragDescription;
2886 }
2887
2888 // For events with a [screen] location, translate into window coordinates
2889 if ((what == DragEvent.ACTION_DRAG_LOCATION) || (what == DragEvent.ACTION_DROP)) {
2890 mDragPoint.set(event.mX, event.mY);
2891 if (mTranslator != null) {
2892 mTranslator.translatePointInScreenToAppWindow(mDragPoint);
2893 }
2894
2895 if (mCurScrollY != 0) {
2896 mDragPoint.offset(0, mCurScrollY);
2897 }
2898
2899 event.mX = mDragPoint.x;
2900 event.mY = mDragPoint.y;
2901 }
2902
2903 // Remember who the current drag target is pre-dispatch
2904 final View prevDragView = mCurrentDragView;
2905
2906 // Now dispatch the drag/drop event
Chris Tated4533f12010-10-19 15:15:08 -07002907 boolean result = mView.dispatchDragEvent(event);
Christopher Tatea53146c2010-09-07 11:57:52 -07002908
2909 // If we changed apparent drag target, tell the OS about it
2910 if (prevDragView != mCurrentDragView) {
2911 try {
2912 if (prevDragView != null) {
2913 sWindowSession.dragRecipientExited(mWindow);
2914 }
2915 if (mCurrentDragView != null) {
2916 sWindowSession.dragRecipientEntered(mWindow);
2917 }
2918 } catch (RemoteException e) {
2919 Slog.e(TAG, "Unable to note drag target change");
2920 }
Christopher Tatea53146c2010-09-07 11:57:52 -07002921 }
Chris Tated4533f12010-10-19 15:15:08 -07002922
Christopher Tate407b4e92010-11-30 17:14:08 -08002923 // Report the drop result when we're done
Chris Tated4533f12010-10-19 15:15:08 -07002924 if (what == DragEvent.ACTION_DROP) {
Christopher Tate1fc014f2011-01-19 12:56:26 -08002925 mDragDescription = null;
Chris Tated4533f12010-10-19 15:15:08 -07002926 try {
2927 Log.i(TAG, "Reporting drop result: " + result);
2928 sWindowSession.reportDropResult(mWindow, result);
2929 } catch (RemoteException e) {
2930 Log.e(TAG, "Unable to report drop result");
2931 }
2932 }
Christopher Tate407b4e92010-11-30 17:14:08 -08002933
2934 // When the drag operation ends, release any local state object
2935 // that may have been in use
2936 if (what == DragEvent.ACTION_DRAG_ENDED) {
2937 setLocalDragState(null);
2938 }
Christopher Tatea53146c2010-09-07 11:57:52 -07002939 }
2940 }
2941 event.recycle();
2942 }
2943
Joe Onorato664644d2011-01-23 17:53:23 -08002944 public void handleDispatchSystemUiVisibilityChanged(int visibility) {
2945 if (mView == null) return;
2946 mView.dispatchSystemUiVisibilityChanged(visibility);
2947 }
2948
Christopher Tate2c095f32010-10-04 14:13:40 -07002949 public void getLastTouchPoint(Point outLocation) {
2950 outLocation.x = (int) mLastTouchPoint.x;
2951 outLocation.y = (int) mLastTouchPoint.y;
2952 }
2953
Chris Tate9d1ab882010-11-02 15:55:39 -07002954 public void setDragFocus(View newDragTarget) {
Christopher Tatea53146c2010-09-07 11:57:52 -07002955 if (mCurrentDragView != newDragTarget) {
Chris Tate048691c2010-10-12 17:39:18 -07002956 mCurrentDragView = newDragTarget;
Christopher Tatea53146c2010-09-07 11:57:52 -07002957 }
Christopher Tatea53146c2010-09-07 11:57:52 -07002958 }
2959
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002960 private AudioManager getAudioManager() {
2961 if (mView == null) {
2962 throw new IllegalStateException("getAudioManager called when there is no mView");
2963 }
2964 if (mAudioManager == null) {
2965 mAudioManager = (AudioManager) mView.getContext().getSystemService(Context.AUDIO_SERVICE);
2966 }
2967 return mAudioManager;
2968 }
2969
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002970 private int relayoutWindow(WindowManager.LayoutParams params, int viewVisibility,
2971 boolean insetsPending) throws RemoteException {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002972
2973 float appScale = mAttachInfo.mApplicationScale;
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002974 boolean restore = false;
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002975 if (params != null && mTranslator != null) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07002976 restore = true;
2977 params.backup();
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002978 mTranslator.translateWindowLayout(params);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002979 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002980 if (params != null) {
2981 if (DBG) Log.d(TAG, "WindowLayout in layoutWindow:" + params);
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002982 }
Dianne Hackborn694f79b2010-03-17 19:44:59 -07002983 mPendingConfiguration.seq = 0;
Dianne Hackbornf123e492010-09-24 11:16:23 -07002984 //Log.d(TAG, ">>>>>> CALLING relayout");
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002985 int relayoutResult = sWindowSession.relayout(
2986 mWindow, params,
Dianne Hackborn189ee182010-12-02 21:48:53 -08002987 (int) (mView.getMeasuredWidth() * appScale + 0.5f),
2988 (int) (mView.getMeasuredHeight() * appScale + 0.5f),
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002989 viewVisibility, insetsPending, mWinFrame,
Dianne Hackborn694f79b2010-03-17 19:44:59 -07002990 mPendingContentInsets, mPendingVisibleInsets,
2991 mPendingConfiguration, mSurface);
Dianne Hackbornf123e492010-09-24 11:16:23 -07002992 //Log.d(TAG, "<<<<<< BACK FROM relayout");
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002993 if (restore) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07002994 params.restore();
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002995 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002996
2997 if (mTranslator != null) {
2998 mTranslator.translateRectInScreenToAppWinFrame(mWinFrame);
2999 mTranslator.translateRectInScreenToAppWindow(mPendingContentInsets);
3000 mTranslator.translateRectInScreenToAppWindow(mPendingVisibleInsets);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07003001 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07003002 return relayoutResult;
3003 }
Romain Guy8506ab42009-06-11 17:35:47 -07003004
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07003005 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003006 * {@inheritDoc}
3007 */
3008 public void playSoundEffect(int effectId) {
3009 checkThread();
3010
Jean-Michel Trivi13b18fd2010-05-05 09:18:15 -07003011 try {
3012 final AudioManager audioManager = getAudioManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003013
Jean-Michel Trivi13b18fd2010-05-05 09:18:15 -07003014 switch (effectId) {
3015 case SoundEffectConstants.CLICK:
3016 audioManager.playSoundEffect(AudioManager.FX_KEY_CLICK);
3017 return;
3018 case SoundEffectConstants.NAVIGATION_DOWN:
3019 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_DOWN);
3020 return;
3021 case SoundEffectConstants.NAVIGATION_LEFT:
3022 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_LEFT);
3023 return;
3024 case SoundEffectConstants.NAVIGATION_RIGHT:
3025 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_RIGHT);
3026 return;
3027 case SoundEffectConstants.NAVIGATION_UP:
3028 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_UP);
3029 return;
3030 default:
3031 throw new IllegalArgumentException("unknown effect id " + effectId +
3032 " not defined in " + SoundEffectConstants.class.getCanonicalName());
3033 }
3034 } catch (IllegalStateException e) {
3035 // Exception thrown by getAudioManager() when mView is null
3036 Log.e(TAG, "FATAL EXCEPTION when attempting to play sound effect: " + e);
3037 e.printStackTrace();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003038 }
3039 }
3040
3041 /**
3042 * {@inheritDoc}
3043 */
3044 public boolean performHapticFeedback(int effectId, boolean always) {
3045 try {
3046 return sWindowSession.performHapticFeedback(mWindow, effectId, always);
3047 } catch (RemoteException e) {
3048 return false;
3049 }
3050 }
3051
3052 /**
3053 * {@inheritDoc}
3054 */
3055 public View focusSearch(View focused, int direction) {
3056 checkThread();
3057 if (!(mView instanceof ViewGroup)) {
3058 return null;
3059 }
3060 return FocusFinder.getInstance().findNextFocus((ViewGroup) mView, focused, direction);
3061 }
3062
3063 public void debug() {
3064 mView.debug();
3065 }
3066
3067 public void die(boolean immediate) {
Dianne Hackborn94d69142009-09-28 22:14:42 -07003068 if (immediate) {
3069 doDie();
3070 } else {
3071 sendEmptyMessage(DIE);
3072 }
3073 }
3074
3075 void doDie() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003076 checkThread();
Jeff Brownb75fa302010-07-15 23:47:29 -07003077 if (LOCAL_LOGV) Log.v(TAG, "DIE in " + this + " of " + mSurface);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003078 synchronized (this) {
3079 if (mAdded && !mFirst) {
Romain Guy29d89972010-09-22 16:10:57 -07003080 destroyHardwareRenderer();
3081
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003082 int viewVisibility = mView.getVisibility();
3083 boolean viewVisibilityChanged = mViewVisibility != viewVisibility;
3084 if (mWindowAttributesChanged || viewVisibilityChanged) {
3085 // If layout params have been changed, first give them
3086 // to the window manager to make sure it has the correct
3087 // animation info.
3088 try {
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07003089 if ((relayoutWindow(mWindowAttributes, viewVisibility, false)
3090 & WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003091 sWindowSession.finishDrawing(mWindow);
3092 }
3093 } catch (RemoteException e) {
3094 }
3095 }
3096
Dianne Hackborn0586a1b2009-09-06 21:08:27 -07003097 mSurface.release();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003098 }
3099 if (mAdded) {
3100 mAdded = false;
Dianne Hackborn94d69142009-09-28 22:14:42 -07003101 dispatchDetachedFromWindow();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003102 }
3103 }
3104 }
3105
Romain Guy29d89972010-09-22 16:10:57 -07003106 private void destroyHardwareRenderer() {
Romain Guyb051e892010-09-28 19:09:36 -07003107 if (mAttachInfo.mHardwareRenderer != null) {
3108 mAttachInfo.mHardwareRenderer.destroy(true);
3109 mAttachInfo.mHardwareRenderer = null;
Romain Guy29d89972010-09-22 16:10:57 -07003110 mAttachInfo.mHardwareAccelerated = false;
3111 }
3112 }
3113
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003114 public void dispatchFinishedEvent(int seq, boolean handled) {
3115 Message msg = obtainMessage(FINISHED_EVENT);
3116 msg.arg1 = seq;
3117 msg.arg2 = handled ? 1 : 0;
3118 sendMessage(msg);
3119 }
Mitsuru Oshima3d914922009-05-13 22:29:15 -07003120
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003121 public void dispatchResized(int w, int h, Rect coveredInsets,
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003122 Rect visibleInsets, boolean reportDraw, Configuration newConfig) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003123 if (DEBUG_LAYOUT) Log.v(TAG, "Resizing " + this + ": w=" + w
3124 + " h=" + h + " coveredInsets=" + coveredInsets.toShortString()
3125 + " visibleInsets=" + visibleInsets.toShortString()
3126 + " reportDraw=" + reportDraw);
3127 Message msg = obtainMessage(reportDraw ? RESIZED_REPORT :RESIZED);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07003128 if (mTranslator != null) {
3129 mTranslator.translateRectInScreenToAppWindow(coveredInsets);
3130 mTranslator.translateRectInScreenToAppWindow(visibleInsets);
3131 w *= mTranslator.applicationInvertedScale;
3132 h *= mTranslator.applicationInvertedScale;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07003133 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07003134 msg.arg1 = w;
3135 msg.arg2 = h;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003136 ResizedInfo ri = new ResizedInfo();
3137 ri.coveredInsets = new Rect(coveredInsets);
3138 ri.visibleInsets = new Rect(visibleInsets);
3139 ri.newConfig = newConfig;
3140 msg.obj = ri;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003141 sendMessage(msg);
3142 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07003143
Jeff Brown3915bb82010-11-05 15:02:16 -07003144 private InputQueue.FinishedCallback mFinishedCallback;
Jeff Brown46b9ac02010-04-22 18:58:52 -07003145
3146 private final InputHandler mInputHandler = new InputHandler() {
Jeff Brown3915bb82010-11-05 15:02:16 -07003147 public void handleKey(KeyEvent event, InputQueue.FinishedCallback finishedCallback) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07003148 startInputEvent(finishedCallback);
Jeff Brown92ff1dd2010-08-11 16:16:06 -07003149 dispatchKey(event, true);
Jeff Brown46b9ac02010-04-22 18:58:52 -07003150 }
3151
Jeff Brown3915bb82010-11-05 15:02:16 -07003152 public void handleMotion(MotionEvent event, InputQueue.FinishedCallback finishedCallback) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07003153 startInputEvent(finishedCallback);
3154 dispatchMotion(event, true);
Jeff Brown46b9ac02010-04-22 18:58:52 -07003155 }
3156 };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003157
3158 public void dispatchKey(KeyEvent event) {
Jeff Brown92ff1dd2010-08-11 16:16:06 -07003159 dispatchKey(event, false);
3160 }
3161
3162 private void dispatchKey(KeyEvent event, boolean sendDone) {
3163 //noinspection ConstantConditions
3164 if (false && event.getAction() == KeyEvent.ACTION_DOWN) {
3165 if (event.getKeyCode() == KeyEvent.KEYCODE_CAMERA) {
Romain Guy812ccbe2010-06-01 14:07:24 -07003166 if (DBG) Log.d("keydisp", "===================================================");
3167 if (DBG) Log.d("keydisp", "Focused view Hierarchy is:");
3168
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003169 debug();
3170
Romain Guy812ccbe2010-06-01 14:07:24 -07003171 if (DBG) Log.d("keydisp", "===================================================");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003172 }
3173 }
3174
3175 Message msg = obtainMessage(DISPATCH_KEY);
3176 msg.obj = event;
Jeff Brown92ff1dd2010-08-11 16:16:06 -07003177 msg.arg1 = sendDone ? 1 : 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003178
3179 if (LOCAL_LOGV) Log.v(
Jeff Brownc5ed5912010-07-14 18:48:53 -07003180 TAG, "sending key " + event + " to " + mView);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003181
3182 sendMessageAtTime(msg, event.getEventTime());
3183 }
Jeff Brownc5ed5912010-07-14 18:48:53 -07003184
3185 public void dispatchMotion(MotionEvent event) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07003186 dispatchMotion(event, false);
3187 }
3188
3189 private void dispatchMotion(MotionEvent event, boolean sendDone) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07003190 int source = event.getSource();
3191 if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07003192 dispatchPointer(event, sendDone);
Jeff Brownc5ed5912010-07-14 18:48:53 -07003193 } else if ((source & InputDevice.SOURCE_CLASS_TRACKBALL) != 0) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07003194 dispatchTrackball(event, sendDone);
Jeff Brownc5ed5912010-07-14 18:48:53 -07003195 } else {
Jeff Browncb1404e2011-01-15 18:14:15 -08003196 dispatchGenericMotion(event, sendDone);
Jeff Brownc5ed5912010-07-14 18:48:53 -07003197 }
3198 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003199
Jeff Brown00fa7bd2010-07-02 15:37:36 -07003200 public void dispatchPointer(MotionEvent event) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07003201 dispatchPointer(event, false);
3202 }
3203
3204 private void dispatchPointer(MotionEvent event, boolean sendDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003205 Message msg = obtainMessage(DISPATCH_POINTER);
3206 msg.obj = event;
Jeff Brown93ed4e32010-09-23 13:51:48 -07003207 msg.arg1 = sendDone ? 1 : 0;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07003208 sendMessageAtTime(msg, event.getEventTime());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003209 }
3210
Jeff Brown00fa7bd2010-07-02 15:37:36 -07003211 public void dispatchTrackball(MotionEvent event) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07003212 dispatchTrackball(event, false);
3213 }
3214
3215 private void dispatchTrackball(MotionEvent event, boolean sendDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003216 Message msg = obtainMessage(DISPATCH_TRACKBALL);
3217 msg.obj = event;
Jeff Brown93ed4e32010-09-23 13:51:48 -07003218 msg.arg1 = sendDone ? 1 : 0;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07003219 sendMessageAtTime(msg, event.getEventTime());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003220 }
Jeff Browncb1404e2011-01-15 18:14:15 -08003221
3222 private void dispatchGenericMotion(MotionEvent event, boolean sendDone) {
3223 Message msg = obtainMessage(DISPATCH_GENERIC_MOTION);
3224 msg.obj = event;
3225 msg.arg1 = sendDone ? 1 : 0;
3226 sendMessageAtTime(msg, event.getEventTime());
3227 }
3228
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003229 public void dispatchAppVisibility(boolean visible) {
3230 Message msg = obtainMessage(DISPATCH_APP_VISIBILITY);
3231 msg.arg1 = visible ? 1 : 0;
3232 sendMessage(msg);
3233 }
3234
3235 public void dispatchGetNewSurface() {
3236 Message msg = obtainMessage(DISPATCH_GET_NEW_SURFACE);
3237 sendMessage(msg);
3238 }
3239
3240 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
3241 Message msg = Message.obtain();
3242 msg.what = WINDOW_FOCUS_CHANGED;
3243 msg.arg1 = hasFocus ? 1 : 0;
3244 msg.arg2 = inTouchMode ? 1 : 0;
3245 sendMessage(msg);
3246 }
3247
Dianne Hackbornffa42482009-09-23 22:20:11 -07003248 public void dispatchCloseSystemDialogs(String reason) {
3249 Message msg = Message.obtain();
3250 msg.what = CLOSE_SYSTEM_DIALOGS;
3251 msg.obj = reason;
3252 sendMessage(msg);
3253 }
Christopher Tatea53146c2010-09-07 11:57:52 -07003254
3255 public void dispatchDragEvent(DragEvent event) {
Chris Tate91e9bb32010-10-12 12:58:43 -07003256 final int what;
3257 if (event.getAction() == DragEvent.ACTION_DRAG_LOCATION) {
3258 what = DISPATCH_DRAG_LOCATION_EVENT;
3259 removeMessages(what);
3260 } else {
3261 what = DISPATCH_DRAG_EVENT;
3262 }
3263 Message msg = obtainMessage(what, event);
Christopher Tatea53146c2010-09-07 11:57:52 -07003264 sendMessage(msg);
3265 }
3266
Joe Onorato664644d2011-01-23 17:53:23 -08003267 public void dispatchSystemUiVisibilityChanged(int visibility) {
3268 sendMessage(obtainMessage(DISPATCH_SYSTEM_UI_VISIBILITY, visibility, 0));
3269 }
3270
svetoslavganov75986cf2009-05-14 22:28:01 -07003271 /**
3272 * The window is getting focus so if there is anything focused/selected
3273 * send an {@link AccessibilityEvent} to announce that.
3274 */
3275 private void sendAccessibilityEvents() {
3276 if (!AccessibilityManager.getInstance(mView.getContext()).isEnabled()) {
3277 return;
3278 }
3279 mView.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
3280 View focusedView = mView.findFocus();
3281 if (focusedView != null && focusedView != mView) {
3282 focusedView.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
3283 }
3284 }
3285
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003286 public boolean showContextMenuForChild(View originalView) {
3287 return false;
3288 }
3289
Adam Powell6e346362010-07-23 10:18:23 -07003290 public ActionMode startActionModeForChild(View originalView, ActionMode.Callback callback) {
3291 return null;
3292 }
3293
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003294 public void createContextMenu(ContextMenu menu) {
3295 }
3296
3297 public void childDrawableStateChanged(View child) {
3298 }
3299
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003300 void checkThread() {
3301 if (mThread != Thread.currentThread()) {
3302 throw new CalledFromWrongThreadException(
3303 "Only the original thread that created a view hierarchy can touch its views.");
3304 }
3305 }
3306
3307 public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
3308 // ViewRoot never intercepts touch event, so this can be a no-op
3309 }
3310
3311 public boolean requestChildRectangleOnScreen(View child, Rect rectangle,
3312 boolean immediate) {
3313 return scrollToRectOrFocus(rectangle, immediate);
3314 }
Romain Guy8506ab42009-06-11 17:35:47 -07003315
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07003316 class TakenSurfaceHolder extends BaseSurfaceHolder {
3317 @Override
3318 public boolean onAllowLockCanvas() {
3319 return mDrawingAllowed;
3320 }
3321
3322 @Override
3323 public void onRelayoutContainer() {
3324 // Not currently interesting -- from changing between fixed and layout size.
3325 }
3326
3327 public void setFormat(int format) {
3328 ((RootViewSurfaceTaker)mView).setSurfaceFormat(format);
3329 }
3330
3331 public void setType(int type) {
3332 ((RootViewSurfaceTaker)mView).setSurfaceType(type);
3333 }
3334
3335 @Override
3336 public void onUpdateSurface() {
3337 // We take care of format and type changes on our own.
3338 throw new IllegalStateException("Shouldn't be here");
3339 }
3340
3341 public boolean isCreating() {
3342 return mIsCreating;
3343 }
3344
3345 @Override
3346 public void setFixedSize(int width, int height) {
3347 throw new UnsupportedOperationException(
3348 "Currently only support sizing from layout");
3349 }
3350
3351 public void setKeepScreenOn(boolean screenOn) {
3352 ((RootViewSurfaceTaker)mView).setSurfaceKeepScreenOn(screenOn);
3353 }
3354 }
3355
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003356 static class InputMethodCallback extends IInputMethodCallback.Stub {
3357 private WeakReference<ViewRoot> mViewRoot;
3358
3359 public InputMethodCallback(ViewRoot viewRoot) {
3360 mViewRoot = new WeakReference<ViewRoot>(viewRoot);
3361 }
Romain Guy8506ab42009-06-11 17:35:47 -07003362
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003363 public void finishedEvent(int seq, boolean handled) {
3364 final ViewRoot viewRoot = mViewRoot.get();
3365 if (viewRoot != null) {
3366 viewRoot.dispatchFinishedEvent(seq, handled);
3367 }
3368 }
3369
3370 public void sessionCreated(IInputMethodSession session) throws RemoteException {
3371 // Stub -- not for use in the client.
3372 }
3373 }
Romain Guy8506ab42009-06-11 17:35:47 -07003374
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003375 static class W extends IWindow.Stub {
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07003376 private final WeakReference<ViewRoot> mViewRoot;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003377
Romain Guyfb8b7632010-08-23 21:05:08 -07003378 W(ViewRoot viewRoot) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003379 mViewRoot = new WeakReference<ViewRoot>(viewRoot);
3380 }
3381
Romain Guyfb8b7632010-08-23 21:05:08 -07003382 public void resized(int w, int h, Rect coveredInsets, Rect visibleInsets,
3383 boolean reportDraw, Configuration newConfig) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003384 final ViewRoot viewRoot = mViewRoot.get();
3385 if (viewRoot != null) {
Romain Guyfb8b7632010-08-23 21:05:08 -07003386 viewRoot.dispatchResized(w, h, coveredInsets, visibleInsets, reportDraw, newConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003387 }
3388 }
3389
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003390 public void dispatchAppVisibility(boolean visible) {
3391 final ViewRoot viewRoot = mViewRoot.get();
3392 if (viewRoot != null) {
3393 viewRoot.dispatchAppVisibility(visible);
3394 }
3395 }
3396
3397 public void dispatchGetNewSurface() {
3398 final ViewRoot viewRoot = mViewRoot.get();
3399 if (viewRoot != null) {
3400 viewRoot.dispatchGetNewSurface();
3401 }
3402 }
3403
3404 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
3405 final ViewRoot viewRoot = mViewRoot.get();
3406 if (viewRoot != null) {
3407 viewRoot.windowFocusChanged(hasFocus, inTouchMode);
3408 }
3409 }
3410
3411 private static int checkCallingPermission(String permission) {
3412 if (!Process.supportsProcesses()) {
3413 return PackageManager.PERMISSION_GRANTED;
3414 }
3415
3416 try {
3417 return ActivityManagerNative.getDefault().checkPermission(
3418 permission, Binder.getCallingPid(), Binder.getCallingUid());
3419 } catch (RemoteException e) {
3420 return PackageManager.PERMISSION_DENIED;
3421 }
3422 }
3423
3424 public void executeCommand(String command, String parameters, ParcelFileDescriptor out) {
3425 final ViewRoot viewRoot = mViewRoot.get();
3426 if (viewRoot != null) {
3427 final View view = viewRoot.mView;
3428 if (view != null) {
3429 if (checkCallingPermission(Manifest.permission.DUMP) !=
3430 PackageManager.PERMISSION_GRANTED) {
3431 throw new SecurityException("Insufficient permissions to invoke"
3432 + " executeCommand() from pid=" + Binder.getCallingPid()
3433 + ", uid=" + Binder.getCallingUid());
3434 }
3435
3436 OutputStream clientStream = null;
3437 try {
3438 clientStream = new ParcelFileDescriptor.AutoCloseOutputStream(out);
3439 ViewDebug.dispatchCommand(view, command, parameters, clientStream);
3440 } catch (IOException e) {
3441 e.printStackTrace();
3442 } finally {
3443 if (clientStream != null) {
3444 try {
3445 clientStream.close();
3446 } catch (IOException e) {
3447 e.printStackTrace();
3448 }
3449 }
3450 }
3451 }
3452 }
3453 }
Dianne Hackborn72c82ab2009-08-11 21:13:54 -07003454
Dianne Hackbornffa42482009-09-23 22:20:11 -07003455 public void closeSystemDialogs(String reason) {
3456 final ViewRoot viewRoot = mViewRoot.get();
3457 if (viewRoot != null) {
3458 viewRoot.dispatchCloseSystemDialogs(reason);
3459 }
3460 }
3461
Marco Nelissenbf6956b2009-11-09 15:21:13 -08003462 public void dispatchWallpaperOffsets(float x, float y, float xStep, float yStep,
3463 boolean sync) {
Dianne Hackborn19382ac2009-09-11 21:13:37 -07003464 if (sync) {
3465 try {
3466 sWindowSession.wallpaperOffsetsComplete(asBinder());
3467 } catch (RemoteException e) {
3468 }
3469 }
Dianne Hackborn72c82ab2009-08-11 21:13:54 -07003470 }
Dianne Hackborn75804932009-10-20 20:15:20 -07003471
3472 public void dispatchWallpaperCommand(String action, int x, int y,
3473 int z, Bundle extras, boolean sync) {
3474 if (sync) {
3475 try {
3476 sWindowSession.wallpaperCommandComplete(asBinder(), null);
3477 } catch (RemoteException e) {
3478 }
3479 }
3480 }
Christopher Tatea53146c2010-09-07 11:57:52 -07003481
3482 /* Drag/drop */
3483 public void dispatchDragEvent(DragEvent event) {
3484 final ViewRoot viewRoot = mViewRoot.get();
3485 if (viewRoot != null) {
3486 viewRoot.dispatchDragEvent(event);
3487 }
3488 }
Joe Onorato664644d2011-01-23 17:53:23 -08003489
3490 @Override
3491 public void dispatchSystemUiVisibilityChanged(int visibility) {
3492 final ViewRoot viewRoot = mViewRoot.get();
3493 if (viewRoot != null) {
3494 viewRoot.dispatchSystemUiVisibilityChanged(visibility);
3495 }
3496 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003497 }
3498
3499 /**
3500 * Maintains state information for a single trackball axis, generating
3501 * discrete (DPAD) movements based on raw trackball motion.
3502 */
3503 static final class TrackballAxis {
3504 /**
3505 * The maximum amount of acceleration we will apply.
3506 */
3507 static final float MAX_ACCELERATION = 20;
Romain Guy8506ab42009-06-11 17:35:47 -07003508
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003509 /**
3510 * The maximum amount of time (in milliseconds) between events in order
3511 * for us to consider the user to be doing fast trackball movements,
3512 * and thus apply an acceleration.
3513 */
3514 static final long FAST_MOVE_TIME = 150;
Romain Guy8506ab42009-06-11 17:35:47 -07003515
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003516 /**
3517 * Scaling factor to the time (in milliseconds) between events to how
3518 * much to multiple/divide the current acceleration. When movement
3519 * is < FAST_MOVE_TIME this multiplies the acceleration; when >
3520 * FAST_MOVE_TIME it divides it.
3521 */
3522 static final float ACCEL_MOVE_SCALING_FACTOR = (1.0f/40);
Romain Guy8506ab42009-06-11 17:35:47 -07003523
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003524 float position;
3525 float absPosition;
3526 float acceleration = 1;
3527 long lastMoveTime = 0;
3528 int step;
3529 int dir;
3530 int nonAccelMovement;
3531
3532 void reset(int _step) {
3533 position = 0;
3534 acceleration = 1;
3535 lastMoveTime = 0;
3536 step = _step;
3537 dir = 0;
3538 }
3539
3540 /**
3541 * Add trackball movement into the state. If the direction of movement
3542 * has been reversed, the state is reset before adding the
3543 * movement (so that you don't have to compensate for any previously
3544 * collected movement before see the result of the movement in the
3545 * new direction).
3546 *
3547 * @return Returns the absolute value of the amount of movement
3548 * collected so far.
3549 */
3550 float collect(float off, long time, String axis) {
3551 long normTime;
3552 if (off > 0) {
3553 normTime = (long)(off * FAST_MOVE_TIME);
3554 if (dir < 0) {
3555 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to positive!");
3556 position = 0;
3557 step = 0;
3558 acceleration = 1;
3559 lastMoveTime = 0;
3560 }
3561 dir = 1;
3562 } else if (off < 0) {
3563 normTime = (long)((-off) * FAST_MOVE_TIME);
3564 if (dir > 0) {
3565 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to negative!");
3566 position = 0;
3567 step = 0;
3568 acceleration = 1;
3569 lastMoveTime = 0;
3570 }
3571 dir = -1;
3572 } else {
3573 normTime = 0;
3574 }
Romain Guy8506ab42009-06-11 17:35:47 -07003575
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003576 // The number of milliseconds between each movement that is
3577 // considered "normal" and will not result in any acceleration
3578 // or deceleration, scaled by the offset we have here.
3579 if (normTime > 0) {
3580 long delta = time - lastMoveTime;
3581 lastMoveTime = time;
3582 float acc = acceleration;
3583 if (delta < normTime) {
3584 // The user is scrolling rapidly, so increase acceleration.
3585 float scale = (normTime-delta) * ACCEL_MOVE_SCALING_FACTOR;
3586 if (scale > 1) acc *= scale;
3587 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " accelerate: off="
3588 + off + " normTime=" + normTime + " delta=" + delta
3589 + " scale=" + scale + " acc=" + acc);
3590 acceleration = acc < MAX_ACCELERATION ? acc : MAX_ACCELERATION;
3591 } else {
3592 // The user is scrolling slowly, so decrease acceleration.
3593 float scale = (delta-normTime) * ACCEL_MOVE_SCALING_FACTOR;
3594 if (scale > 1) acc /= scale;
3595 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " deccelerate: off="
3596 + off + " normTime=" + normTime + " delta=" + delta
3597 + " scale=" + scale + " acc=" + acc);
3598 acceleration = acc > 1 ? acc : 1;
3599 }
3600 }
3601 position += off;
3602 return (absPosition = Math.abs(position));
3603 }
3604
3605 /**
3606 * Generate the number of discrete movement events appropriate for
3607 * the currently collected trackball movement.
3608 *
3609 * @param precision The minimum movement required to generate the
3610 * first discrete movement.
3611 *
3612 * @return Returns the number of discrete movements, either positive
3613 * or negative, or 0 if there is not enough trackball movement yet
3614 * for a discrete movement.
3615 */
3616 int generate(float precision) {
3617 int movement = 0;
3618 nonAccelMovement = 0;
3619 do {
3620 final int dir = position >= 0 ? 1 : -1;
3621 switch (step) {
3622 // If we are going to execute the first step, then we want
3623 // to do this as soon as possible instead of waiting for
3624 // a full movement, in order to make things look responsive.
3625 case 0:
3626 if (absPosition < precision) {
3627 return movement;
3628 }
3629 movement += dir;
3630 nonAccelMovement += dir;
3631 step = 1;
3632 break;
3633 // If we have generated the first movement, then we need
3634 // to wait for the second complete trackball motion before
3635 // generating the second discrete movement.
3636 case 1:
3637 if (absPosition < 2) {
3638 return movement;
3639 }
3640 movement += dir;
3641 nonAccelMovement += dir;
3642 position += dir > 0 ? -2 : 2;
3643 absPosition = Math.abs(position);
3644 step = 2;
3645 break;
3646 // After the first two, we generate discrete movements
3647 // consistently with the trackball, applying an acceleration
3648 // if the trackball is moving quickly. This is a simple
3649 // acceleration on top of what we already compute based
3650 // on how quickly the wheel is being turned, to apply
3651 // a longer increasing acceleration to continuous movement
3652 // in one direction.
3653 default:
3654 if (absPosition < 1) {
3655 return movement;
3656 }
3657 movement += dir;
3658 position += dir >= 0 ? -1 : 1;
3659 absPosition = Math.abs(position);
3660 float acc = acceleration;
3661 acc *= 1.1f;
3662 acceleration = acc < MAX_ACCELERATION ? acc : acceleration;
3663 break;
3664 }
3665 } while (true);
3666 }
3667 }
3668
3669 public static final class CalledFromWrongThreadException extends AndroidRuntimeException {
3670 public CalledFromWrongThreadException(String msg) {
3671 super(msg);
3672 }
3673 }
3674
3675 private SurfaceHolder mHolder = new SurfaceHolder() {
3676 // we only need a SurfaceHolder for opengl. it would be nice
3677 // to implement everything else though, especially the callback
3678 // support (opengl doesn't make use of it right now, but eventually
3679 // will).
3680 public Surface getSurface() {
3681 return mSurface;
3682 }
3683
3684 public boolean isCreating() {
3685 return false;
3686 }
3687
3688 public void addCallback(Callback callback) {
3689 }
3690
3691 public void removeCallback(Callback callback) {
3692 }
3693
3694 public void setFixedSize(int width, int height) {
3695 }
3696
3697 public void setSizeFromLayout() {
3698 }
3699
3700 public void setFormat(int format) {
3701 }
3702
3703 public void setType(int type) {
3704 }
3705
3706 public void setKeepScreenOn(boolean screenOn) {
3707 }
3708
3709 public Canvas lockCanvas() {
3710 return null;
3711 }
3712
3713 public Canvas lockCanvas(Rect dirty) {
3714 return null;
3715 }
3716
3717 public void unlockCanvasAndPost(Canvas canvas) {
3718 }
3719 public Rect getSurfaceFrame() {
3720 return null;
3721 }
3722 };
3723
3724 static RunQueue getRunQueue() {
3725 RunQueue rq = sRunQueues.get();
3726 if (rq != null) {
3727 return rq;
3728 }
3729 rq = new RunQueue();
3730 sRunQueues.set(rq);
3731 return rq;
3732 }
Romain Guy8506ab42009-06-11 17:35:47 -07003733
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003734 /**
3735 * @hide
3736 */
3737 static final class RunQueue {
3738 private final ArrayList<HandlerAction> mActions = new ArrayList<HandlerAction>();
3739
3740 void post(Runnable action) {
3741 postDelayed(action, 0);
3742 }
3743
3744 void postDelayed(Runnable action, long delayMillis) {
3745 HandlerAction handlerAction = new HandlerAction();
3746 handlerAction.action = action;
3747 handlerAction.delay = delayMillis;
3748
3749 synchronized (mActions) {
3750 mActions.add(handlerAction);
3751 }
3752 }
3753
3754 void removeCallbacks(Runnable action) {
3755 final HandlerAction handlerAction = new HandlerAction();
3756 handlerAction.action = action;
3757
3758 synchronized (mActions) {
3759 final ArrayList<HandlerAction> actions = mActions;
3760
3761 while (actions.remove(handlerAction)) {
3762 // Keep going
3763 }
3764 }
3765 }
3766
3767 void executeActions(Handler handler) {
3768 synchronized (mActions) {
3769 final ArrayList<HandlerAction> actions = mActions;
3770 final int count = actions.size();
3771
3772 for (int i = 0; i < count; i++) {
3773 final HandlerAction handlerAction = actions.get(i);
3774 handler.postDelayed(handlerAction.action, handlerAction.delay);
3775 }
3776
Romain Guy15df6702009-08-17 20:17:30 -07003777 actions.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003778 }
3779 }
3780
3781 private static class HandlerAction {
3782 Runnable action;
3783 long delay;
3784
3785 @Override
3786 public boolean equals(Object o) {
3787 if (this == o) return true;
3788 if (o == null || getClass() != o.getClass()) return false;
3789
3790 HandlerAction that = (HandlerAction) o;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003791 return !(action != null ? !action.equals(that.action) : that.action != null);
3792
3793 }
3794
3795 @Override
3796 public int hashCode() {
3797 int result = action != null ? action.hashCode() : 0;
3798 result = 31 * result + (int) (delay ^ (delay >>> 32));
3799 return result;
3800 }
3801 }
3802 }
3803
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003804 private static native void nativeShowFPS(Canvas canvas, int durationMillis);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003805}