blob: 7d6e18f0daed2b72eefb00f7fb448098379b5397 [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 Hackbornce418e62011-03-01 14:31:38 -0800158 // Set to true if the owner of this window is in the stopped state,
159 // so the window should no longer be active.
160 boolean mStopped = false;
161
Dianne Hackbornd76b67c2010-07-13 17:48:30 -0700162 SurfaceHolder.Callback2 mSurfaceHolderCallback;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700163 BaseSurfaceHolder mSurfaceHolder;
164 boolean mIsCreating;
165 boolean mDrawingAllowed;
166
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800167 final Region mTransparentRegion;
168 final Region mPreviousTransparentRegion;
169
170 int mWidth;
171 int mHeight;
Romain Guy7d7b5492011-01-24 16:33:45 -0800172 Rect mDirty;
173 final Rect mCurrentDirty = new Rect();
174 final Rect mPreviousDirty = new Rect();
Romain Guybb93d552009-03-24 21:04:15 -0700175 boolean mIsAnimating;
Romain Guy8506ab42009-06-11 17:35:47 -0700176
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700177 CompatibilityInfo.Translator mTranslator;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800178
179 final View.AttachInfo mAttachInfo;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700180 InputChannel mInputChannel;
Dianne Hackborn1e4b9f32010-06-23 14:10:57 -0700181 InputQueue.Callback mInputQueueCallback;
182 InputQueue mInputQueue;
Joe Onorato86f67862010-11-05 18:57:34 -0700183 FallbackEventHandler mFallbackEventHandler;
Dianne Hackborna95e4cb2010-06-18 18:09:33 -0700184
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800185 final Rect mTempRect; // used in the transaction to not thrash the heap.
186 final Rect mVisRect; // used to retrieve visible rect of focused view.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800187
188 boolean mTraversalScheduled;
189 boolean mWillDrawSoon;
190 boolean mLayoutRequested;
191 boolean mFirst;
192 boolean mReportNextDraw;
193 boolean mFullRedrawNeeded;
194 boolean mNewSurfaceNeeded;
195 boolean mHasHadWindowFocus;
196 boolean mLastWasImTarget;
197
198 boolean mWindowAttributesChanged = false;
199
200 // These can be accessed by any thread, must be protected with a lock.
Mathias Agopian5583dc62009-07-09 16:28:11 -0700201 // Surface can never be reassigned or cleared (use Surface.clear()).
202 private final Surface mSurface = new Surface();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800203
204 boolean mAdded;
205 boolean mAddedTouchMode;
206
207 /*package*/ int mAddNesting;
208
209 // These are accessed by multiple threads.
210 final Rect mWinFrame; // frame given by window manager.
211
212 final Rect mPendingVisibleInsets = new Rect();
213 final Rect mPendingContentInsets = new Rect();
214 final ViewTreeObserver.InternalInsetsInfo mLastGivenInsets
215 = new ViewTreeObserver.InternalInsetsInfo();
216
Dianne Hackborn694f79b2010-03-17 19:44:59 -0700217 final Configuration mLastConfiguration = new Configuration();
218 final Configuration mPendingConfiguration = new Configuration();
219
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800220 class ResizedInfo {
221 Rect coveredInsets;
222 Rect visibleInsets;
223 Configuration newConfig;
224 }
225
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800226 boolean mScrollMayChange;
227 int mSoftInputMode;
228 View mLastScrolledFocus;
229 int mScrollY;
230 int mCurScrollY;
231 Scroller mScroller;
Dianne Hackborn0f761d62010-11-30 22:06:10 -0800232 Bitmap mResizeBitmap;
233 long mResizeBitmapStartTime;
234 int mResizeBitmapDuration;
235 static final Interpolator mResizeInterpolator = new AccelerateDecelerateInterpolator();
Romain Guy8506ab42009-06-11 17:35:47 -0700236
Romain Guy8506ab42009-06-11 17:35:47 -0700237 final ViewConfiguration mViewConfiguration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800238
Christopher Tatea53146c2010-09-07 11:57:52 -0700239 /* Drag/drop */
240 ClipDescription mDragDescription;
241 View mCurrentDragView;
Christopher Tate7fb8b562011-01-20 13:46:41 -0800242 volatile Object mLocalDragState;
Christopher Tatea53146c2010-09-07 11:57:52 -0700243 final PointF mDragPoint = new PointF();
Christopher Tate2c095f32010-10-04 14:13:40 -0700244 final PointF mLastTouchPoint = new PointF();
Christopher Tatea53146c2010-09-07 11:57:52 -0700245
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800246 /**
247 * see {@link #playSoundEffect(int)}
248 */
249 AudioManager mAudioManager;
250
Dianne Hackborn11ea3342009-07-22 21:48:55 -0700251 private final int mDensity;
Adam Powellb08013c2010-09-16 16:28:11 -0700252
Dianne Hackborn4c62fc02009-08-08 20:40:27 -0700253 public static IWindowSession getWindowSession(Looper mainLooper) {
254 synchronized (mStaticInit) {
255 if (!mInitialized) {
256 try {
257 InputMethodManager imm = InputMethodManager.getInstance(mainLooper);
258 sWindowSession = IWindowManager.Stub.asInterface(
259 ServiceManager.getService("window"))
260 .openSession(imm.getClient(), imm.getInputContext());
261 mInitialized = true;
262 } catch (RemoteException e) {
263 }
264 }
265 return sWindowSession;
266 }
267 }
268
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800269 public ViewRoot(Context context) {
270 super();
271
Romain Guy812ccbe2010-06-01 14:07:24 -0700272 if (MEASURE_LATENCY) {
273 if (lt == null) {
274 lt = new LatencyTimer(100, 1000);
275 }
Michael Chan53071d62009-05-13 17:29:48 -0700276 }
277
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800278 // Initialize the statics when this class is first instantiated. This is
279 // done here instead of in the static block because Zygote does not
280 // allow the spawning of threads.
Dianne Hackborn4c62fc02009-08-08 20:40:27 -0700281 getWindowSession(context.getMainLooper());
282
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800283 mThread = Thread.currentThread();
284 mLocation = new WindowLeaked(null);
285 mLocation.fillInStackTrace();
286 mWidth = -1;
287 mHeight = -1;
288 mDirty = new Rect();
289 mTempRect = new Rect();
290 mVisRect = new Rect();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800291 mWinFrame = new Rect();
Romain Guyfb8b7632010-08-23 21:05:08 -0700292 mWindow = new W(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800293 mInputMethodCallback = new InputMethodCallback(this);
294 mViewVisibility = View.GONE;
295 mTransparentRegion = new Region();
296 mPreviousTransparentRegion = new Region();
297 mFirst = true; // true for the first time the view is added
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800298 mAdded = false;
299 mAttachInfo = new View.AttachInfo(sWindowSession, mWindow, this, this);
300 mViewConfiguration = ViewConfiguration.get(context);
Dianne Hackborn11ea3342009-07-22 21:48:55 -0700301 mDensity = context.getResources().getDisplayMetrics().densityDpi;
Joe Onorato86f67862010-11-05 18:57:34 -0700302 mFallbackEventHandler = PolicyManager.makeNewFallbackEventHandler(context);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800303 }
304
Dianne Hackborn2a9094d2010-02-03 19:20:09 -0800305 public static void addFirstDrawHandler(Runnable callback) {
306 synchronized (sFirstDrawHandlers) {
307 if (!sFirstDrawComplete) {
308 sFirstDrawHandlers.add(callback);
309 }
310 }
311 }
312
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800313 public static void addConfigCallback(ComponentCallbacks callback) {
314 synchronized (sConfigCallbacks) {
315 sConfigCallbacks.add(callback);
316 }
317 }
318
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800319 // FIXME for perf testing only
320 private boolean mProfile = false;
321
322 /**
323 * Call this to profile the next traversal call.
324 * FIXME for perf testing only. Remove eventually
325 */
326 public void profile() {
327 mProfile = true;
328 }
329
330 /**
331 * Indicates whether we are in touch mode. Calling this method triggers an IPC
332 * call and should be avoided whenever possible.
333 *
334 * @return True, if the device is in touch mode, false otherwise.
335 *
336 * @hide
337 */
338 static boolean isInTouchMode() {
339 if (mInitialized) {
340 try {
341 return sWindowSession.getInTouchMode();
342 } catch (RemoteException e) {
343 }
344 }
345 return false;
346 }
347
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800348 /**
349 * We have one child
350 */
Romain Guye4d01122010-06-16 18:44:05 -0700351 public void setView(View view, WindowManager.LayoutParams attrs, View panelParentView) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800352 synchronized (this) {
353 if (mView == null) {
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700354 mView = view;
Joe Onorato86f67862010-11-05 18:57:34 -0700355 mFallbackEventHandler.setView(view);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700356 mWindowAttributes.copyFrom(attrs);
Mitsuru Oshima1ecf5d22009-07-06 17:20:38 -0700357 attrs = mWindowAttributes;
Romain Guye4d01122010-06-16 18:44:05 -0700358
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700359 if (view instanceof RootViewSurfaceTaker) {
360 mSurfaceHolderCallback =
361 ((RootViewSurfaceTaker)view).willYouTakeTheSurface();
362 if (mSurfaceHolderCallback != null) {
363 mSurfaceHolder = new TakenSurfaceHolder();
Dianne Hackborn289b9b62010-07-09 11:44:11 -0700364 mSurfaceHolder.setFormat(PixelFormat.UNKNOWN);
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700365 }
366 }
Romain Guy1aec9a22011-01-05 09:37:12 -0800367
368 // If the application owns the surface, don't enable hardware acceleration
369 if (mSurfaceHolder == null) {
370 enableHardwareAcceleration(attrs);
371 }
372
Mitsuru Oshima38ed7d772009-07-21 14:39:34 -0700373 Resources resources = mView.getContext().getResources();
374 CompatibilityInfo compatibilityInfo = resources.getCompatibilityInfo();
Mitsuru Oshima589cebe2009-07-22 20:38:58 -0700375 mTranslator = compatibilityInfo.getTranslator();
Mitsuru Oshima38ed7d772009-07-21 14:39:34 -0700376
377 if (mTranslator != null || !compatibilityInfo.supportsScreen()) {
Mitsuru Oshima240f8a72009-07-22 20:39:14 -0700378 mSurface.setCompatibleDisplayMetrics(resources.getDisplayMetrics(),
379 mTranslator);
Mitsuru Oshima38ed7d772009-07-21 14:39:34 -0700380 }
381
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -0700382 boolean restore = false;
Romain Guy35b38ce2009-10-07 13:38:55 -0700383 if (mTranslator != null) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -0700384 restore = true;
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700385 attrs.backup();
386 mTranslator.translateWindowLayout(attrs);
Mitsuru Oshima3d914922009-05-13 22:29:15 -0700387 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700388 if (DEBUG_LAYOUT) Log.d(TAG, "WindowLayout in setView:" + attrs);
389
Mitsuru Oshima1ecf5d22009-07-06 17:20:38 -0700390 if (!compatibilityInfo.supportsScreen()) {
391 attrs.flags |= WindowManager.LayoutParams.FLAG_COMPATIBLE_WINDOW;
392 }
393
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800394 mSoftInputMode = attrs.softInputMode;
395 mWindowAttributesChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800396 mAttachInfo.mRootView = view;
Romain Guy35b38ce2009-10-07 13:38:55 -0700397 mAttachInfo.mScalingRequired = mTranslator != null;
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700398 mAttachInfo.mApplicationScale =
399 mTranslator == null ? 1.0f : mTranslator.applicationScale;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800400 if (panelParentView != null) {
401 mAttachInfo.mPanelParentWindowToken
402 = panelParentView.getApplicationWindowToken();
403 }
404 mAdded = true;
405 int res; /* = WindowManagerImpl.ADD_OKAY; */
Romain Guy8506ab42009-06-11 17:35:47 -0700406
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800407 // Schedule the first layout -before- adding to the window
408 // manager, to make sure we do the relayout before receiving
409 // any other events from the system.
410 requestLayout();
Jeff Brown46b9ac02010-04-22 18:58:52 -0700411 mInputChannel = new InputChannel();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800412 try {
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700413 res = sWindowSession.add(mWindow, mWindowAttributes,
Jeff Brown46b9ac02010-04-22 18:58:52 -0700414 getHostVisibility(), mAttachInfo.mContentInsets,
415 mInputChannel);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800416 } catch (RemoteException e) {
417 mAdded = false;
418 mView = null;
419 mAttachInfo.mRootView = null;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700420 mInputChannel = null;
Joe Onorato86f67862010-11-05 18:57:34 -0700421 mFallbackEventHandler.setView(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800422 unscheduleTraversals();
423 throw new RuntimeException("Adding window failed", e);
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700424 } finally {
425 if (restore) {
426 attrs.restore();
427 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800428 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700429
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700430 if (mTranslator != null) {
431 mTranslator.translateRectInScreenToAppWindow(mAttachInfo.mContentInsets);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700432 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800433 mPendingContentInsets.set(mAttachInfo.mContentInsets);
434 mPendingVisibleInsets.set(0, 0, 0, 0);
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800435 if (DEBUG_LAYOUT) Log.v(TAG, "Added window " + mWindow);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800436 if (res < WindowManagerImpl.ADD_OKAY) {
437 mView = null;
438 mAttachInfo.mRootView = null;
439 mAdded = false;
Joe Onorato86f67862010-11-05 18:57:34 -0700440 mFallbackEventHandler.setView(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800441 unscheduleTraversals();
442 switch (res) {
443 case WindowManagerImpl.ADD_BAD_APP_TOKEN:
444 case WindowManagerImpl.ADD_BAD_SUBWINDOW_TOKEN:
445 throw new WindowManagerImpl.BadTokenException(
446 "Unable to add window -- token " + attrs.token
447 + " is not valid; is your activity running?");
448 case WindowManagerImpl.ADD_NOT_APP_TOKEN:
449 throw new WindowManagerImpl.BadTokenException(
450 "Unable to add window -- token " + attrs.token
451 + " is not for an application");
452 case WindowManagerImpl.ADD_APP_EXITING:
453 throw new WindowManagerImpl.BadTokenException(
454 "Unable to add window -- app for token " + attrs.token
455 + " is exiting");
456 case WindowManagerImpl.ADD_DUPLICATE_ADD:
457 throw new WindowManagerImpl.BadTokenException(
458 "Unable to add window -- window " + mWindow
459 + " has already been added");
460 case WindowManagerImpl.ADD_STARTING_NOT_NEEDED:
461 // Silently ignore -- we would have just removed it
462 // right away, anyway.
463 return;
464 case WindowManagerImpl.ADD_MULTIPLE_SINGLETON:
465 throw new WindowManagerImpl.BadTokenException(
466 "Unable to add window " + mWindow +
467 " -- another window of this type already exists");
468 case WindowManagerImpl.ADD_PERMISSION_DENIED:
469 throw new WindowManagerImpl.BadTokenException(
470 "Unable to add window " + mWindow +
471 " -- permission denied for this window type");
472 }
473 throw new RuntimeException(
474 "Unable to add window -- unknown error code " + res);
475 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700476
Jeff Brown00fa7bd2010-07-02 15:37:36 -0700477 if (view instanceof RootViewSurfaceTaker) {
478 mInputQueueCallback =
479 ((RootViewSurfaceTaker)view).willYouTakeTheInputQueue();
480 }
481 if (mInputQueueCallback != null) {
482 mInputQueue = new InputQueue(mInputChannel);
483 mInputQueueCallback.onInputQueueCreated(mInputQueue);
484 } else {
485 InputQueue.registerInputChannel(mInputChannel, mInputHandler,
486 Looper.myQueue());
Jeff Brown46b9ac02010-04-22 18:58:52 -0700487 }
488
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800489 view.assignParent(this);
490 mAddedTouchMode = (res&WindowManagerImpl.ADD_FLAG_IN_TOUCH_MODE) != 0;
491 mAppVisible = (res&WindowManagerImpl.ADD_FLAG_APP_VISIBLE) != 0;
492 }
493 }
494 }
495
Romain Guy529b60a2010-08-03 18:05:47 -0700496 private void enableHardwareAcceleration(WindowManager.LayoutParams attrs) {
Dianne Hackborn7eec10e2010-11-12 18:03:47 -0800497 mAttachInfo.mHardwareAccelerated = false;
498 mAttachInfo.mHardwareAccelerationRequested = false;
Romain Guy4f6aff32011-01-12 16:21:41 -0800499
Dianne Hackborn7eec10e2010-11-12 18:03:47 -0800500 // Try to enable hardware acceleration if requested
Jim Miller1b365922011-03-09 19:38:07 -0800501 final boolean hardwareAccelerated =
502 (attrs.flags & WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED) != 0;
503
504 if (attrs != null && hardwareAccelerated) {
Dianne Hackborn7eec10e2010-11-12 18:03:47 -0800505 // Only enable hardware acceleration if we are not in the system process
506 // The window manager creates ViewRoots to display animated preview windows
507 // of launching apps and we don't want those to be hardware accelerated
Jim Miller1b365922011-03-09 19:38:07 -0800508
509 final boolean systemHwAccelerated =
510 (attrs.flags & WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED_SYSTEM) != 0;
511
512 if (!HardwareRenderer.sRendererDisabled || systemHwAccelerated) {
Romain Guyff26a0c2011-01-20 11:35:46 -0800513 // Don't enable hardware acceleration when we're not on the main thread
Jim Miller1b365922011-03-09 19:38:07 -0800514 if (!systemHwAccelerated && Looper.getMainLooper() != Looper.myLooper()) {
515 Log.w(HardwareRenderer.LOG_TAG, "Attempting to initialize hardware "
Romain Guyff26a0c2011-01-20 11:35:46 -0800516 + "acceleration outside of the main thread, aborting");
517 return;
518 }
519
Romain Guye4d01122010-06-16 18:44:05 -0700520 final boolean translucent = attrs.format != PixelFormat.OPAQUE;
Romain Guyb051e892010-09-28 19:09:36 -0700521 if (mAttachInfo.mHardwareRenderer != null) {
522 mAttachInfo.mHardwareRenderer.destroy(true);
Romain Guy4caa4ed2010-08-25 14:46:24 -0700523 }
Romain Guyb051e892010-09-28 19:09:36 -0700524 mAttachInfo.mHardwareRenderer = HardwareRenderer.createGlRenderer(2, translucent);
Dianne Hackborn7eec10e2010-11-12 18:03:47 -0800525 mAttachInfo.mHardwareAccelerated = mAttachInfo.mHardwareAccelerationRequested
526 = mAttachInfo.mHardwareRenderer != null;
527 } else if (HardwareRenderer.isAvailable()) {
528 mAttachInfo.mHardwareAccelerationRequested = true;
Romain Guye4d01122010-06-16 18:44:05 -0700529 }
530 }
531 }
532
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800533 public View getView() {
534 return mView;
535 }
536
537 final WindowLeaked getLocation() {
538 return mLocation;
539 }
540
541 void setLayoutParams(WindowManager.LayoutParams attrs, boolean newView) {
542 synchronized (this) {
The Android Open Source Project10592532009-03-18 17:39:46 -0700543 int oldSoftInputMode = mWindowAttributes.softInputMode;
Mitsuru Oshima5a2b91d2009-07-16 16:30:02 -0700544 // preserve compatible window flag if exists.
545 int compatibleWindowFlag =
546 mWindowAttributes.flags & WindowManager.LayoutParams.FLAG_COMPATIBLE_WINDOW;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800547 mWindowAttributes.copyFrom(attrs);
Mitsuru Oshima5a2b91d2009-07-16 16:30:02 -0700548 mWindowAttributes.flags |= compatibleWindowFlag;
549
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800550 if (newView) {
551 mSoftInputMode = attrs.softInputMode;
552 requestLayout();
553 }
The Android Open Source Project10592532009-03-18 17:39:46 -0700554 // Don't lose the mode we last auto-computed.
555 if ((attrs.softInputMode&WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST)
556 == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED) {
557 mWindowAttributes.softInputMode = (mWindowAttributes.softInputMode
558 & ~WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST)
559 | (oldSoftInputMode
560 & WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST);
561 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800562 mWindowAttributesChanged = true;
563 scheduleTraversals();
564 }
565 }
566
567 void handleAppVisibility(boolean visible) {
568 if (mAppVisible != visible) {
569 mAppVisible = visible;
570 scheduleTraversals();
571 }
572 }
573
574 void handleGetNewSurface() {
575 mNewSurfaceNeeded = true;
576 mFullRedrawNeeded = true;
577 scheduleTraversals();
578 }
579
580 /**
581 * {@inheritDoc}
582 */
583 public void requestLayout() {
584 checkThread();
585 mLayoutRequested = true;
586 scheduleTraversals();
587 }
588
589 /**
590 * {@inheritDoc}
591 */
592 public boolean isLayoutRequested() {
593 return mLayoutRequested;
594 }
595
596 public void invalidateChild(View child, Rect dirty) {
597 checkThread();
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700598 if (DEBUG_DRAW) Log.v(TAG, "Invalidate child: " + dirty);
Chet Haase70d4ba12010-10-06 09:46:45 -0700599 if (dirty == null) {
600 // Fast invalidation for GL-enabled applications; GL must redraw everything
601 invalidate();
602 return;
603 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700604 if (mCurScrollY != 0 || mTranslator != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800605 mTempRect.set(dirty);
Romain Guy1e095972009-07-07 11:22:45 -0700606 dirty = mTempRect;
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700607 if (mCurScrollY != 0) {
Romain Guy1e095972009-07-07 11:22:45 -0700608 dirty.offset(0, -mCurScrollY);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700609 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700610 if (mTranslator != null) {
Romain Guy1e095972009-07-07 11:22:45 -0700611 mTranslator.translateRectInAppWindowToScreen(dirty);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700612 }
Romain Guy1e095972009-07-07 11:22:45 -0700613 if (mAttachInfo.mScalingRequired) {
614 dirty.inset(-1, -1);
615 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800616 }
Chet Haasedaf98e92011-01-10 14:10:36 -0800617 if (!mDirty.isEmpty() && !mDirty.contains(dirty)) {
Romain Guy7d695942010-12-01 17:22:29 -0800618 mAttachInfo.mIgnoreDirtyState = true;
619 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800620 mDirty.union(dirty);
621 if (!mWillDrawSoon) {
622 scheduleTraversals();
623 }
624 }
Romain Guy0d9275e2010-10-26 14:22:30 -0700625
626 void invalidate() {
627 mDirty.set(0, 0, mWidth, mHeight);
628 scheduleTraversals();
629 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800630
Dianne Hackbornce418e62011-03-01 14:31:38 -0800631 void setStopped(boolean stopped) {
632 if (mStopped != stopped) {
633 mStopped = stopped;
634 if (!stopped) {
635 scheduleTraversals();
636 }
637 }
638 }
639
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800640 public ViewParent getParent() {
641 return null;
642 }
643
644 public ViewParent invalidateChildInParent(final int[] location, final Rect dirty) {
645 invalidateChild(null, dirty);
646 return null;
647 }
648
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700649 public boolean getChildVisibleRect(View child, Rect r, android.graphics.Point offset) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800650 if (child != mView) {
651 throw new RuntimeException("child is not mine, honest!");
652 }
653 // Note: don't apply scroll offset, because we want to know its
654 // visibility in the virtual canvas being given to the view hierarchy.
655 return r.intersect(0, 0, mWidth, mHeight);
656 }
657
658 public void bringChildToFront(View child) {
659 }
660
661 public void scheduleTraversals() {
662 if (!mTraversalScheduled) {
663 mTraversalScheduled = true;
664 sendEmptyMessage(DO_TRAVERSAL);
665 }
666 }
667
668 public void unscheduleTraversals() {
669 if (mTraversalScheduled) {
670 mTraversalScheduled = false;
671 removeMessages(DO_TRAVERSAL);
672 }
673 }
674
675 int getHostVisibility() {
676 return mAppVisible ? mView.getVisibility() : View.GONE;
677 }
Romain Guy8506ab42009-06-11 17:35:47 -0700678
Dianne Hackborn0f761d62010-11-30 22:06:10 -0800679 void disposeResizeBitmap() {
680 if (mResizeBitmap != null) {
681 mResizeBitmap.recycle();
682 mResizeBitmap = null;
683 }
684 }
685
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800686 private void performTraversals() {
687 // cache mView since it is used so much below...
688 final View host = mView;
689
690 if (DBG) {
691 System.out.println("======================================");
692 System.out.println("performTraversals");
693 host.debug();
694 }
695
696 if (host == null || !mAdded)
697 return;
698
699 mTraversalScheduled = false;
700 mWillDrawSoon = true;
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800701 boolean windowSizeMayChange = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800702 boolean fullRedrawNeeded = mFullRedrawNeeded;
703 boolean newSurface = false;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700704 boolean surfaceChanged = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800705 WindowManager.LayoutParams lp = mWindowAttributes;
706
707 int desiredWindowWidth;
708 int desiredWindowHeight;
709 int childWidthMeasureSpec;
710 int childHeightMeasureSpec;
711
712 final View.AttachInfo attachInfo = mAttachInfo;
713
714 final int viewVisibility = getHostVisibility();
715 boolean viewVisibilityChanged = mViewVisibility != viewVisibility
716 || mNewSurfaceNeeded;
717
718 WindowManager.LayoutParams params = null;
719 if (mWindowAttributesChanged) {
720 mWindowAttributesChanged = false;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700721 surfaceChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800722 params = lp;
723 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700724 Rect frame = mWinFrame;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800725 if (mFirst) {
726 fullRedrawNeeded = true;
727 mLayoutRequested = true;
728
Romain Guy8506ab42009-06-11 17:35:47 -0700729 DisplayMetrics packageMetrics =
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700730 mView.getContext().getResources().getDisplayMetrics();
731 desiredWindowWidth = packageMetrics.widthPixels;
732 desiredWindowHeight = packageMetrics.heightPixels;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800733
734 // For the very first time, tell the view hierarchy that it
735 // is attached to the window. Note that at this point the surface
736 // object is not initialized to its backing store, but soon it
737 // will be (assuming the window is visible).
738 attachInfo.mSurface = mSurface;
Romain Guyc5d55862011-01-21 19:01:46 -0800739 // We used to use the following condition to choose 32 bits drawing caches:
740 // PixelFormat.hasAlpha(lp.format) || lp.format == PixelFormat.RGBX_8888
741 // However, windows are now always 32 bits by default, so choose 32 bits
742 attachInfo.mUse32BitDrawingCache = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800743 attachInfo.mHasWindowFocus = false;
744 attachInfo.mWindowVisibility = viewVisibility;
745 attachInfo.mRecomputeGlobalAttributes = false;
746 attachInfo.mKeepScreenOn = false;
Joe Onorato664644d2011-01-23 17:53:23 -0800747 attachInfo.mSystemUiVisibility = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800748 viewVisibilityChanged = false;
Dianne Hackborn694f79b2010-03-17 19:44:59 -0700749 mLastConfiguration.setTo(host.getResources().getConfiguration());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800750 host.dispatchAttachedToWindow(attachInfo, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800751 //Log.i(TAG, "Screen on initialized: " + attachInfo.mKeepScreenOn);
svetoslavganov75986cf2009-05-14 22:28:01 -0700752
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800753 } else {
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700754 desiredWindowWidth = frame.width();
755 desiredWindowHeight = frame.height();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800756 if (desiredWindowWidth != mWidth || desiredWindowHeight != mHeight) {
Jeff Brownc5ed5912010-07-14 18:48:53 -0700757 if (DEBUG_ORIENTATION) Log.v(TAG,
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700758 "View " + host + " resized to: " + frame);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800759 fullRedrawNeeded = true;
760 mLayoutRequested = true;
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800761 windowSizeMayChange = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800762 }
763 }
764
765 if (viewVisibilityChanged) {
766 attachInfo.mWindowVisibility = viewVisibility;
767 host.dispatchWindowVisibilityChanged(viewVisibility);
768 if (viewVisibility != View.VISIBLE || mNewSurfaceNeeded) {
Romain Guyb051e892010-09-28 19:09:36 -0700769 if (mAttachInfo.mHardwareRenderer != null) {
770 mAttachInfo.mHardwareRenderer.destroy(false);
Romain Guy4caa4ed2010-08-25 14:46:24 -0700771 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800772 }
773 if (viewVisibility == View.GONE) {
774 // After making a window gone, we will count it as being
775 // shown for the first time the next time it gets focus.
776 mHasHadWindowFocus = false;
777 }
778 }
779
780 boolean insetsChanged = false;
Romain Guy8506ab42009-06-11 17:35:47 -0700781
Dianne Hackbornce418e62011-03-01 14:31:38 -0800782 if (mLayoutRequested && !mStopped) {
Romain Guy15df6702009-08-17 20:17:30 -0700783 // Execute enqueued actions on every layout in case a view that was detached
784 // enqueued an action after being detached
785 getRunQueue().executeActions(attachInfo.mHandler);
786
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800787 final Resources res = mView.getContext().getResources();
788
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800789 if (mFirst) {
790 host.fitSystemWindows(mAttachInfo.mContentInsets);
791 // make sure touch mode code executes by setting cached value
792 // to opposite of the added touch mode.
793 mAttachInfo.mInTouchMode = !mAddedTouchMode;
Romain Guy2d4cff62010-04-09 15:39:00 -0700794 ensureTouchModeLocally(mAddedTouchMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800795 } else {
796 if (!mAttachInfo.mContentInsets.equals(mPendingContentInsets)) {
Dianne Hackborn0f761d62010-11-30 22:06:10 -0800797 if (mWidth > 0 && mHeight > 0 &&
798 mSurface != null && mSurface.isValid() &&
Dianne Hackborn63042d62011-01-26 18:56:29 -0800799 !mAttachInfo.mTurnOffWindowResizeAnim &&
Dianne Hackborn0f761d62010-11-30 22:06:10 -0800800 mAttachInfo.mHardwareRenderer != null &&
801 mAttachInfo.mHardwareRenderer.isEnabled() &&
802 lp != null && !PixelFormat.formatHasAlpha(lp.format)) {
803
804 disposeResizeBitmap();
805
806 boolean completed = false;
807 try {
808 mResizeBitmap = Bitmap.createBitmap(mWidth, mHeight,
809 Bitmap.Config.ARGB_8888);
810 mResizeBitmap.setHasAlpha(false);
811 Canvas canvas = new Canvas(mResizeBitmap);
Romain Guyf90f8172011-01-25 22:53:24 -0800812 canvas.drawColor(0xff000000, PorterDuff.Mode.SRC);
Dianne Hackborn0f761d62010-11-30 22:06:10 -0800813 int yoff;
814 final boolean scrolling = mScroller != null
815 && mScroller.computeScrollOffset();
816 if (scrolling) {
817 yoff = mScroller.getCurrY();
818 mScroller.abortAnimation();
819 } else {
820 yoff = mScrollY;
821 }
822 canvas.translate(0, -yoff);
823 if (mTranslator != null) {
824 mTranslator.translateCanvas(canvas);
825 }
826 canvas.setScreenDensity(mAttachInfo.mScalingRequired
827 ? DisplayMetrics.DENSITY_DEVICE : 0);
828 mView.draw(canvas);
829 mResizeBitmapStartTime = SystemClock.uptimeMillis();
830 mResizeBitmapDuration = mView.getResources().getInteger(
831 com.android.internal.R.integer.config_mediumAnimTime);
832 completed = true;
833 } catch (OutOfMemoryError e) {
834 Log.w(TAG, "Not enough memory for content change anim buffer", e);
835 } finally {
836 if (!completed) {
837 mResizeBitmap = null;
838 }
839 }
840 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800841 mAttachInfo.mContentInsets.set(mPendingContentInsets);
842 host.fitSystemWindows(mAttachInfo.mContentInsets);
843 insetsChanged = true;
844 if (DEBUG_LAYOUT) Log.v(TAG, "Content insets changing to: "
845 + mAttachInfo.mContentInsets);
846 }
847 if (!mAttachInfo.mVisibleInsets.equals(mPendingVisibleInsets)) {
848 mAttachInfo.mVisibleInsets.set(mPendingVisibleInsets);
849 if (DEBUG_LAYOUT) Log.v(TAG, "Visible insets changing to: "
850 + mAttachInfo.mVisibleInsets);
851 }
852 if (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT
853 || lp.height == ViewGroup.LayoutParams.WRAP_CONTENT) {
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800854 windowSizeMayChange = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800855
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800856 DisplayMetrics packageMetrics = res.getDisplayMetrics();
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700857 desiredWindowWidth = packageMetrics.widthPixels;
858 desiredWindowHeight = packageMetrics.heightPixels;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800859 }
860 }
861
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800862 // Ask host how big it wants to be
Jeff Brownc5ed5912010-07-14 18:48:53 -0700863 if (DEBUG_ORIENTATION || DEBUG_LAYOUT) Log.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800864 "Measuring " + host + " in display " + desiredWindowWidth
865 + "x" + desiredWindowHeight + "...");
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800866
867 boolean goodMeasure = false;
868 if (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT
869 || lp.height == ViewGroup.LayoutParams.WRAP_CONTENT) {
870 // On large screens, we don't want to allow dialogs to just
871 // stretch to fill the entire width of the screen to display
872 // one line of text. First try doing the layout at a smaller
873 // size to see if it will fit.
874 final DisplayMetrics packageMetrics = res.getDisplayMetrics();
875 res.getValue(com.android.internal.R.dimen.config_prefDialogWidth, mTmpValue, true);
876 int baseSize = 0;
877 if (mTmpValue.type == TypedValue.TYPE_DIMENSION) {
878 baseSize = (int)mTmpValue.getDimension(packageMetrics);
879 }
880 if (DEBUG_DIALOG) Log.v(TAG, "Window " + mView + ": baseSize=" + baseSize);
Dianne Hackborn7d3a5bc2010-11-29 22:52:12 -0800881 if (baseSize != 0 && desiredWindowWidth > baseSize) {
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800882 childWidthMeasureSpec = getRootMeasureSpec(baseSize, lp.width);
883 childHeightMeasureSpec = getRootMeasureSpec(desiredWindowHeight, lp.height);
884 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
885 if (DEBUG_DIALOG) Log.v(TAG, "Window " + mView + ": measured ("
Dianne Hackborn189ee182010-12-02 21:48:53 -0800886 + host.getMeasuredWidth() + "," + host.getMeasuredHeight() + ")");
887 if ((host.getMeasuredWidthAndState()&View.MEASURED_STATE_TOO_SMALL) == 0) {
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800888 goodMeasure = true;
889 } else {
890 // Didn't fit in that size... try expanding a bit.
891 baseSize = (baseSize+desiredWindowWidth)/2;
892 if (DEBUG_DIALOG) Log.v(TAG, "Window " + mView + ": next baseSize="
893 + baseSize);
Dianne Hackborn189ee182010-12-02 21:48:53 -0800894 childWidthMeasureSpec = getRootMeasureSpec(baseSize, lp.width);
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800895 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
896 if (DEBUG_DIALOG) Log.v(TAG, "Window " + mView + ": measured ("
Dianne Hackborn189ee182010-12-02 21:48:53 -0800897 + host.getMeasuredWidth() + "," + host.getMeasuredHeight() + ")");
898 if ((host.getMeasuredWidthAndState()&View.MEASURED_STATE_TOO_SMALL) == 0) {
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800899 if (DEBUG_DIALOG) Log.v(TAG, "Good!");
900 goodMeasure = true;
901 }
902 }
903 }
904 }
905
906 if (!goodMeasure) {
907 childWidthMeasureSpec = getRootMeasureSpec(desiredWindowWidth, lp.width);
908 childHeightMeasureSpec = getRootMeasureSpec(desiredWindowHeight, lp.height);
909 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
Adam Powellaa0b92c2010-12-13 22:38:53 -0800910 if (mWidth != host.getMeasuredWidth() || mHeight != host.getMeasuredHeight()) {
911 windowSizeMayChange = true;
912 }
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800913 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800914
915 if (DBG) {
916 System.out.println("======================================");
917 System.out.println("performTraversals -- after measure");
918 host.debug();
919 }
920 }
921
Romain Guy6e81e572011-01-25 12:52:58 -0800922 if (attachInfo.mRecomputeGlobalAttributes && host.mAttachInfo != null) {
Joe Onorato664644d2011-01-23 17:53:23 -0800923 //Log.i(TAG, "Computing view hierarchy attributes!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800924 attachInfo.mRecomputeGlobalAttributes = false;
Joe Onorato664644d2011-01-23 17:53:23 -0800925 boolean oldScreenOn = attachInfo.mKeepScreenOn;
926 int oldVis = attachInfo.mSystemUiVisibility;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800927 attachInfo.mKeepScreenOn = false;
Joe Onorato664644d2011-01-23 17:53:23 -0800928 attachInfo.mSystemUiVisibility = 0;
929 attachInfo.mHasSystemUiListeners = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800930 host.dispatchCollectViewAttributes(0);
Joe Onorato14782f72011-01-25 19:53:17 -0800931 if (attachInfo.mKeepScreenOn != oldScreenOn
932 || attachInfo.mSystemUiVisibility != oldVis
933 || attachInfo.mHasSystemUiListeners) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800934 params = lp;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800935 }
936 }
937
938 if (mFirst || attachInfo.mViewVisibilityChanged) {
939 attachInfo.mViewVisibilityChanged = false;
940 int resizeMode = mSoftInputMode &
941 WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST;
942 // If we are in auto resize mode, then we need to determine
943 // what mode to use now.
944 if (resizeMode == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED) {
945 final int N = attachInfo.mScrollContainers.size();
946 for (int i=0; i<N; i++) {
947 if (attachInfo.mScrollContainers.get(i).isShown()) {
948 resizeMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE;
949 }
950 }
951 if (resizeMode == 0) {
952 resizeMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN;
953 }
954 if ((lp.softInputMode &
955 WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) != resizeMode) {
956 lp.softInputMode = (lp.softInputMode &
957 ~WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) |
958 resizeMode;
959 params = lp;
960 }
961 }
962 }
Romain Guy8506ab42009-06-11 17:35:47 -0700963
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800964 if (params != null && (host.mPrivateFlags & View.REQUEST_TRANSPARENT_REGIONS) != 0) {
965 if (!PixelFormat.formatHasAlpha(params.format)) {
966 params.format = PixelFormat.TRANSLUCENT;
967 }
968 }
969
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800970 boolean windowShouldResize = mLayoutRequested && windowSizeMayChange
Dianne Hackborn189ee182010-12-02 21:48:53 -0800971 && ((mWidth != host.getMeasuredWidth() || mHeight != host.getMeasuredHeight())
Romain Guy2e4f4262010-04-06 11:07:52 -0700972 || (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT &&
973 frame.width() < desiredWindowWidth && frame.width() != mWidth)
974 || (lp.height == ViewGroup.LayoutParams.WRAP_CONTENT &&
975 frame.height() < desiredWindowHeight && frame.height() != mHeight));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800976
977 final boolean computesInternalInsets =
978 attachInfo.mTreeObserver.hasComputeInternalInsetsListeners();
Romain Guy812ccbe2010-06-01 14:07:24 -0700979
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800980 boolean insetsPending = false;
981 int relayoutResult = 0;
Romain Guy812ccbe2010-06-01 14:07:24 -0700982
983 if (mFirst || windowShouldResize || insetsChanged ||
984 viewVisibilityChanged || params != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800985
986 if (viewVisibility == View.VISIBLE) {
987 // If this window is giving internal insets to the window
988 // manager, and it is being added or changing its visibility,
989 // then we want to first give the window manager "fake"
990 // insets to cause it to effectively ignore the content of
991 // the window during layout. This avoids it briefly causing
992 // other windows to resize/move based on the raw frame of the
993 // window, waiting until we can finish laying out this window
994 // and get back to the window manager with the ultimately
995 // computed insets.
Romain Guy812ccbe2010-06-01 14:07:24 -0700996 insetsPending = computesInternalInsets && (mFirst || viewVisibilityChanged);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800997 }
998
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700999 if (mSurfaceHolder != null) {
1000 mSurfaceHolder.mSurfaceLock.lock();
1001 mDrawingAllowed = true;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001002 }
Romain Guy812ccbe2010-06-01 14:07:24 -07001003
Romain Guyc361da82010-10-25 15:29:10 -07001004 boolean hwInitialized = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001005 boolean contentInsetsChanged = false;
Romain Guy13922e02009-05-12 17:56:14 -07001006 boolean visibleInsetsChanged;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001007 boolean hadSurface = mSurface.isValid();
Romain Guy812ccbe2010-06-01 14:07:24 -07001008
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001009 try {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001010 int fl = 0;
1011 if (params != null) {
1012 fl = params.flags;
1013 if (attachInfo.mKeepScreenOn) {
1014 params.flags |= WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
1015 }
Joe Onorato14782f72011-01-25 19:53:17 -08001016 params.subtreeSystemUiVisibility = attachInfo.mSystemUiVisibility;
1017 params.hasSystemUiListeners = attachInfo.mHasSystemUiListeners
1018 || params.subtreeSystemUiVisibility != 0
1019 || params.systemUiVisibility != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001020 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001021 if (DEBUG_LAYOUT) {
Dianne Hackborn189ee182010-12-02 21:48:53 -08001022 Log.i(TAG, "host=w:" + host.getMeasuredWidth() + ", h:" +
1023 host.getMeasuredHeight() + ", params=" + params);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001024 }
Romain Guy2a83f002011-01-18 18:28:21 -08001025
1026 final int surfaceGenerationId = mSurface.getGenerationId();
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001027 relayoutResult = relayoutWindow(params, viewVisibility, insetsPending);
1028
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001029 if (params != null) {
1030 params.flags = fl;
1031 }
1032
1033 if (DEBUG_LAYOUT) Log.v(TAG, "relayout: frame=" + frame.toShortString()
1034 + " content=" + mPendingContentInsets.toShortString()
1035 + " visible=" + mPendingVisibleInsets.toShortString()
1036 + " surface=" + mSurface);
Romain Guy8506ab42009-06-11 17:35:47 -07001037
Dianne Hackborn694f79b2010-03-17 19:44:59 -07001038 if (mPendingConfiguration.seq != 0) {
1039 if (DEBUG_CONFIGURATION) Log.v(TAG, "Visible with new config: "
1040 + mPendingConfiguration);
1041 updateConfiguration(mPendingConfiguration, !mFirst);
1042 mPendingConfiguration.seq = 0;
1043 }
1044
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001045 contentInsetsChanged = !mPendingContentInsets.equals(
1046 mAttachInfo.mContentInsets);
1047 visibleInsetsChanged = !mPendingVisibleInsets.equals(
1048 mAttachInfo.mVisibleInsets);
1049 if (contentInsetsChanged) {
1050 mAttachInfo.mContentInsets.set(mPendingContentInsets);
1051 host.fitSystemWindows(mAttachInfo.mContentInsets);
1052 if (DEBUG_LAYOUT) Log.v(TAG, "Content insets changing to: "
1053 + mAttachInfo.mContentInsets);
1054 }
1055 if (visibleInsetsChanged) {
1056 mAttachInfo.mVisibleInsets.set(mPendingVisibleInsets);
1057 if (DEBUG_LAYOUT) Log.v(TAG, "Visible insets changing to: "
1058 + mAttachInfo.mVisibleInsets);
1059 }
1060
1061 if (!hadSurface) {
1062 if (mSurface.isValid()) {
1063 // If we are creating a new surface, then we need to
1064 // completely redraw it. Also, when we get to the
1065 // point of drawing it we will hold off and schedule
1066 // a new traversal instead. This is so we can tell the
1067 // window manager about all of the windows being displayed
1068 // before actually drawing them, so it can display then
1069 // all at once.
1070 newSurface = true;
1071 fullRedrawNeeded = true;
Jack Palevich61a6e682009-10-09 17:37:50 -07001072 mPreviousTransparentRegion.setEmpty();
Romain Guy8506ab42009-06-11 17:35:47 -07001073
Romain Guyb051e892010-09-28 19:09:36 -07001074 if (mAttachInfo.mHardwareRenderer != null) {
Dianne Hackborn64825172011-03-02 21:32:58 -08001075 try {
1076 hwInitialized = mAttachInfo.mHardwareRenderer.initialize(mHolder);
1077 } catch (Surface.OutOfResourcesException e) {
1078 Log.e(TAG, "OutOfResourcesException initializing HW surface", e);
1079 try {
1080 if (!sWindowSession.outOfMemory(mWindow)) {
1081 Slog.w(TAG, "No processes killed for memory; killing self");
1082 Process.killProcess(Process.myPid());
1083 }
1084 } catch (RemoteException ex) {
1085 }
1086 mLayoutRequested = true; // ask wm for a new surface next time.
1087 return;
1088 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001089 }
1090 }
1091 } else if (!mSurface.isValid()) {
1092 // If the surface has been removed, then reset the scroll
1093 // positions.
1094 mLastScrolledFocus = null;
1095 mScrollY = mCurScrollY = 0;
1096 if (mScroller != null) {
1097 mScroller.abortAnimation();
1098 }
Dianne Hackborn0f761d62010-11-30 22:06:10 -08001099 disposeResizeBitmap();
Romain Guy2a83f002011-01-18 18:28:21 -08001100 } else if (surfaceGenerationId != mSurface.getGenerationId() &&
1101 mSurfaceHolder == null && mAttachInfo.mHardwareRenderer != null) {
Romain Guy7d7b5492011-01-24 16:33:45 -08001102 fullRedrawNeeded = true;
Dianne Hackborn64825172011-03-02 21:32:58 -08001103 try {
1104 mAttachInfo.mHardwareRenderer.updateSurface(mHolder);
1105 } catch (Surface.OutOfResourcesException e) {
1106 Log.e(TAG, "OutOfResourcesException updating HW surface", e);
1107 try {
1108 if (!sWindowSession.outOfMemory(mWindow)) {
1109 Slog.w(TAG, "No processes killed for memory; killing self");
1110 Process.killProcess(Process.myPid());
1111 }
1112 } catch (RemoteException ex) {
1113 }
1114 mLayoutRequested = true; // ask wm for a new surface next time.
1115 return;
1116 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001117 }
1118 } catch (RemoteException e) {
1119 }
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001120
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001121 if (DEBUG_ORIENTATION) Log.v(
Jeff Brownc5ed5912010-07-14 18:48:53 -07001122 TAG, "Relayout returned: frame=" + frame + ", surface=" + mSurface);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001123
1124 attachInfo.mWindowLeft = frame.left;
1125 attachInfo.mWindowTop = frame.top;
1126
1127 // !!FIXME!! This next section handles the case where we did not get the
1128 // window size we asked for. We should avoid this by getting a maximum size from
1129 // the window session beforehand.
1130 mWidth = frame.width();
1131 mHeight = frame.height();
1132
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001133 if (mSurfaceHolder != null) {
1134 // The app owns the surface; tell it about what is going on.
1135 if (mSurface.isValid()) {
1136 // XXX .copyFrom() doesn't work!
1137 //mSurfaceHolder.mSurface.copyFrom(mSurface);
1138 mSurfaceHolder.mSurface = mSurface;
1139 }
Jeff Brown30bc34f2011-01-25 12:56:56 -08001140 mSurfaceHolder.setSurfaceFrameSize(mWidth, mHeight);
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001141 mSurfaceHolder.mSurfaceLock.unlock();
1142 if (mSurface.isValid()) {
1143 if (!hadSurface) {
1144 mSurfaceHolder.ungetCallbacks();
1145
1146 mIsCreating = true;
1147 mSurfaceHolderCallback.surfaceCreated(mSurfaceHolder);
1148 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
1149 if (callbacks != null) {
1150 for (SurfaceHolder.Callback c : callbacks) {
1151 c.surfaceCreated(mSurfaceHolder);
1152 }
1153 }
1154 surfaceChanged = true;
1155 }
1156 if (surfaceChanged) {
1157 mSurfaceHolderCallback.surfaceChanged(mSurfaceHolder,
1158 lp.format, mWidth, mHeight);
1159 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
1160 if (callbacks != null) {
1161 for (SurfaceHolder.Callback c : callbacks) {
1162 c.surfaceChanged(mSurfaceHolder, lp.format,
1163 mWidth, mHeight);
1164 }
1165 }
1166 }
1167 mIsCreating = false;
1168 } else if (hadSurface) {
1169 mSurfaceHolder.ungetCallbacks();
1170 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
1171 mSurfaceHolderCallback.surfaceDestroyed(mSurfaceHolder);
1172 if (callbacks != null) {
1173 for (SurfaceHolder.Callback c : callbacks) {
1174 c.surfaceDestroyed(mSurfaceHolder);
1175 }
1176 }
1177 mSurfaceHolder.mSurfaceLock.lock();
Jozef BABJAK93c5b6a2011-02-22 09:33:19 +01001178 try {
1179 mSurfaceHolder.mSurface = new Surface();
1180 } finally {
1181 mSurfaceHolder.mSurfaceLock.unlock();
1182 }
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001183 }
1184 }
Romain Guy53389bd2010-09-07 17:16:32 -07001185
Romain Guy6b5108b2011-01-04 16:11:10 -08001186 if (hwInitialized || ((windowShouldResize || params != null) &&
Romain Guydbf78bd2010-12-07 17:04:03 -08001187 mAttachInfo.mHardwareRenderer != null &&
1188 mAttachInfo.mHardwareRenderer.isEnabled())) {
Romain Guyb051e892010-09-28 19:09:36 -07001189 mAttachInfo.mHardwareRenderer.setup(mWidth, mHeight);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001190 }
1191
Dianne Hackbornce418e62011-03-01 14:31:38 -08001192 if (!mStopped) {
1193 boolean focusChangedDueToTouchMode = ensureTouchModeLocally(
1194 (relayoutResult&WindowManagerImpl.RELAYOUT_IN_TOUCH_MODE) != 0);
1195 if (focusChangedDueToTouchMode || mWidth != host.getMeasuredWidth()
1196 || mHeight != host.getMeasuredHeight() || contentInsetsChanged) {
1197 childWidthMeasureSpec = getRootMeasureSpec(mWidth, lp.width);
1198 childHeightMeasureSpec = getRootMeasureSpec(mHeight, lp.height);
1199
1200 if (DEBUG_LAYOUT) Log.v(TAG, "Ooops, something changed! mWidth="
1201 + mWidth + " measuredWidth=" + host.getMeasuredWidth()
1202 + " mHeight=" + mHeight
1203 + " measuredHeight=" + host.getMeasuredHeight()
1204 + " coveredInsetsChanged=" + contentInsetsChanged);
1205
1206 // Ask host how big it wants to be
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001207 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
Dianne Hackbornce418e62011-03-01 14:31:38 -08001208
1209 // Implementation of weights from WindowManager.LayoutParams
1210 // We just grow the dimensions as needed and re-measure if
1211 // needs be
1212 int width = host.getMeasuredWidth();
1213 int height = host.getMeasuredHeight();
1214 boolean measureAgain = false;
1215
1216 if (lp.horizontalWeight > 0.0f) {
1217 width += (int) ((mWidth - width) * lp.horizontalWeight);
1218 childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(width,
1219 MeasureSpec.EXACTLY);
1220 measureAgain = true;
1221 }
1222 if (lp.verticalWeight > 0.0f) {
1223 height += (int) ((mHeight - height) * lp.verticalWeight);
1224 childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(height,
1225 MeasureSpec.EXACTLY);
1226 measureAgain = true;
1227 }
1228
1229 if (measureAgain) {
1230 if (DEBUG_LAYOUT) Log.v(TAG,
1231 "And hey let's measure once more: width=" + width
1232 + " height=" + height);
1233 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
1234 }
1235
1236 mLayoutRequested = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001237 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001238 }
1239 }
1240
Dianne Hackbornce418e62011-03-01 14:31:38 -08001241 final boolean didLayout = mLayoutRequested && !mStopped;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001242 boolean triggerGlobalLayoutListener = didLayout
1243 || attachInfo.mRecomputeGlobalAttributes;
1244 if (didLayout) {
1245 mLayoutRequested = false;
1246 mScrollMayChange = true;
1247 if (DEBUG_ORIENTATION || DEBUG_LAYOUT) Log.v(
Jeff Brownc5ed5912010-07-14 18:48:53 -07001248 TAG, "Laying out " + host + " to (" +
Dianne Hackborn189ee182010-12-02 21:48:53 -08001249 host.getMeasuredWidth() + ", " + host.getMeasuredHeight() + ")");
Romain Guy13922e02009-05-12 17:56:14 -07001250 long startTime = 0L;
Romain Guy5429e1d2010-09-07 12:38:00 -07001251 if (ViewDebug.DEBUG_PROFILE_LAYOUT) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001252 startTime = SystemClock.elapsedRealtime();
1253 }
Dianne Hackborn189ee182010-12-02 21:48:53 -08001254 host.layout(0, 0, host.getMeasuredWidth(), host.getMeasuredHeight());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001255
Romain Guy13922e02009-05-12 17:56:14 -07001256 if (Config.DEBUG && ViewDebug.consistencyCheckEnabled) {
1257 if (!host.dispatchConsistencyCheck(ViewDebug.CONSISTENCY_LAYOUT)) {
1258 throw new IllegalStateException("The view hierarchy is an inconsistent state,"
1259 + "please refer to the logs with the tag "
1260 + ViewDebug.CONSISTENCY_LOG_TAG + " for more infomation.");
1261 }
1262 }
1263
Romain Guy5429e1d2010-09-07 12:38:00 -07001264 if (ViewDebug.DEBUG_PROFILE_LAYOUT) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001265 EventLog.writeEvent(60001, SystemClock.elapsedRealtime() - startTime);
1266 }
1267
1268 // By this point all views have been sized and positionned
1269 // We can compute the transparent area
1270
1271 if ((host.mPrivateFlags & View.REQUEST_TRANSPARENT_REGIONS) != 0) {
1272 // start out transparent
1273 // TODO: AVOID THAT CALL BY CACHING THE RESULT?
1274 host.getLocationInWindow(mTmpLocation);
1275 mTransparentRegion.set(mTmpLocation[0], mTmpLocation[1],
1276 mTmpLocation[0] + host.mRight - host.mLeft,
1277 mTmpLocation[1] + host.mBottom - host.mTop);
1278
1279 host.gatherTransparentRegion(mTransparentRegion);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001280 if (mTranslator != null) {
1281 mTranslator.translateRegionInWindowToScreen(mTransparentRegion);
1282 }
1283
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001284 if (!mTransparentRegion.equals(mPreviousTransparentRegion)) {
1285 mPreviousTransparentRegion.set(mTransparentRegion);
1286 // reconfigure window manager
1287 try {
1288 sWindowSession.setTransparentRegion(mWindow, mTransparentRegion);
1289 } catch (RemoteException e) {
1290 }
1291 }
1292 }
1293
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001294 if (DBG) {
1295 System.out.println("======================================");
1296 System.out.println("performTraversals -- after setFrame");
1297 host.debug();
1298 }
1299 }
1300
1301 if (triggerGlobalLayoutListener) {
1302 attachInfo.mRecomputeGlobalAttributes = false;
1303 attachInfo.mTreeObserver.dispatchOnGlobalLayout();
1304 }
1305
1306 if (computesInternalInsets) {
Jeff Brownfbf09772011-01-16 14:06:57 -08001307 // Clear the original insets.
1308 final ViewTreeObserver.InternalInsetsInfo insets = attachInfo.mGivenInternalInsets;
1309 insets.reset();
1310
1311 // Compute new insets in place.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001312 attachInfo.mTreeObserver.dispatchOnComputeInternalInsets(insets);
Jeff Brownfbf09772011-01-16 14:06:57 -08001313
1314 // Tell the window manager.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001315 if (insetsPending || !mLastGivenInsets.equals(insets)) {
1316 mLastGivenInsets.set(insets);
Jeff Brownfbf09772011-01-16 14:06:57 -08001317
1318 // Translate insets to screen coordinates if needed.
1319 final Rect contentInsets;
1320 final Rect visibleInsets;
1321 final Region touchableRegion;
1322 if (mTranslator != null) {
1323 contentInsets = mTranslator.getTranslatedContentInsets(insets.contentInsets);
1324 visibleInsets = mTranslator.getTranslatedVisibleInsets(insets.visibleInsets);
1325 touchableRegion = mTranslator.getTranslatedTouchableArea(insets.touchableRegion);
1326 } else {
1327 contentInsets = insets.contentInsets;
1328 visibleInsets = insets.visibleInsets;
1329 touchableRegion = insets.touchableRegion;
1330 }
1331
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001332 try {
1333 sWindowSession.setInsets(mWindow, insets.mTouchableInsets,
Jeff Brownfbf09772011-01-16 14:06:57 -08001334 contentInsets, visibleInsets, touchableRegion);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001335 } catch (RemoteException e) {
1336 }
1337 }
1338 }
Romain Guy8506ab42009-06-11 17:35:47 -07001339
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001340 if (mFirst) {
1341 // handle first focus request
1342 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: mView.hasFocus()="
1343 + mView.hasFocus());
1344 if (mView != null) {
1345 if (!mView.hasFocus()) {
1346 mView.requestFocus(View.FOCUS_FORWARD);
1347 mFocusedView = mRealFocusedView = mView.findFocus();
1348 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: requested focused view="
1349 + mFocusedView);
1350 } else {
1351 mRealFocusedView = mView.findFocus();
1352 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: existing focused view="
1353 + mRealFocusedView);
1354 }
1355 }
1356 }
1357
1358 mFirst = false;
1359 mWillDrawSoon = false;
1360 mNewSurfaceNeeded = false;
1361 mViewVisibility = viewVisibility;
1362
1363 if (mAttachInfo.mHasWindowFocus) {
1364 final boolean imTarget = WindowManager.LayoutParams
1365 .mayUseInputMethod(mWindowAttributes.flags);
1366 if (imTarget != mLastWasImTarget) {
1367 mLastWasImTarget = imTarget;
1368 InputMethodManager imm = InputMethodManager.peekInstance();
1369 if (imm != null && imTarget) {
1370 imm.startGettingWindowFocus(mView);
1371 imm.onWindowFocus(mView, mView.findFocus(),
1372 mWindowAttributes.softInputMode,
1373 !mHasHadWindowFocus, mWindowAttributes.flags);
1374 }
1375 }
1376 }
Romain Guy8506ab42009-06-11 17:35:47 -07001377
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001378 boolean cancelDraw = attachInfo.mTreeObserver.dispatchOnPreDraw();
1379
1380 if (!cancelDraw && !newSurface) {
1381 mFullRedrawNeeded = false;
1382 draw(fullRedrawNeeded);
1383
1384 if ((relayoutResult&WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0
1385 || mReportNextDraw) {
1386 if (LOCAL_LOGV) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001387 Log.v(TAG, "FINISHED DRAWING: " + mWindowAttributes.getTitle());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001388 }
1389 mReportNextDraw = false;
Dianne Hackbornd76b67c2010-07-13 17:48:30 -07001390 if (mSurfaceHolder != null && mSurface.isValid()) {
1391 mSurfaceHolderCallback.surfaceRedrawNeeded(mSurfaceHolder);
1392 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
1393 if (callbacks != null) {
1394 for (SurfaceHolder.Callback c : callbacks) {
1395 if (c instanceof SurfaceHolder.Callback2) {
1396 ((SurfaceHolder.Callback2)c).surfaceRedrawNeeded(
1397 mSurfaceHolder);
1398 }
1399 }
1400 }
1401 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001402 try {
1403 sWindowSession.finishDrawing(mWindow);
1404 } catch (RemoteException e) {
1405 }
1406 }
1407 } else {
1408 // We were supposed to report when we are done drawing. Since we canceled the
1409 // draw, remember it here.
1410 if ((relayoutResult&WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0) {
1411 mReportNextDraw = true;
1412 }
1413 if (fullRedrawNeeded) {
1414 mFullRedrawNeeded = true;
1415 }
1416 // Try again
1417 scheduleTraversals();
1418 }
1419 }
1420
1421 public void requestTransparentRegion(View child) {
1422 // the test below should not fail unless someone is messing with us
1423 checkThread();
1424 if (mView == child) {
1425 mView.mPrivateFlags |= View.REQUEST_TRANSPARENT_REGIONS;
1426 // Need to make sure we re-evaluate the window attributes next
1427 // time around, to ensure the window has the correct format.
1428 mWindowAttributesChanged = true;
Mathias Agopian1bd80ad2010-11-04 17:13:39 -07001429 requestLayout();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001430 }
1431 }
1432
1433 /**
1434 * Figures out the measure spec for the root view in a window based on it's
1435 * layout params.
1436 *
1437 * @param windowSize
1438 * The available width or height of the window
1439 *
1440 * @param rootDimension
1441 * The layout params for one dimension (width or height) of the
1442 * window.
1443 *
1444 * @return The measure spec to use to measure the root view.
1445 */
1446 private int getRootMeasureSpec(int windowSize, int rootDimension) {
1447 int measureSpec;
1448 switch (rootDimension) {
1449
Romain Guy980a9382010-01-08 15:06:28 -08001450 case ViewGroup.LayoutParams.MATCH_PARENT:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001451 // Window can't resize. Force root view to be windowSize.
1452 measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.EXACTLY);
1453 break;
1454 case ViewGroup.LayoutParams.WRAP_CONTENT:
1455 // Window can resize. Set max size for root view.
1456 measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.AT_MOST);
1457 break;
1458 default:
1459 // Window wants to be an exact size. Force root view to be that size.
1460 measureSpec = MeasureSpec.makeMeasureSpec(rootDimension, MeasureSpec.EXACTLY);
1461 break;
1462 }
1463 return measureSpec;
1464 }
1465
Dianne Hackborn0f761d62010-11-30 22:06:10 -08001466 int mHardwareYOffset;
1467 int mResizeAlpha;
1468 final Paint mResizePaint = new Paint();
1469
1470 public void onHardwarePreDraw(Canvas canvas) {
1471 canvas.translate(0, -mHardwareYOffset);
1472 }
1473
1474 public void onHardwarePostDraw(Canvas canvas) {
1475 if (mResizeBitmap != null) {
1476 canvas.translate(0, mHardwareYOffset);
1477 mResizePaint.setAlpha(mResizeAlpha);
1478 canvas.drawBitmap(mResizeBitmap, 0, 0, mResizePaint);
1479 }
1480 }
1481
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001482 private void draw(boolean fullRedrawNeeded) {
1483 Surface surface = mSurface;
1484 if (surface == null || !surface.isValid()) {
1485 return;
1486 }
1487
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001488 if (!sFirstDrawComplete) {
1489 synchronized (sFirstDrawHandlers) {
1490 sFirstDrawComplete = true;
Romain Guy812ccbe2010-06-01 14:07:24 -07001491 final int count = sFirstDrawHandlers.size();
1492 for (int i = 0; i< count; i++) {
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001493 post(sFirstDrawHandlers.get(i));
1494 }
1495 }
1496 }
1497
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001498 scrollToRectOrFocus(null, false);
1499
1500 if (mAttachInfo.mViewScrollChanged) {
1501 mAttachInfo.mViewScrollChanged = false;
1502 mAttachInfo.mTreeObserver.dispatchOnScrollChanged();
1503 }
Romain Guy8506ab42009-06-11 17:35:47 -07001504
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001505 int yoff;
Dianne Hackborn0f761d62010-11-30 22:06:10 -08001506 boolean animating = mScroller != null && mScroller.computeScrollOffset();
1507 if (animating) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001508 yoff = mScroller.getCurrY();
1509 } else {
1510 yoff = mScrollY;
1511 }
1512 if (mCurScrollY != yoff) {
1513 mCurScrollY = yoff;
1514 fullRedrawNeeded = true;
1515 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001516 float appScale = mAttachInfo.mApplicationScale;
1517 boolean scalingRequired = mAttachInfo.mScalingRequired;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001518
Dianne Hackborn0f761d62010-11-30 22:06:10 -08001519 int resizeAlpha = 0;
1520 if (mResizeBitmap != null) {
1521 long deltaTime = SystemClock.uptimeMillis() - mResizeBitmapStartTime;
1522 if (deltaTime < mResizeBitmapDuration) {
1523 float amt = deltaTime/(float)mResizeBitmapDuration;
1524 amt = mResizeInterpolator.getInterpolation(amt);
1525 animating = true;
1526 resizeAlpha = 255 - (int)(amt*255);
1527 } else {
1528 disposeResizeBitmap();
1529 }
1530 }
1531
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001532 Rect dirty = mDirty;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001533 if (mSurfaceHolder != null) {
1534 // The app owns the surface, we won't draw.
1535 dirty.setEmpty();
Dianne Hackborn0f761d62010-11-30 22:06:10 -08001536 if (animating) {
1537 if (mScroller != null) {
1538 mScroller.abortAnimation();
1539 }
1540 disposeResizeBitmap();
1541 }
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001542 return;
1543 }
Romain Guy58ef7fb2010-09-13 12:52:37 -07001544
1545 if (fullRedrawNeeded) {
1546 mAttachInfo.mIgnoreDirtyState = true;
1547 dirty.union(0, 0, (int) (mWidth * appScale + 0.5f), (int) (mHeight * appScale + 0.5f));
1548 }
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001549
Romain Guyb051e892010-09-28 19:09:36 -07001550 if (mAttachInfo.mHardwareRenderer != null && mAttachInfo.mHardwareRenderer.isEnabled()) {
Romain Guyfd507262010-10-10 15:42:49 -07001551 if (!dirty.isEmpty() || mIsAnimating) {
Romain Guy101e2ae2010-10-11 12:41:21 -07001552 mIsAnimating = false;
Dianne Hackborn0f761d62010-11-30 22:06:10 -08001553 mHardwareYOffset = yoff;
1554 mResizeAlpha = resizeAlpha;
Romain Guy7d7b5492011-01-24 16:33:45 -08001555
1556 mCurrentDirty.set(dirty);
1557 mCurrentDirty.union(mPreviousDirty);
1558 mPreviousDirty.set(dirty);
1559 dirty.setEmpty();
1560
Romain Guyf90f8172011-01-25 22:53:24 -08001561 Rect currentDirty = mCurrentDirty;
1562 if (animating) {
1563 currentDirty = null;
1564 }
1565
1566 mAttachInfo.mHardwareRenderer.draw(mView, mAttachInfo, this, currentDirty);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001567 }
Romain Guy812ccbe2010-06-01 14:07:24 -07001568
Dianne Hackborn0f761d62010-11-30 22:06:10 -08001569 if (animating) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001570 mFullRedrawNeeded = true;
1571 scheduleTraversals();
1572 }
Romain Guy812ccbe2010-06-01 14:07:24 -07001573
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001574 return;
1575 }
1576
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001577 if (DEBUG_ORIENTATION || DEBUG_DRAW) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001578 Log.v(TAG, "Draw " + mView + "/"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001579 + mWindowAttributes.getTitle()
1580 + ": dirty={" + dirty.left + "," + dirty.top
1581 + "," + dirty.right + "," + dirty.bottom + "} surface="
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001582 + surface + " surface.isValid()=" + surface.isValid() + ", appScale:" +
1583 appScale + ", width=" + mWidth + ", height=" + mHeight);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001584 }
1585
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001586 if (!dirty.isEmpty() || mIsAnimating) {
1587 Canvas canvas;
1588 try {
1589 int left = dirty.left;
1590 int top = dirty.top;
1591 int right = dirty.right;
1592 int bottom = dirty.bottom;
Romain Guyfea12b82011-01-27 15:36:40 -08001593
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001594 canvas = surface.lockCanvas(dirty);
Romain Guy5bcdff42009-05-14 21:27:18 -07001595
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001596 if (left != dirty.left || top != dirty.top || right != dirty.right ||
1597 bottom != dirty.bottom) {
1598 mAttachInfo.mIgnoreDirtyState = true;
1599 }
1600
1601 // TODO: Do this in native
1602 canvas.setDensity(mDensity);
1603 } catch (Surface.OutOfResourcesException e) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001604 Log.e(TAG, "OutOfResourcesException locking surface", e);
Dianne Hackborn64825172011-03-02 21:32:58 -08001605 try {
1606 if (!sWindowSession.outOfMemory(mWindow)) {
1607 Slog.w(TAG, "No processes killed for memory; killing self");
1608 Process.killProcess(Process.myPid());
1609 }
1610 } catch (RemoteException ex) {
1611 }
Dianne Hackborn83a6f452011-01-27 17:17:19 -08001612 mLayoutRequested = true; // ask wm for a new surface next time.
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001613 return;
1614 } catch (IllegalArgumentException e) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001615 Log.e(TAG, "IllegalArgumentException locking surface", e);
Dianne Hackborndb773c52011-03-04 16:43:41 -08001616 // Don't assume this is due to out of memory, it could be
1617 // something else, and if it is something else then we could
1618 // kill stuff (or ourself) for no reason.
Dianne Hackborn83a6f452011-01-27 17:17:19 -08001619 mLayoutRequested = true; // ask wm for a new surface next time.
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001620 return;
Romain Guy5bcdff42009-05-14 21:27:18 -07001621 }
1622
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001623 try {
1624 if (!dirty.isEmpty() || mIsAnimating) {
1625 long startTime = 0L;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001626
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001627 if (DEBUG_ORIENTATION || DEBUG_DRAW) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001628 Log.v(TAG, "Surface " + surface + " drawing to bitmap w="
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001629 + canvas.getWidth() + ", h=" + canvas.getHeight());
1630 //canvas.drawARGB(255, 255, 0, 0);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001631 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001632
Romain Guy5429e1d2010-09-07 12:38:00 -07001633 if (ViewDebug.DEBUG_PROFILE_DRAWING) {
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001634 startTime = SystemClock.elapsedRealtime();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001635 }
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001636
1637 // If this bitmap's format includes an alpha channel, we
1638 // need to clear it before drawing so that the child will
1639 // properly re-composite its drawing on a transparent
1640 // background. This automatically respects the clip/dirty region
1641 // or
1642 // If we are applying an offset, we need to clear the area
1643 // where the offset doesn't appear to avoid having garbage
1644 // left in the blank areas.
1645 if (!canvas.isOpaque() || yoff != 0) {
1646 canvas.drawColor(0, PorterDuff.Mode.CLEAR);
1647 }
1648
1649 dirty.setEmpty();
1650 mIsAnimating = false;
1651 mAttachInfo.mDrawingTime = SystemClock.uptimeMillis();
1652 mView.mPrivateFlags |= View.DRAWN;
1653
1654 if (DEBUG_DRAW) {
1655 Context cxt = mView.getContext();
1656 Log.i(TAG, "Drawing: package:" + cxt.getPackageName() +
1657 ", metrics=" + cxt.getResources().getDisplayMetrics() +
1658 ", compatibilityInfo=" + cxt.getResources().getCompatibilityInfo());
1659 }
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001660 try {
1661 canvas.translate(0, -yoff);
1662 if (mTranslator != null) {
1663 mTranslator.translateCanvas(canvas);
1664 }
1665 canvas.setScreenDensity(scalingRequired
1666 ? DisplayMetrics.DENSITY_DEVICE : 0);
1667 mView.draw(canvas);
1668 } finally {
1669 mAttachInfo.mIgnoreDirtyState = false;
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001670 }
1671
1672 if (Config.DEBUG && ViewDebug.consistencyCheckEnabled) {
1673 mView.dispatchConsistencyCheck(ViewDebug.CONSISTENCY_DRAWING);
1674 }
1675
Romain Guy5429e1d2010-09-07 12:38:00 -07001676 if (SHOW_FPS || ViewDebug.DEBUG_SHOW_FPS) {
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001677 int now = (int)SystemClock.elapsedRealtime();
1678 if (sDrawTime != 0) {
1679 nativeShowFPS(canvas, now - sDrawTime);
1680 }
1681 sDrawTime = now;
1682 }
1683
Romain Guy5429e1d2010-09-07 12:38:00 -07001684 if (ViewDebug.DEBUG_PROFILE_DRAWING) {
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001685 EventLog.writeEvent(60000, SystemClock.elapsedRealtime() - startTime);
1686 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001687 }
1688
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001689 } finally {
1690 surface.unlockCanvasAndPost(canvas);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001691 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001692 }
1693
1694 if (LOCAL_LOGV) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001695 Log.v(TAG, "Surface " + surface + " unlockCanvasAndPost");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001696 }
Romain Guy8506ab42009-06-11 17:35:47 -07001697
Dianne Hackborn0f761d62010-11-30 22:06:10 -08001698 if (animating) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001699 mFullRedrawNeeded = true;
1700 scheduleTraversals();
1701 }
1702 }
1703
1704 boolean scrollToRectOrFocus(Rect rectangle, boolean immediate) {
1705 final View.AttachInfo attachInfo = mAttachInfo;
1706 final Rect ci = attachInfo.mContentInsets;
1707 final Rect vi = attachInfo.mVisibleInsets;
1708 int scrollY = 0;
1709 boolean handled = false;
Romain Guy8506ab42009-06-11 17:35:47 -07001710
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001711 if (vi.left > ci.left || vi.top > ci.top
1712 || vi.right > ci.right || vi.bottom > ci.bottom) {
1713 // We'll assume that we aren't going to change the scroll
1714 // offset, since we want to avoid that unless it is actually
1715 // going to make the focus visible... otherwise we scroll
1716 // all over the place.
1717 scrollY = mScrollY;
1718 // We can be called for two different situations: during a draw,
1719 // to update the scroll position if the focus has changed (in which
1720 // case 'rectangle' is null), or in response to a
1721 // requestChildRectangleOnScreen() call (in which case 'rectangle'
1722 // is non-null and we just want to scroll to whatever that
1723 // rectangle is).
1724 View focus = mRealFocusedView;
Romain Guye8b16522009-07-14 13:06:42 -07001725
1726 // When in touch mode, focus points to the previously focused view,
1727 // which may have been removed from the view hierarchy. The following
Joe Onoratob71193b2009-11-24 18:34:42 -05001728 // line checks whether the view is still in our hierarchy.
1729 if (focus == null || focus.mAttachInfo != mAttachInfo) {
Romain Guye8b16522009-07-14 13:06:42 -07001730 mRealFocusedView = null;
1731 return false;
1732 }
1733
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001734 if (focus != mLastScrolledFocus) {
1735 // If the focus has changed, then ignore any requests to scroll
1736 // to a rectangle; first we want to make sure the entire focus
1737 // view is visible.
1738 rectangle = null;
1739 }
1740 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Eval scroll: focus=" + focus
1741 + " rectangle=" + rectangle + " ci=" + ci
1742 + " vi=" + vi);
1743 if (focus == mLastScrolledFocus && !mScrollMayChange
1744 && rectangle == null) {
1745 // Optimization: if the focus hasn't changed since last
1746 // time, and no layout has happened, then just leave things
1747 // as they are.
1748 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Keeping scroll y="
1749 + mScrollY + " vi=" + vi.toShortString());
1750 } else if (focus != null) {
1751 // We need to determine if the currently focused view is
1752 // within the visible part of the window and, if not, apply
1753 // a pan so it can be seen.
1754 mLastScrolledFocus = focus;
1755 mScrollMayChange = false;
1756 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Need to scroll?");
1757 // Try to find the rectangle from the focus view.
1758 if (focus.getGlobalVisibleRect(mVisRect, null)) {
1759 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Root w="
1760 + mView.getWidth() + " h=" + mView.getHeight()
1761 + " ci=" + ci.toShortString()
1762 + " vi=" + vi.toShortString());
1763 if (rectangle == null) {
1764 focus.getFocusedRect(mTempRect);
1765 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Focus " + focus
1766 + ": focusRect=" + mTempRect.toShortString());
Dianne Hackborn1c6a8942010-03-23 16:34:20 -07001767 if (mView instanceof ViewGroup) {
1768 ((ViewGroup) mView).offsetDescendantRectToMyCoords(
1769 focus, mTempRect);
1770 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001771 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1772 "Focus in window: focusRect="
1773 + mTempRect.toShortString()
1774 + " visRect=" + mVisRect.toShortString());
1775 } else {
1776 mTempRect.set(rectangle);
1777 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1778 "Request scroll to rect: "
1779 + mTempRect.toShortString()
1780 + " visRect=" + mVisRect.toShortString());
1781 }
1782 if (mTempRect.intersect(mVisRect)) {
1783 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1784 "Focus window visible rect: "
1785 + mTempRect.toShortString());
1786 if (mTempRect.height() >
1787 (mView.getHeight()-vi.top-vi.bottom)) {
1788 // If the focus simply is not going to fit, then
1789 // best is probably just to leave things as-is.
1790 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1791 "Too tall; leaving scrollY=" + scrollY);
1792 } else if ((mTempRect.top-scrollY) < vi.top) {
1793 scrollY -= vi.top - (mTempRect.top-scrollY);
1794 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1795 "Top covered; scrollY=" + scrollY);
1796 } else if ((mTempRect.bottom-scrollY)
1797 > (mView.getHeight()-vi.bottom)) {
1798 scrollY += (mTempRect.bottom-scrollY)
1799 - (mView.getHeight()-vi.bottom);
1800 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1801 "Bottom covered; scrollY=" + scrollY);
1802 }
1803 handled = true;
1804 }
1805 }
1806 }
1807 }
Romain Guy8506ab42009-06-11 17:35:47 -07001808
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001809 if (scrollY != mScrollY) {
1810 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Pan scroll changed: old="
1811 + mScrollY + " , new=" + scrollY);
Dianne Hackborn0f761d62010-11-30 22:06:10 -08001812 if (!immediate && mResizeBitmap == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001813 if (mScroller == null) {
1814 mScroller = new Scroller(mView.getContext());
1815 }
1816 mScroller.startScroll(0, mScrollY, 0, scrollY-mScrollY);
1817 } else if (mScroller != null) {
1818 mScroller.abortAnimation();
1819 }
1820 mScrollY = scrollY;
1821 }
Romain Guy8506ab42009-06-11 17:35:47 -07001822
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001823 return handled;
1824 }
Romain Guy8506ab42009-06-11 17:35:47 -07001825
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001826 public void requestChildFocus(View child, View focused) {
1827 checkThread();
1828 if (mFocusedView != focused) {
1829 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(mFocusedView, focused);
1830 scheduleTraversals();
1831 }
1832 mFocusedView = mRealFocusedView = focused;
1833 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Request child focus: focus now "
1834 + mFocusedView);
1835 }
1836
1837 public void clearChildFocus(View child) {
1838 checkThread();
1839
1840 View oldFocus = mFocusedView;
1841
1842 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Clearing child focus");
1843 mFocusedView = mRealFocusedView = null;
1844 if (mView != null && !mView.hasFocus()) {
1845 // If a view gets the focus, the listener will be invoked from requestChildFocus()
1846 if (!mView.requestFocus(View.FOCUS_FORWARD)) {
1847 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
1848 }
1849 } else if (oldFocus != null) {
1850 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
1851 }
1852 }
1853
1854
1855 public void focusableViewAvailable(View v) {
1856 checkThread();
1857
1858 if (mView != null && !mView.hasFocus()) {
1859 v.requestFocus();
1860 } else {
1861 // the one case where will transfer focus away from the current one
1862 // is if the current view is a view group that prefers to give focus
1863 // to its children first AND the view is a descendant of it.
1864 mFocusedView = mView.findFocus();
1865 boolean descendantsHaveDibsOnFocus =
1866 (mFocusedView instanceof ViewGroup) &&
1867 (((ViewGroup) mFocusedView).getDescendantFocusability() ==
1868 ViewGroup.FOCUS_AFTER_DESCENDANTS);
1869 if (descendantsHaveDibsOnFocus && isViewDescendantOf(v, mFocusedView)) {
1870 // If a view gets the focus, the listener will be invoked from requestChildFocus()
1871 v.requestFocus();
1872 }
1873 }
1874 }
1875
1876 public void recomputeViewAttributes(View child) {
1877 checkThread();
1878 if (mView == child) {
1879 mAttachInfo.mRecomputeGlobalAttributes = true;
1880 if (!mWillDrawSoon) {
1881 scheduleTraversals();
1882 }
1883 }
1884 }
1885
1886 void dispatchDetachedFromWindow() {
Romain Guy90fc03b2011-01-16 13:07:15 -08001887 if (mView != null && mView.mAttachInfo != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001888 mView.dispatchDetachedFromWindow();
1889 }
1890
1891 mView = null;
1892 mAttachInfo.mRootView = null;
Mathias Agopian5583dc62009-07-09 16:28:11 -07001893 mAttachInfo.mSurface = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001894
Romain Guy29d89972010-09-22 16:10:57 -07001895 destroyHardwareRenderer();
Romain Guy4caa4ed2010-08-25 14:46:24 -07001896
Dianne Hackborn0586a1b2009-09-06 21:08:27 -07001897 mSurface.release();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001898
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001899 if (mInputChannel != null) {
1900 if (mInputQueueCallback != null) {
1901 mInputQueueCallback.onInputQueueDestroyed(mInputQueue);
1902 mInputQueueCallback = null;
1903 } else {
1904 InputQueue.unregisterInputChannel(mInputChannel);
Jeff Brown46b9ac02010-04-22 18:58:52 -07001905 }
1906 }
1907
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001908 try {
1909 sWindowSession.remove(mWindow);
1910 } catch (RemoteException e) {
1911 }
Jeff Brown349703e2010-06-22 01:27:15 -07001912
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001913 // Dispose the input channel after removing the window so the Window Manager
1914 // doesn't interpret the input channel being closed as an abnormal termination.
1915 if (mInputChannel != null) {
1916 mInputChannel.dispose();
1917 mInputChannel = null;
Jeff Brown349703e2010-06-22 01:27:15 -07001918 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001919 }
Romain Guy8506ab42009-06-11 17:35:47 -07001920
Dianne Hackborn694f79b2010-03-17 19:44:59 -07001921 void updateConfiguration(Configuration config, boolean force) {
1922 if (DEBUG_CONFIGURATION) Log.v(TAG,
1923 "Applying new config to window "
1924 + mWindowAttributes.getTitle()
1925 + ": " + config);
1926 synchronized (sConfigCallbacks) {
1927 for (int i=sConfigCallbacks.size()-1; i>=0; i--) {
1928 sConfigCallbacks.get(i).onConfigurationChanged(config);
1929 }
1930 }
1931 if (mView != null) {
1932 // At this point the resources have been updated to
1933 // have the most recent config, whatever that is. Use
1934 // the on in them which may be newer.
1935 if (mView != null) {
1936 config = mView.getResources().getConfiguration();
1937 }
1938 if (force || mLastConfiguration.diff(config) != 0) {
1939 mLastConfiguration.setTo(config);
1940 mView.dispatchConfigurationChanged(config);
1941 }
1942 }
1943 }
1944
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001945 /**
1946 * Return true if child is an ancestor of parent, (or equal to the parent).
1947 */
1948 private static boolean isViewDescendantOf(View child, View parent) {
1949 if (child == parent) {
1950 return true;
1951 }
1952
1953 final ViewParent theParent = child.getParent();
1954 return (theParent instanceof ViewGroup) && isViewDescendantOf((View) theParent, parent);
1955 }
1956
Romain Guycdb86672010-03-18 18:54:50 -07001957 private static void forceLayout(View view) {
1958 view.forceLayout();
1959 if (view instanceof ViewGroup) {
1960 ViewGroup group = (ViewGroup) view;
1961 final int count = group.getChildCount();
1962 for (int i = 0; i < count; i++) {
1963 forceLayout(group.getChildAt(i));
1964 }
1965 }
1966 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001967
1968 public final static int DO_TRAVERSAL = 1000;
1969 public final static int DIE = 1001;
1970 public final static int RESIZED = 1002;
1971 public final static int RESIZED_REPORT = 1003;
1972 public final static int WINDOW_FOCUS_CHANGED = 1004;
1973 public final static int DISPATCH_KEY = 1005;
1974 public final static int DISPATCH_POINTER = 1006;
1975 public final static int DISPATCH_TRACKBALL = 1007;
1976 public final static int DISPATCH_APP_VISIBILITY = 1008;
1977 public final static int DISPATCH_GET_NEW_SURFACE = 1009;
1978 public final static int FINISHED_EVENT = 1010;
1979 public final static int DISPATCH_KEY_FROM_IME = 1011;
1980 public final static int FINISH_INPUT_CONNECTION = 1012;
1981 public final static int CHECK_FOCUS = 1013;
Dianne Hackbornffa42482009-09-23 22:20:11 -07001982 public final static int CLOSE_SYSTEM_DIALOGS = 1014;
Christopher Tatea53146c2010-09-07 11:57:52 -07001983 public final static int DISPATCH_DRAG_EVENT = 1015;
Chris Tate91e9bb32010-10-12 12:58:43 -07001984 public final static int DISPATCH_DRAG_LOCATION_EVENT = 1016;
Joe Onorato664644d2011-01-23 17:53:23 -08001985 public final static int DISPATCH_SYSTEM_UI_VISIBILITY = 1017;
Joe Onorato10f41262011-01-24 13:16:08 -08001986 public final static int DISPATCH_GENERIC_MOTION = 1018;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001987
1988 @Override
1989 public void handleMessage(Message msg) {
1990 switch (msg.what) {
1991 case View.AttachInfo.INVALIDATE_MSG:
1992 ((View) msg.obj).invalidate();
1993 break;
1994 case View.AttachInfo.INVALIDATE_RECT_MSG:
1995 final View.AttachInfo.InvalidateInfo info = (View.AttachInfo.InvalidateInfo) msg.obj;
1996 info.target.invalidate(info.left, info.top, info.right, info.bottom);
1997 info.release();
1998 break;
1999 case DO_TRAVERSAL:
2000 if (mProfile) {
2001 Debug.startMethodTracing("ViewRoot");
2002 }
2003
2004 performTraversals();
2005
2006 if (mProfile) {
2007 Debug.stopMethodTracing();
2008 mProfile = false;
2009 }
2010 break;
2011 case FINISHED_EVENT:
2012 handleFinishedEvent(msg.arg1, msg.arg2 != 0);
2013 break;
2014 case DISPATCH_KEY:
Jeff Brown92ff1dd2010-08-11 16:16:06 -07002015 deliverKeyEvent((KeyEvent)msg.obj, msg.arg1 != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002016 break;
Jeff Brown3915bb82010-11-05 15:02:16 -07002017 case DISPATCH_POINTER:
2018 deliverPointerEvent((MotionEvent) msg.obj, msg.arg1 != 0);
2019 break;
2020 case DISPATCH_TRACKBALL:
2021 deliverTrackballEvent((MotionEvent) msg.obj, msg.arg1 != 0);
2022 break;
Jeff Browncb1404e2011-01-15 18:14:15 -08002023 case DISPATCH_GENERIC_MOTION:
2024 deliverGenericMotionEvent((MotionEvent) msg.obj, msg.arg1 != 0);
2025 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002026 case DISPATCH_APP_VISIBILITY:
2027 handleAppVisibility(msg.arg1 != 0);
2028 break;
2029 case DISPATCH_GET_NEW_SURFACE:
2030 handleGetNewSurface();
2031 break;
2032 case RESIZED:
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002033 ResizedInfo ri = (ResizedInfo)msg.obj;
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002034
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002035 if (mWinFrame.width() == msg.arg1 && mWinFrame.height() == msg.arg2
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002036 && mPendingContentInsets.equals(ri.coveredInsets)
Dianne Hackbornd49258f2010-03-26 00:44:29 -07002037 && mPendingVisibleInsets.equals(ri.visibleInsets)
2038 && ((ResizedInfo)msg.obj).newConfig == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002039 break;
2040 }
2041 // fall through...
2042 case RESIZED_REPORT:
2043 if (mAdded) {
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002044 Configuration config = ((ResizedInfo)msg.obj).newConfig;
2045 if (config != null) {
Dianne Hackborn694f79b2010-03-17 19:44:59 -07002046 updateConfiguration(config, false);
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002047 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002048 mWinFrame.left = 0;
2049 mWinFrame.right = msg.arg1;
2050 mWinFrame.top = 0;
2051 mWinFrame.bottom = msg.arg2;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002052 mPendingContentInsets.set(((ResizedInfo)msg.obj).coveredInsets);
2053 mPendingVisibleInsets.set(((ResizedInfo)msg.obj).visibleInsets);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002054 if (msg.what == RESIZED_REPORT) {
2055 mReportNextDraw = true;
2056 }
Romain Guycdb86672010-03-18 18:54:50 -07002057
2058 if (mView != null) {
2059 forceLayout(mView);
2060 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002061 requestLayout();
2062 }
2063 break;
2064 case WINDOW_FOCUS_CHANGED: {
2065 if (mAdded) {
2066 boolean hasWindowFocus = msg.arg1 != 0;
2067 mAttachInfo.mHasWindowFocus = hasWindowFocus;
2068 if (hasWindowFocus) {
2069 boolean inTouchMode = msg.arg2 != 0;
Romain Guy2d4cff62010-04-09 15:39:00 -07002070 ensureTouchModeLocally(inTouchMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002071
Romain Guyc361da82010-10-25 15:29:10 -07002072 if (mAttachInfo.mHardwareRenderer != null &&
2073 mSurface != null && mSurface.isValid()) {
Romain Guy7d7b5492011-01-24 16:33:45 -08002074 mFullRedrawNeeded = true;
Dianne Hackborn64825172011-03-02 21:32:58 -08002075 try {
2076 mAttachInfo.mHardwareRenderer.initializeIfNeeded(mWidth, mHeight,
2077 mAttachInfo, mHolder);
2078 } catch (Surface.OutOfResourcesException e) {
2079 Log.e(TAG, "OutOfResourcesException locking surface", e);
2080 try {
2081 if (!sWindowSession.outOfMemory(mWindow)) {
2082 Slog.w(TAG, "No processes killed for memory; killing self");
2083 Process.killProcess(Process.myPid());
2084 }
2085 } catch (RemoteException ex) {
2086 }
2087 // Retry in a bit.
2088 sendMessageDelayed(obtainMessage(msg.what, msg.arg1, msg.arg2), 500);
2089 return;
2090 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002091 }
2092 }
Romain Guy8506ab42009-06-11 17:35:47 -07002093
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002094 mLastWasImTarget = WindowManager.LayoutParams
2095 .mayUseInputMethod(mWindowAttributes.flags);
Romain Guy8506ab42009-06-11 17:35:47 -07002096
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002097 InputMethodManager imm = InputMethodManager.peekInstance();
2098 if (mView != null) {
2099 if (hasWindowFocus && imm != null && mLastWasImTarget) {
2100 imm.startGettingWindowFocus(mView);
2101 }
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07002102 mAttachInfo.mKeyDispatchState.reset();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002103 mView.dispatchWindowFocusChanged(hasWindowFocus);
2104 }
svetoslavganov75986cf2009-05-14 22:28:01 -07002105
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002106 // Note: must be done after the focus change callbacks,
2107 // so all of the view state is set up correctly.
2108 if (hasWindowFocus) {
2109 if (imm != null && mLastWasImTarget) {
2110 imm.onWindowFocus(mView, mView.findFocus(),
2111 mWindowAttributes.softInputMode,
2112 !mHasHadWindowFocus, mWindowAttributes.flags);
2113 }
2114 // Clear the forward bit. We can just do this directly, since
2115 // the window manager doesn't care about it.
2116 mWindowAttributes.softInputMode &=
2117 ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
2118 ((WindowManager.LayoutParams)mView.getLayoutParams())
2119 .softInputMode &=
2120 ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
2121 mHasHadWindowFocus = true;
2122 }
svetoslavganov75986cf2009-05-14 22:28:01 -07002123
2124 if (hasWindowFocus && mView != null) {
2125 sendAccessibilityEvents();
2126 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002127 }
2128 } break;
2129 case DIE:
Dianne Hackborn94d69142009-09-28 22:14:42 -07002130 doDie();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002131 break;
The Android Open Source Project10592532009-03-18 17:39:46 -07002132 case DISPATCH_KEY_FROM_IME: {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002133 if (LOCAL_LOGV) Log.v(
Jeff Brownc5ed5912010-07-14 18:48:53 -07002134 TAG, "Dispatching key "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002135 + msg.obj + " from IME to " + mView);
The Android Open Source Project10592532009-03-18 17:39:46 -07002136 KeyEvent event = (KeyEvent)msg.obj;
2137 if ((event.getFlags()&KeyEvent.FLAG_FROM_SYSTEM) != 0) {
2138 // The IME is trying to say this event is from the
2139 // system! Bad bad bad!
Romain Guy812ccbe2010-06-01 14:07:24 -07002140 event = KeyEvent.changeFlags(event, event.getFlags() & ~KeyEvent.FLAG_FROM_SYSTEM);
The Android Open Source Project10592532009-03-18 17:39:46 -07002141 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002142 deliverKeyEventPostIme((KeyEvent)msg.obj, false);
The Android Open Source Project10592532009-03-18 17:39:46 -07002143 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002144 case FINISH_INPUT_CONNECTION: {
2145 InputMethodManager imm = InputMethodManager.peekInstance();
2146 if (imm != null) {
2147 imm.reportFinishInputConnection((InputConnection)msg.obj);
2148 }
2149 } break;
2150 case CHECK_FOCUS: {
2151 InputMethodManager imm = InputMethodManager.peekInstance();
2152 if (imm != null) {
2153 imm.checkFocus();
2154 }
2155 } break;
Dianne Hackbornffa42482009-09-23 22:20:11 -07002156 case CLOSE_SYSTEM_DIALOGS: {
2157 if (mView != null) {
2158 mView.onCloseSystemDialogs((String)msg.obj);
2159 }
2160 } break;
Chris Tate91e9bb32010-10-12 12:58:43 -07002161 case DISPATCH_DRAG_EVENT:
2162 case DISPATCH_DRAG_LOCATION_EVENT: {
Christopher Tate7fb8b562011-01-20 13:46:41 -08002163 DragEvent event = (DragEvent)msg.obj;
2164 event.mLocalState = mLocalDragState; // only present when this app called startDrag()
2165 handleDragEvent(event);
Christopher Tatea53146c2010-09-07 11:57:52 -07002166 } break;
Joe Onorato664644d2011-01-23 17:53:23 -08002167 case DISPATCH_SYSTEM_UI_VISIBILITY: {
2168 handleDispatchSystemUiVisibilityChanged(msg.arg1);
2169 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002170 }
2171 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002172
Jeff Brown3915bb82010-11-05 15:02:16 -07002173 private void startInputEvent(InputQueue.FinishedCallback finishedCallback) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07002174 if (mFinishedCallback != null) {
2175 Slog.w(TAG, "Received a new input event from the input queue but there is "
2176 + "already an unfinished input event in progress.");
2177 }
2178
2179 mFinishedCallback = finishedCallback;
2180 }
2181
Jeff Brown3915bb82010-11-05 15:02:16 -07002182 private void finishInputEvent(boolean handled) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07002183 if (LOCAL_LOGV) Log.v(TAG, "Telling window manager input event is finished");
Jeff Brown92ff1dd2010-08-11 16:16:06 -07002184
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002185 if (mFinishedCallback != null) {
Jeff Brown3915bb82010-11-05 15:02:16 -07002186 mFinishedCallback.finished(handled);
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002187 mFinishedCallback = null;
Jeff Brown92ff1dd2010-08-11 16:16:06 -07002188 } else {
Jeff Brown93ed4e32010-09-23 13:51:48 -07002189 Slog.w(TAG, "Attempted to tell the input queue that the current input event "
2190 + "is finished but there is no input event actually in progress.");
Jeff Brown46b9ac02010-04-22 18:58:52 -07002191 }
2192 }
2193
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002194 /**
2195 * Something in the current window tells us we need to change the touch mode. For
2196 * example, we are not in touch mode, and the user touches the screen.
2197 *
2198 * If the touch mode has changed, tell the window manager, and handle it locally.
2199 *
2200 * @param inTouchMode Whether we want to be in touch mode.
2201 * @return True if the touch mode changed and focus changed was changed as a result
2202 */
2203 boolean ensureTouchMode(boolean inTouchMode) {
2204 if (DBG) Log.d("touchmode", "ensureTouchMode(" + inTouchMode + "), current "
2205 + "touch mode is " + mAttachInfo.mInTouchMode);
2206 if (mAttachInfo.mInTouchMode == inTouchMode) return false;
2207
2208 // tell the window manager
2209 try {
2210 sWindowSession.setInTouchMode(inTouchMode);
2211 } catch (RemoteException e) {
2212 throw new RuntimeException(e);
2213 }
2214
2215 // handle the change
Romain Guy2d4cff62010-04-09 15:39:00 -07002216 return ensureTouchModeLocally(inTouchMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002217 }
2218
2219 /**
2220 * Ensure that the touch mode for this window is set, and if it is changing,
2221 * take the appropriate action.
2222 * @param inTouchMode Whether we want to be in touch mode.
2223 * @return True if the touch mode changed and focus changed was changed as a result
2224 */
Romain Guy2d4cff62010-04-09 15:39:00 -07002225 private boolean ensureTouchModeLocally(boolean inTouchMode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002226 if (DBG) Log.d("touchmode", "ensureTouchModeLocally(" + inTouchMode + "), current "
2227 + "touch mode is " + mAttachInfo.mInTouchMode);
2228
2229 if (mAttachInfo.mInTouchMode == inTouchMode) return false;
2230
2231 mAttachInfo.mInTouchMode = inTouchMode;
2232 mAttachInfo.mTreeObserver.dispatchOnTouchModeChanged(inTouchMode);
2233
Romain Guy2d4cff62010-04-09 15:39:00 -07002234 return (inTouchMode) ? enterTouchMode() : leaveTouchMode();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002235 }
2236
2237 private boolean enterTouchMode() {
2238 if (mView != null) {
2239 if (mView.hasFocus()) {
2240 // note: not relying on mFocusedView here because this could
2241 // be when the window is first being added, and mFocused isn't
2242 // set yet.
2243 final View focused = mView.findFocus();
2244 if (focused != null && !focused.isFocusableInTouchMode()) {
2245
2246 final ViewGroup ancestorToTakeFocus =
2247 findAncestorToTakeFocusInTouchMode(focused);
2248 if (ancestorToTakeFocus != null) {
2249 // there is an ancestor that wants focus after its descendants that
2250 // is focusable in touch mode.. give it focus
2251 return ancestorToTakeFocus.requestFocus();
2252 } else {
2253 // nothing appropriate to have focus in touch mode, clear it out
2254 mView.unFocus();
2255 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(focused, null);
2256 mFocusedView = null;
2257 return true;
2258 }
2259 }
2260 }
2261 }
2262 return false;
2263 }
2264
2265
2266 /**
2267 * Find an ancestor of focused that wants focus after its descendants and is
2268 * focusable in touch mode.
2269 * @param focused The currently focused view.
2270 * @return An appropriate view, or null if no such view exists.
2271 */
2272 private ViewGroup findAncestorToTakeFocusInTouchMode(View focused) {
2273 ViewParent parent = focused.getParent();
2274 while (parent instanceof ViewGroup) {
2275 final ViewGroup vgParent = (ViewGroup) parent;
2276 if (vgParent.getDescendantFocusability() == ViewGroup.FOCUS_AFTER_DESCENDANTS
2277 && vgParent.isFocusableInTouchMode()) {
2278 return vgParent;
2279 }
2280 if (vgParent.isRootNamespace()) {
2281 return null;
2282 } else {
2283 parent = vgParent.getParent();
2284 }
2285 }
2286 return null;
2287 }
2288
2289 private boolean leaveTouchMode() {
2290 if (mView != null) {
2291 if (mView.hasFocus()) {
2292 // i learned the hard way to not trust mFocusedView :)
2293 mFocusedView = mView.findFocus();
2294 if (!(mFocusedView instanceof ViewGroup)) {
2295 // some view has focus, let it keep it
2296 return false;
2297 } else if (((ViewGroup)mFocusedView).getDescendantFocusability() !=
2298 ViewGroup.FOCUS_AFTER_DESCENDANTS) {
2299 // some view group has focus, and doesn't prefer its children
2300 // over itself for focus, so let them keep it.
2301 return false;
2302 }
2303 }
2304
2305 // find the best view to give focus to in this brave new non-touch-mode
2306 // world
2307 final View focused = focusSearch(null, View.FOCUS_DOWN);
2308 if (focused != null) {
2309 return focused.requestFocus(View.FOCUS_DOWN);
2310 }
2311 }
2312 return false;
2313 }
2314
Jeff Brown3915bb82010-11-05 15:02:16 -07002315 private void deliverPointerEvent(MotionEvent event, boolean sendDone) {
2316 // If there is no view, then the event will not be handled.
2317 if (mView == null || !mAdded) {
Jeff Brown33bbfd22011-02-24 20:55:35 -08002318 finishMotionEvent(event, sendDone, false);
Jeff Brown3915bb82010-11-05 15:02:16 -07002319 return;
2320 }
2321
2322 // Translate the pointer event for compatibility, if needed.
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002323 if (mTranslator != null) {
2324 mTranslator.translateEventInScreenToAppWindow(event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002325 }
2326
Jeff Brown3915bb82010-11-05 15:02:16 -07002327 // Enter touch mode on the down.
2328 boolean isDown = event.getAction() == MotionEvent.ACTION_DOWN;
2329 if (isDown) {
2330 ensureTouchMode(true);
2331 }
2332 if(Config.LOGV) {
2333 captureMotionLog("captureDispatchPointer", event);
2334 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002335
Jeff Brown3915bb82010-11-05 15:02:16 -07002336 // Offset the scroll position.
2337 if (mCurScrollY != 0) {
2338 event.offsetLocation(0, mCurScrollY);
2339 }
2340 if (MEASURE_LATENCY) {
Jeff Brown33bbfd22011-02-24 20:55:35 -08002341 lt.sample("A Dispatching PointerEvents", System.nanoTime() - event.getEventTimeNano());
Jeff Brown3915bb82010-11-05 15:02:16 -07002342 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002343
Jeff Brown3915bb82010-11-05 15:02:16 -07002344 // Remember the touch position for possible drag-initiation.
2345 mLastTouchPoint.x = event.getRawX();
2346 mLastTouchPoint.y = event.getRawY();
2347
2348 // Dispatch touch to view hierarchy.
Jeff Brown33bbfd22011-02-24 20:55:35 -08002349 boolean handled = mView.dispatchPointerEvent(event);
Jeff Brown3915bb82010-11-05 15:02:16 -07002350 if (MEASURE_LATENCY) {
Jeff Brown33bbfd22011-02-24 20:55:35 -08002351 lt.sample("B Dispatched PointerEvents ", System.nanoTime() - event.getEventTimeNano());
Jeff Brown3915bb82010-11-05 15:02:16 -07002352 }
2353 if (handled) {
Jeff Brown33bbfd22011-02-24 20:55:35 -08002354 finishMotionEvent(event, sendDone, true);
Jeff Brown3915bb82010-11-05 15:02:16 -07002355 return;
2356 }
2357
2358 // Apply edge slop and try again, if appropriate.
2359 final int edgeFlags = event.getEdgeFlags();
2360 if (edgeFlags != 0 && mView instanceof ViewGroup) {
2361 final int edgeSlop = mViewConfiguration.getScaledEdgeSlop();
2362 int direction = View.FOCUS_UP;
2363 int x = (int)event.getX();
2364 int y = (int)event.getY();
2365 final int[] deltas = new int[2];
2366
2367 if ((edgeFlags & MotionEvent.EDGE_TOP) != 0) {
2368 direction = View.FOCUS_DOWN;
2369 if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
2370 deltas[0] = edgeSlop;
2371 x += edgeSlop;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002372 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
Jeff Brown3915bb82010-11-05 15:02:16 -07002373 deltas[0] = -edgeSlop;
2374 x -= edgeSlop;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002375 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002376 } else if ((edgeFlags & MotionEvent.EDGE_BOTTOM) != 0) {
2377 direction = View.FOCUS_UP;
2378 if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
2379 deltas[0] = edgeSlop;
2380 x += edgeSlop;
2381 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
2382 deltas[0] = -edgeSlop;
2383 x -= edgeSlop;
2384 }
2385 } else if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
2386 direction = View.FOCUS_RIGHT;
2387 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
2388 direction = View.FOCUS_LEFT;
2389 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002390
Jeff Brown3915bb82010-11-05 15:02:16 -07002391 View nearest = FocusFinder.getInstance().findNearestTouchable(
2392 ((ViewGroup) mView), x, y, direction, deltas);
2393 if (nearest != null) {
2394 event.offsetLocation(deltas[0], deltas[1]);
2395 event.setEdgeFlags(0);
Jeff Brown33bbfd22011-02-24 20:55:35 -08002396 if (mView.dispatchPointerEvent(event)) {
2397 finishMotionEvent(event, sendDone, true);
Jeff Brown3915bb82010-11-05 15:02:16 -07002398 return;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002399 }
2400 }
2401 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002402
2403 // Pointer event was unhandled.
Jeff Brown33bbfd22011-02-24 20:55:35 -08002404 finishMotionEvent(event, sendDone, false);
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002405 }
2406
Jeff Brown33bbfd22011-02-24 20:55:35 -08002407 private void finishMotionEvent(MotionEvent event, boolean sendDone, boolean handled) {
Jeff Brown3915bb82010-11-05 15:02:16 -07002408 event.recycle();
2409 if (sendDone) {
2410 finishInputEvent(handled);
2411 }
Jeff Brown33bbfd22011-02-24 20:55:35 -08002412 if (LOCAL_LOGV || WATCH_POINTER) {
2413 if ((event.getSource() & InputDevice.SOURCE_CLASS_POINTER) != 0) {
2414 Log.i(TAG, "Done dispatching!");
2415 }
2416 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002417 }
2418
2419 private void deliverTrackballEvent(MotionEvent event, boolean sendDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002420 if (DEBUG_TRACKBALL) Log.v(TAG, "Motion event:" + event);
2421
Jeff Brown3915bb82010-11-05 15:02:16 -07002422 // If there is no view, then the event will not be handled.
2423 if (mView == null || !mAdded) {
Jeff Brown33bbfd22011-02-24 20:55:35 -08002424 finishMotionEvent(event, sendDone, false);
Jeff Brown3915bb82010-11-05 15:02:16 -07002425 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002426 }
2427
Jeff Brown3915bb82010-11-05 15:02:16 -07002428 // Deliver the trackball event to the view.
2429 if (mView.dispatchTrackballEvent(event)) {
2430 // If we reach this, we delivered a trackball event to mView and
2431 // mView consumed it. Because we will not translate the trackball
2432 // event into a key event, touch mode will not exit, so we exit
2433 // touch mode here.
2434 ensureTouchMode(false);
2435
Jeff Brown33bbfd22011-02-24 20:55:35 -08002436 finishMotionEvent(event, sendDone, true);
Jeff Brown3915bb82010-11-05 15:02:16 -07002437 mLastTrackballTime = Integer.MIN_VALUE;
2438 return;
2439 }
2440
2441 // Translate the trackball event into DPAD keys and try to deliver those.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002442 final TrackballAxis x = mTrackballAxisX;
2443 final TrackballAxis y = mTrackballAxisY;
2444
2445 long curTime = SystemClock.uptimeMillis();
Jeff Brown3915bb82010-11-05 15:02:16 -07002446 if ((mLastTrackballTime + MAX_TRACKBALL_DELAY) < curTime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002447 // It has been too long since the last movement,
2448 // so restart at the beginning.
2449 x.reset(0);
2450 y.reset(0);
2451 mLastTrackballTime = curTime;
2452 }
2453
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002454 final int action = event.getAction();
Jeff Brown49ed71d2010-12-06 17:13:33 -08002455 final int metaState = event.getMetaState();
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002456 switch (action) {
2457 case MotionEvent.ACTION_DOWN:
2458 x.reset(2);
2459 y.reset(2);
2460 deliverKeyEvent(new KeyEvent(curTime, curTime,
Jeff Brown49ed71d2010-12-06 17:13:33 -08002461 KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_CENTER, 0, metaState,
2462 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
2463 InputDevice.SOURCE_KEYBOARD), false);
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002464 break;
2465 case MotionEvent.ACTION_UP:
2466 x.reset(2);
2467 y.reset(2);
2468 deliverKeyEvent(new KeyEvent(curTime, curTime,
Jeff Brown49ed71d2010-12-06 17:13:33 -08002469 KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_CENTER, 0, metaState,
2470 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
2471 InputDevice.SOURCE_KEYBOARD), false);
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002472 break;
2473 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002474
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002475 if (DEBUG_TRACKBALL) Log.v(TAG, "TB X=" + x.position + " step="
2476 + x.step + " dir=" + x.dir + " acc=" + x.acceleration
2477 + " move=" + event.getX()
2478 + " / Y=" + y.position + " step="
2479 + y.step + " dir=" + y.dir + " acc=" + y.acceleration
2480 + " move=" + event.getY());
2481 final float xOff = x.collect(event.getX(), event.getEventTime(), "X");
2482 final float yOff = y.collect(event.getY(), event.getEventTime(), "Y");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002483
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002484 // Generate DPAD events based on the trackball movement.
2485 // We pick the axis that has moved the most as the direction of
2486 // the DPAD. When we generate DPAD events for one axis, then the
2487 // other axis is reset -- we don't want to perform DPAD jumps due
2488 // to slight movements in the trackball when making major movements
2489 // along the other axis.
2490 int keycode = 0;
2491 int movement = 0;
2492 float accel = 1;
2493 if (xOff > yOff) {
2494 movement = x.generate((2/event.getXPrecision()));
2495 if (movement != 0) {
2496 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_RIGHT
2497 : KeyEvent.KEYCODE_DPAD_LEFT;
2498 accel = x.acceleration;
2499 y.reset(2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002500 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002501 } else if (yOff > 0) {
2502 movement = y.generate((2/event.getYPrecision()));
2503 if (movement != 0) {
2504 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_DOWN
2505 : KeyEvent.KEYCODE_DPAD_UP;
2506 accel = y.acceleration;
2507 x.reset(2);
2508 }
2509 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002510
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002511 if (keycode != 0) {
2512 if (movement < 0) movement = -movement;
2513 int accelMovement = (int)(movement * accel);
2514 if (DEBUG_TRACKBALL) Log.v(TAG, "Move: movement=" + movement
2515 + " accelMovement=" + accelMovement
2516 + " accel=" + accel);
2517 if (accelMovement > movement) {
2518 if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: "
2519 + keycode);
2520 movement--;
Jeff Brown49ed71d2010-12-06 17:13:33 -08002521 int repeatCount = accelMovement - movement;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002522 deliverKeyEvent(new KeyEvent(curTime, curTime,
Jeff Brown49ed71d2010-12-06 17:13:33 -08002523 KeyEvent.ACTION_MULTIPLE, keycode, repeatCount, metaState,
2524 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
2525 InputDevice.SOURCE_KEYBOARD), false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002526 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002527 while (movement > 0) {
2528 if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: "
2529 + keycode);
2530 movement--;
2531 curTime = SystemClock.uptimeMillis();
2532 deliverKeyEvent(new KeyEvent(curTime, curTime,
Jeff Brown49ed71d2010-12-06 17:13:33 -08002533 KeyEvent.ACTION_DOWN, keycode, 0, metaState,
2534 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
2535 InputDevice.SOURCE_KEYBOARD), false);
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002536 deliverKeyEvent(new KeyEvent(curTime, curTime,
Jeff Brown49ed71d2010-12-06 17:13:33 -08002537 KeyEvent.ACTION_UP, keycode, 0, metaState,
2538 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
2539 InputDevice.SOURCE_KEYBOARD), false);
2540 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002541 mLastTrackballTime = curTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002542 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002543
2544 // Unfortunately we can't tell whether the application consumed the keys, so
2545 // we always consider the trackball event handled.
Jeff Brown33bbfd22011-02-24 20:55:35 -08002546 finishMotionEvent(event, sendDone, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002547 }
2548
Jeff Browncb1404e2011-01-15 18:14:15 -08002549 private void deliverGenericMotionEvent(MotionEvent event, boolean sendDone) {
2550 final int source = event.getSource();
2551 final boolean isJoystick = (source & InputDevice.SOURCE_CLASS_JOYSTICK) != 0;
2552
2553 // If there is no view, then the event will not be handled.
2554 if (mView == null || !mAdded) {
2555 if (isJoystick) {
2556 updateJoystickDirection(event, false);
2557 }
Jeff Brown33bbfd22011-02-24 20:55:35 -08002558 finishMotionEvent(event, sendDone, false);
Jeff Browncb1404e2011-01-15 18:14:15 -08002559 return;
2560 }
2561
2562 // Deliver the event to the view.
2563 if (mView.dispatchGenericMotionEvent(event)) {
Jeff Browncb1404e2011-01-15 18:14:15 -08002564 if (isJoystick) {
2565 updateJoystickDirection(event, false);
2566 }
Jeff Brown33bbfd22011-02-24 20:55:35 -08002567 finishMotionEvent(event, sendDone, true);
Jeff Browncb1404e2011-01-15 18:14:15 -08002568 return;
2569 }
2570
2571 if (isJoystick) {
2572 // Translate the joystick event into DPAD keys and try to deliver those.
2573 updateJoystickDirection(event, true);
Jeff Brown33bbfd22011-02-24 20:55:35 -08002574 finishMotionEvent(event, sendDone, true);
Jeff Browncb1404e2011-01-15 18:14:15 -08002575 } else {
Jeff Brown33bbfd22011-02-24 20:55:35 -08002576 finishMotionEvent(event, sendDone, false);
Jeff Browncb1404e2011-01-15 18:14:15 -08002577 }
2578 }
2579
2580 private void updateJoystickDirection(MotionEvent event, boolean synthesizeNewKeys) {
2581 final long time = event.getEventTime();
2582 final int metaState = event.getMetaState();
2583 final int deviceId = event.getDeviceId();
2584 final int source = event.getSource();
Jeff Brown6f2fba42011-02-19 01:08:02 -08002585
2586 int xDirection = joystickAxisValueToDirection(event.getAxisValue(MotionEvent.AXIS_HAT_X));
2587 if (xDirection == 0) {
2588 xDirection = joystickAxisValueToDirection(event.getX());
2589 }
2590
2591 int yDirection = joystickAxisValueToDirection(event.getAxisValue(MotionEvent.AXIS_HAT_Y));
2592 if (yDirection == 0) {
2593 yDirection = joystickAxisValueToDirection(event.getY());
2594 }
Jeff Browncb1404e2011-01-15 18:14:15 -08002595
2596 if (xDirection != mLastJoystickXDirection) {
2597 if (mLastJoystickXKeyCode != 0) {
2598 deliverKeyEvent(new KeyEvent(time, time,
2599 KeyEvent.ACTION_UP, mLastJoystickXKeyCode, 0, metaState,
2600 deviceId, 0, KeyEvent.FLAG_FALLBACK, source), false);
2601 mLastJoystickXKeyCode = 0;
2602 }
2603
2604 mLastJoystickXDirection = xDirection;
2605
2606 if (xDirection != 0 && synthesizeNewKeys) {
2607 mLastJoystickXKeyCode = xDirection > 0
2608 ? KeyEvent.KEYCODE_DPAD_RIGHT : KeyEvent.KEYCODE_DPAD_LEFT;
2609 deliverKeyEvent(new KeyEvent(time, time,
2610 KeyEvent.ACTION_DOWN, mLastJoystickXKeyCode, 0, metaState,
2611 deviceId, 0, KeyEvent.FLAG_FALLBACK, source), false);
2612 }
2613 }
2614
2615 if (yDirection != mLastJoystickYDirection) {
2616 if (mLastJoystickYKeyCode != 0) {
2617 deliverKeyEvent(new KeyEvent(time, time,
2618 KeyEvent.ACTION_UP, mLastJoystickYKeyCode, 0, metaState,
2619 deviceId, 0, KeyEvent.FLAG_FALLBACK, source), false);
2620 mLastJoystickYKeyCode = 0;
2621 }
2622
2623 mLastJoystickYDirection = yDirection;
2624
2625 if (yDirection != 0 && synthesizeNewKeys) {
2626 mLastJoystickYKeyCode = yDirection > 0
2627 ? KeyEvent.KEYCODE_DPAD_DOWN : KeyEvent.KEYCODE_DPAD_UP;
2628 deliverKeyEvent(new KeyEvent(time, time,
2629 KeyEvent.ACTION_DOWN, mLastJoystickYKeyCode, 0, metaState,
2630 deviceId, 0, KeyEvent.FLAG_FALLBACK, source), false);
2631 }
2632 }
2633 }
2634
2635 private static int joystickAxisValueToDirection(float value) {
2636 if (value >= 0.5f) {
2637 return 1;
2638 } else if (value <= -0.5f) {
2639 return -1;
2640 } else {
2641 return 0;
2642 }
2643 }
2644
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002645 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08002646 * Returns true if the key is used for keyboard navigation.
2647 * @param keyEvent The key event.
2648 * @return True if the key is used for keyboard navigation.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002649 */
Jeff Brown4e6319b2010-12-13 10:36:51 -08002650 private static boolean isNavigationKey(KeyEvent keyEvent) {
2651 switch (keyEvent.getKeyCode()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002652 case KeyEvent.KEYCODE_DPAD_LEFT:
2653 case KeyEvent.KEYCODE_DPAD_RIGHT:
2654 case KeyEvent.KEYCODE_DPAD_UP:
2655 case KeyEvent.KEYCODE_DPAD_DOWN:
Jeff Brown4e6319b2010-12-13 10:36:51 -08002656 case KeyEvent.KEYCODE_DPAD_CENTER:
2657 case KeyEvent.KEYCODE_PAGE_UP:
2658 case KeyEvent.KEYCODE_PAGE_DOWN:
2659 case KeyEvent.KEYCODE_MOVE_HOME:
2660 case KeyEvent.KEYCODE_MOVE_END:
2661 case KeyEvent.KEYCODE_TAB:
2662 case KeyEvent.KEYCODE_SPACE:
2663 case KeyEvent.KEYCODE_ENTER:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002664 return true;
2665 }
2666 return false;
2667 }
2668
2669 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08002670 * Returns true if the key is used for typing.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002671 * @param keyEvent The key event.
Jeff Brown4e6319b2010-12-13 10:36:51 -08002672 * @return True if the key is used for typing.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002673 */
Jeff Brown4e6319b2010-12-13 10:36:51 -08002674 private static boolean isTypingKey(KeyEvent keyEvent) {
2675 return keyEvent.getUnicodeChar() > 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002676 }
2677
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002678 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08002679 * 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 -08002680 * @param event The key event.
2681 * @return Whether this key event should be consumed (meaning the act of
2682 * leaving touch mode alone is considered the event).
2683 */
2684 private boolean checkForLeavingTouchModeAndConsume(KeyEvent event) {
Jeff Brown4e6319b2010-12-13 10:36:51 -08002685 // Only relevant in touch mode.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002686 if (!mAttachInfo.mInTouchMode) {
2687 return false;
2688 }
2689
Jeff Brown4e6319b2010-12-13 10:36:51 -08002690 // Only consider leaving touch mode on DOWN or MULTIPLE actions, never on UP.
2691 final int action = event.getAction();
2692 if (action != KeyEvent.ACTION_DOWN && action != KeyEvent.ACTION_MULTIPLE) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002693 return false;
2694 }
2695
Jeff Brown4e6319b2010-12-13 10:36:51 -08002696 // Don't leave touch mode if the IME told us not to.
2697 if ((event.getFlags() & KeyEvent.FLAG_KEEP_TOUCH_MODE) != 0) {
2698 return false;
2699 }
2700
2701 // If the key can be used for keyboard navigation then leave touch mode
2702 // and select a focused view if needed (in ensureTouchMode).
2703 // When a new focused view is selected, we consume the navigation key because
2704 // navigation doesn't make much sense unless a view already has focus so
2705 // the key's purpose is to set focus.
2706 if (isNavigationKey(event)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002707 return ensureTouchMode(false);
2708 }
Jeff Brown4e6319b2010-12-13 10:36:51 -08002709
2710 // If the key can be used for typing then leave touch mode
2711 // and select a focused view if needed (in ensureTouchMode).
2712 // Always allow the view to process the typing key.
2713 if (isTypingKey(event)) {
2714 ensureTouchMode(false);
2715 return false;
2716 }
2717
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002718 return false;
2719 }
2720
2721 /**
Romain Guy8506ab42009-06-11 17:35:47 -07002722 * log motion events
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002723 */
2724 private static void captureMotionLog(String subTag, MotionEvent ev) {
Romain Guy8506ab42009-06-11 17:35:47 -07002725 //check dynamic switch
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002726 if (ev == null ||
2727 SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_EVENT, 0) == 0) {
2728 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002729 }
Romain Guy8506ab42009-06-11 17:35:47 -07002730
2731 StringBuilder sb = new StringBuilder(subTag + ": ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002732 sb.append(ev.getDownTime()).append(',');
2733 sb.append(ev.getEventTime()).append(',');
2734 sb.append(ev.getAction()).append(',');
Romain Guy8506ab42009-06-11 17:35:47 -07002735 sb.append(ev.getX()).append(',');
2736 sb.append(ev.getY()).append(',');
2737 sb.append(ev.getPressure()).append(',');
2738 sb.append(ev.getSize()).append(',');
2739 sb.append(ev.getMetaState()).append(',');
2740 sb.append(ev.getXPrecision()).append(',');
2741 sb.append(ev.getYPrecision()).append(',');
2742 sb.append(ev.getDeviceId()).append(',');
2743 sb.append(ev.getEdgeFlags());
2744 Log.d(TAG, sb.toString());
2745 }
2746 /**
2747 * log motion events
2748 */
2749 private static void captureKeyLog(String subTag, KeyEvent ev) {
2750 //check dynamic switch
2751 if (ev == null ||
2752 SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_EVENT, 0) == 0) {
2753 return;
2754 }
2755 StringBuilder sb = new StringBuilder(subTag + ": ");
2756 sb.append(ev.getDownTime()).append(',');
2757 sb.append(ev.getEventTime()).append(',');
2758 sb.append(ev.getAction()).append(',');
2759 sb.append(ev.getKeyCode()).append(',');
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002760 sb.append(ev.getRepeatCount()).append(',');
2761 sb.append(ev.getMetaState()).append(',');
2762 sb.append(ev.getDeviceId()).append(',');
2763 sb.append(ev.getScanCode());
Romain Guy8506ab42009-06-11 17:35:47 -07002764 Log.d(TAG, sb.toString());
2765 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002766
2767 int enqueuePendingEvent(Object event, boolean sendDone) {
2768 int seq = mPendingEventSeq+1;
2769 if (seq < 0) seq = 0;
2770 mPendingEventSeq = seq;
2771 mPendingEvents.put(seq, event);
2772 return sendDone ? seq : -seq;
2773 }
2774
2775 Object retrievePendingEvent(int seq) {
2776 if (seq < 0) seq = -seq;
2777 Object event = mPendingEvents.get(seq);
2778 if (event != null) {
2779 mPendingEvents.remove(seq);
2780 }
2781 return event;
2782 }
Romain Guy8506ab42009-06-11 17:35:47 -07002783
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002784 private void deliverKeyEvent(KeyEvent event, boolean sendDone) {
Jeff Brown3915bb82010-11-05 15:02:16 -07002785 // If there is no view, then the event will not be handled.
2786 if (mView == null || !mAdded) {
2787 finishKeyEvent(event, sendDone, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002788 return;
2789 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002790
2791 if (LOCAL_LOGV) Log.v(TAG, "Dispatching key " + event + " to " + mView);
2792
2793 // Perform predispatching before the IME.
2794 if (mView.dispatchKeyEventPreIme(event)) {
2795 finishKeyEvent(event, sendDone, true);
2796 return;
2797 }
2798
2799 // Dispatch to the IME before propagating down the view hierarchy.
2800 // The IME will eventually call back into handleFinishedEvent.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002801 if (mLastWasImTarget) {
2802 InputMethodManager imm = InputMethodManager.peekInstance();
Jeff Brown3915bb82010-11-05 15:02:16 -07002803 if (imm != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002804 int seq = enqueuePendingEvent(event, sendDone);
2805 if (DEBUG_IMF) Log.v(TAG, "Sending key event to IME: seq="
2806 + seq + " event=" + event);
Jeff Brown3915bb82010-11-05 15:02:16 -07002807 imm.dispatchKeyEvent(mView.getContext(), seq, event, mInputMethodCallback);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002808 return;
2809 }
2810 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002811
2812 // Not dispatching to IME, continue with post IME actions.
2813 deliverKeyEventPostIme(event, sendDone);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002814 }
2815
Jeff Brown3915bb82010-11-05 15:02:16 -07002816 private void handleFinishedEvent(int seq, boolean handled) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002817 final KeyEvent event = (KeyEvent)retrievePendingEvent(seq);
2818 if (DEBUG_IMF) Log.v(TAG, "IME finished event: seq=" + seq
2819 + " handled=" + handled + " event=" + event);
2820 if (event != null) {
2821 final boolean sendDone = seq >= 0;
Jeff Brown3915bb82010-11-05 15:02:16 -07002822 if (handled) {
2823 finishKeyEvent(event, sendDone, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002824 } else {
Jeff Brown3915bb82010-11-05 15:02:16 -07002825 deliverKeyEventPostIme(event, sendDone);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002826 }
2827 }
2828 }
Romain Guy8506ab42009-06-11 17:35:47 -07002829
Jeff Brown3915bb82010-11-05 15:02:16 -07002830 private void deliverKeyEventPostIme(KeyEvent event, boolean sendDone) {
2831 // If the view went away, then the event will not be handled.
2832 if (mView == null || !mAdded) {
2833 finishKeyEvent(event, sendDone, false);
2834 return;
2835 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002836
Jeff Brown3915bb82010-11-05 15:02:16 -07002837 // If the key's purpose is to exit touch mode then we consume it and consider it handled.
2838 if (checkForLeavingTouchModeAndConsume(event)) {
2839 finishKeyEvent(event, sendDone, true);
2840 return;
2841 }
Romain Guy8506ab42009-06-11 17:35:47 -07002842
Jeff Brown3915bb82010-11-05 15:02:16 -07002843 if (Config.LOGV) {
2844 captureKeyLog("captureDispatchKeyEvent", event);
2845 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002846
Jeff Brown90655042010-12-02 13:50:46 -08002847 // Make sure the fallback event policy sees all keys that will be delivered to the
2848 // view hierarchy.
2849 mFallbackEventHandler.preDispatchKeyEvent(event);
2850
Jeff Brown3915bb82010-11-05 15:02:16 -07002851 // Deliver the key to the view hierarchy.
2852 if (mView.dispatchKeyEvent(event)) {
2853 finishKeyEvent(event, sendDone, true);
2854 return;
2855 }
Joe Onorato86f67862010-11-05 18:57:34 -07002856
Jeff Brownc1df9072010-12-21 16:38:50 -08002857 // If the Control modifier is held, try to interpret the key as a shortcut.
2858 if (event.getAction() == KeyEvent.ACTION_UP
2859 && event.isCtrlPressed()
2860 && !KeyEvent.isModifierKey(event.getKeyCode())) {
2861 if (mView.dispatchKeyShortcutEvent(event)) {
2862 finishKeyEvent(event, sendDone, true);
2863 return;
2864 }
2865 }
2866
Jeff Brown3915bb82010-11-05 15:02:16 -07002867 // Apply the fallback event policy.
2868 if (mFallbackEventHandler.dispatchKeyEvent(event)) {
2869 finishKeyEvent(event, sendDone, true);
2870 return;
2871 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002872
Jeff Brown3915bb82010-11-05 15:02:16 -07002873 // Handle automatic focus changes.
2874 if (event.getAction() == KeyEvent.ACTION_DOWN) {
2875 int direction = 0;
2876 switch (event.getKeyCode()) {
2877 case KeyEvent.KEYCODE_DPAD_LEFT:
Jeff Brown4e6319b2010-12-13 10:36:51 -08002878 if (event.hasNoModifiers()) {
2879 direction = View.FOCUS_LEFT;
2880 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002881 break;
2882 case KeyEvent.KEYCODE_DPAD_RIGHT:
Jeff Brown4e6319b2010-12-13 10:36:51 -08002883 if (event.hasNoModifiers()) {
2884 direction = View.FOCUS_RIGHT;
2885 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002886 break;
2887 case KeyEvent.KEYCODE_DPAD_UP:
Jeff Brown4e6319b2010-12-13 10:36:51 -08002888 if (event.hasNoModifiers()) {
2889 direction = View.FOCUS_UP;
2890 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002891 break;
2892 case KeyEvent.KEYCODE_DPAD_DOWN:
Jeff Brown4e6319b2010-12-13 10:36:51 -08002893 if (event.hasNoModifiers()) {
2894 direction = View.FOCUS_DOWN;
2895 }
2896 break;
2897 case KeyEvent.KEYCODE_TAB:
2898 if (event.hasNoModifiers()) {
2899 direction = View.FOCUS_FORWARD;
2900 } else if (event.hasModifiers(KeyEvent.META_SHIFT_ON)) {
2901 direction = View.FOCUS_BACKWARD;
2902 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002903 break;
2904 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002905
Jeff Brown3915bb82010-11-05 15:02:16 -07002906 if (direction != 0) {
2907 View focused = mView != null ? mView.findFocus() : null;
2908 if (focused != null) {
2909 View v = focused.focusSearch(direction);
2910 if (v != null && v != focused) {
2911 // do the math the get the interesting rect
2912 // of previous focused into the coord system of
2913 // newly focused view
2914 focused.getFocusedRect(mTempRect);
2915 if (mView instanceof ViewGroup) {
2916 ((ViewGroup) mView).offsetDescendantRectToMyCoords(
2917 focused, mTempRect);
2918 ((ViewGroup) mView).offsetRectIntoDescendantCoords(
2919 v, mTempRect);
2920 }
2921 if (v.requestFocus(direction, mTempRect)) {
2922 playSoundEffect(
2923 SoundEffectConstants.getContantForFocusDirection(direction));
2924 finishKeyEvent(event, sendDone, true);
2925 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002926 }
2927 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002928
2929 // Give the focused view a last chance to handle the dpad key.
2930 if (mView.dispatchUnhandledMove(focused, direction)) {
2931 finishKeyEvent(event, sendDone, true);
2932 return;
2933 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002934 }
2935 }
Jeff Brown3915bb82010-11-05 15:02:16 -07002936 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002937
Jeff Brown3915bb82010-11-05 15:02:16 -07002938 // Key was unhandled.
2939 finishKeyEvent(event, sendDone, false);
2940 }
2941
2942 private void finishKeyEvent(KeyEvent event, boolean sendDone, boolean handled) {
2943 if (sendDone) {
2944 finishInputEvent(handled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002945 }
2946 }
2947
Christopher Tatea53146c2010-09-07 11:57:52 -07002948 /* drag/drop */
Christopher Tate407b4e92010-11-30 17:14:08 -08002949 void setLocalDragState(Object obj) {
2950 mLocalDragState = obj;
2951 }
2952
Christopher Tatea53146c2010-09-07 11:57:52 -07002953 private void handleDragEvent(DragEvent event) {
2954 // From the root, only drag start/end/location are dispatched. entered/exited
2955 // are determined and dispatched by the viewgroup hierarchy, who then report
2956 // that back here for ultimate reporting back to the framework.
2957 if (mView != null && mAdded) {
2958 final int what = event.mAction;
2959
2960 if (what == DragEvent.ACTION_DRAG_EXITED) {
2961 // A direct EXITED event means that the window manager knows we've just crossed
2962 // a window boundary, so the current drag target within this one must have
2963 // just been exited. Send it the usual notifications and then we're done
2964 // for now.
Chris Tate9d1ab882010-11-02 15:55:39 -07002965 mView.dispatchDragEvent(event);
Christopher Tatea53146c2010-09-07 11:57:52 -07002966 } else {
2967 // Cache the drag description when the operation starts, then fill it in
2968 // on subsequent calls as a convenience
2969 if (what == DragEvent.ACTION_DRAG_STARTED) {
Chris Tate9d1ab882010-11-02 15:55:39 -07002970 mCurrentDragView = null; // Start the current-recipient tracking
Christopher Tatea53146c2010-09-07 11:57:52 -07002971 mDragDescription = event.mClipDescription;
2972 } else {
2973 event.mClipDescription = mDragDescription;
2974 }
2975
2976 // For events with a [screen] location, translate into window coordinates
2977 if ((what == DragEvent.ACTION_DRAG_LOCATION) || (what == DragEvent.ACTION_DROP)) {
2978 mDragPoint.set(event.mX, event.mY);
2979 if (mTranslator != null) {
2980 mTranslator.translatePointInScreenToAppWindow(mDragPoint);
2981 }
2982
2983 if (mCurScrollY != 0) {
2984 mDragPoint.offset(0, mCurScrollY);
2985 }
2986
2987 event.mX = mDragPoint.x;
2988 event.mY = mDragPoint.y;
2989 }
2990
2991 // Remember who the current drag target is pre-dispatch
2992 final View prevDragView = mCurrentDragView;
2993
2994 // Now dispatch the drag/drop event
Chris Tated4533f12010-10-19 15:15:08 -07002995 boolean result = mView.dispatchDragEvent(event);
Christopher Tatea53146c2010-09-07 11:57:52 -07002996
2997 // If we changed apparent drag target, tell the OS about it
2998 if (prevDragView != mCurrentDragView) {
2999 try {
3000 if (prevDragView != null) {
3001 sWindowSession.dragRecipientExited(mWindow);
3002 }
3003 if (mCurrentDragView != null) {
3004 sWindowSession.dragRecipientEntered(mWindow);
3005 }
3006 } catch (RemoteException e) {
3007 Slog.e(TAG, "Unable to note drag target change");
3008 }
Christopher Tatea53146c2010-09-07 11:57:52 -07003009 }
Chris Tated4533f12010-10-19 15:15:08 -07003010
Christopher Tate407b4e92010-11-30 17:14:08 -08003011 // Report the drop result when we're done
Chris Tated4533f12010-10-19 15:15:08 -07003012 if (what == DragEvent.ACTION_DROP) {
Christopher Tate1fc014f2011-01-19 12:56:26 -08003013 mDragDescription = null;
Chris Tated4533f12010-10-19 15:15:08 -07003014 try {
3015 Log.i(TAG, "Reporting drop result: " + result);
3016 sWindowSession.reportDropResult(mWindow, result);
3017 } catch (RemoteException e) {
3018 Log.e(TAG, "Unable to report drop result");
3019 }
3020 }
Christopher Tate407b4e92010-11-30 17:14:08 -08003021
3022 // When the drag operation ends, release any local state object
3023 // that may have been in use
3024 if (what == DragEvent.ACTION_DRAG_ENDED) {
3025 setLocalDragState(null);
3026 }
Christopher Tatea53146c2010-09-07 11:57:52 -07003027 }
3028 }
3029 event.recycle();
3030 }
3031
Joe Onorato664644d2011-01-23 17:53:23 -08003032 public void handleDispatchSystemUiVisibilityChanged(int visibility) {
3033 if (mView == null) return;
Joe Onorato14782f72011-01-25 19:53:17 -08003034 if (mAttachInfo != null) {
3035 mAttachInfo.mSystemUiVisibility = visibility;
3036 }
Joe Onorato664644d2011-01-23 17:53:23 -08003037 mView.dispatchSystemUiVisibilityChanged(visibility);
3038 }
3039
Christopher Tate2c095f32010-10-04 14:13:40 -07003040 public void getLastTouchPoint(Point outLocation) {
3041 outLocation.x = (int) mLastTouchPoint.x;
3042 outLocation.y = (int) mLastTouchPoint.y;
3043 }
3044
Chris Tate9d1ab882010-11-02 15:55:39 -07003045 public void setDragFocus(View newDragTarget) {
Christopher Tatea53146c2010-09-07 11:57:52 -07003046 if (mCurrentDragView != newDragTarget) {
Chris Tate048691c2010-10-12 17:39:18 -07003047 mCurrentDragView = newDragTarget;
Christopher Tatea53146c2010-09-07 11:57:52 -07003048 }
Christopher Tatea53146c2010-09-07 11:57:52 -07003049 }
3050
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003051 private AudioManager getAudioManager() {
3052 if (mView == null) {
3053 throw new IllegalStateException("getAudioManager called when there is no mView");
3054 }
3055 if (mAudioManager == null) {
3056 mAudioManager = (AudioManager) mView.getContext().getSystemService(Context.AUDIO_SERVICE);
3057 }
3058 return mAudioManager;
3059 }
3060
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07003061 private int relayoutWindow(WindowManager.LayoutParams params, int viewVisibility,
3062 boolean insetsPending) throws RemoteException {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07003063
3064 float appScale = mAttachInfo.mApplicationScale;
Mitsuru Oshima3d914922009-05-13 22:29:15 -07003065 boolean restore = false;
Mitsuru Oshima64f59342009-06-21 00:03:11 -07003066 if (params != null && mTranslator != null) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07003067 restore = true;
3068 params.backup();
Mitsuru Oshima64f59342009-06-21 00:03:11 -07003069 mTranslator.translateWindowLayout(params);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07003070 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07003071 if (params != null) {
3072 if (DBG) Log.d(TAG, "WindowLayout in layoutWindow:" + params);
Mitsuru Oshima3d914922009-05-13 22:29:15 -07003073 }
Dianne Hackborn694f79b2010-03-17 19:44:59 -07003074 mPendingConfiguration.seq = 0;
Dianne Hackbornf123e492010-09-24 11:16:23 -07003075 //Log.d(TAG, ">>>>>> CALLING relayout");
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07003076 int relayoutResult = sWindowSession.relayout(
3077 mWindow, params,
Dianne Hackborn189ee182010-12-02 21:48:53 -08003078 (int) (mView.getMeasuredWidth() * appScale + 0.5f),
3079 (int) (mView.getMeasuredHeight() * appScale + 0.5f),
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07003080 viewVisibility, insetsPending, mWinFrame,
Dianne Hackborn694f79b2010-03-17 19:44:59 -07003081 mPendingContentInsets, mPendingVisibleInsets,
3082 mPendingConfiguration, mSurface);
Dianne Hackbornf123e492010-09-24 11:16:23 -07003083 //Log.d(TAG, "<<<<<< BACK FROM relayout");
Mitsuru Oshima3d914922009-05-13 22:29:15 -07003084 if (restore) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07003085 params.restore();
Mitsuru Oshima3d914922009-05-13 22:29:15 -07003086 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07003087
3088 if (mTranslator != null) {
3089 mTranslator.translateRectInScreenToAppWinFrame(mWinFrame);
3090 mTranslator.translateRectInScreenToAppWindow(mPendingContentInsets);
3091 mTranslator.translateRectInScreenToAppWindow(mPendingVisibleInsets);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07003092 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07003093 return relayoutResult;
3094 }
Romain Guy8506ab42009-06-11 17:35:47 -07003095
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07003096 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003097 * {@inheritDoc}
3098 */
3099 public void playSoundEffect(int effectId) {
3100 checkThread();
3101
Jean-Michel Trivi13b18fd2010-05-05 09:18:15 -07003102 try {
3103 final AudioManager audioManager = getAudioManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003104
Jean-Michel Trivi13b18fd2010-05-05 09:18:15 -07003105 switch (effectId) {
3106 case SoundEffectConstants.CLICK:
3107 audioManager.playSoundEffect(AudioManager.FX_KEY_CLICK);
3108 return;
3109 case SoundEffectConstants.NAVIGATION_DOWN:
3110 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_DOWN);
3111 return;
3112 case SoundEffectConstants.NAVIGATION_LEFT:
3113 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_LEFT);
3114 return;
3115 case SoundEffectConstants.NAVIGATION_RIGHT:
3116 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_RIGHT);
3117 return;
3118 case SoundEffectConstants.NAVIGATION_UP:
3119 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_UP);
3120 return;
3121 default:
3122 throw new IllegalArgumentException("unknown effect id " + effectId +
3123 " not defined in " + SoundEffectConstants.class.getCanonicalName());
3124 }
3125 } catch (IllegalStateException e) {
3126 // Exception thrown by getAudioManager() when mView is null
3127 Log.e(TAG, "FATAL EXCEPTION when attempting to play sound effect: " + e);
3128 e.printStackTrace();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003129 }
3130 }
3131
3132 /**
3133 * {@inheritDoc}
3134 */
3135 public boolean performHapticFeedback(int effectId, boolean always) {
3136 try {
3137 return sWindowSession.performHapticFeedback(mWindow, effectId, always);
3138 } catch (RemoteException e) {
3139 return false;
3140 }
3141 }
3142
3143 /**
3144 * {@inheritDoc}
3145 */
3146 public View focusSearch(View focused, int direction) {
3147 checkThread();
3148 if (!(mView instanceof ViewGroup)) {
3149 return null;
3150 }
3151 return FocusFinder.getInstance().findNextFocus((ViewGroup) mView, focused, direction);
3152 }
3153
3154 public void debug() {
3155 mView.debug();
3156 }
3157
3158 public void die(boolean immediate) {
Dianne Hackborn94d69142009-09-28 22:14:42 -07003159 if (immediate) {
3160 doDie();
3161 } else {
3162 sendEmptyMessage(DIE);
3163 }
3164 }
3165
3166 void doDie() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003167 checkThread();
Jeff Brownb75fa302010-07-15 23:47:29 -07003168 if (LOCAL_LOGV) Log.v(TAG, "DIE in " + this + " of " + mSurface);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003169 synchronized (this) {
3170 if (mAdded && !mFirst) {
Romain Guy29d89972010-09-22 16:10:57 -07003171 destroyHardwareRenderer();
3172
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003173 int viewVisibility = mView.getVisibility();
3174 boolean viewVisibilityChanged = mViewVisibility != viewVisibility;
3175 if (mWindowAttributesChanged || viewVisibilityChanged) {
3176 // If layout params have been changed, first give them
3177 // to the window manager to make sure it has the correct
3178 // animation info.
3179 try {
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07003180 if ((relayoutWindow(mWindowAttributes, viewVisibility, false)
3181 & WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003182 sWindowSession.finishDrawing(mWindow);
3183 }
3184 } catch (RemoteException e) {
3185 }
3186 }
3187
Dianne Hackborn0586a1b2009-09-06 21:08:27 -07003188 mSurface.release();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003189 }
3190 if (mAdded) {
3191 mAdded = false;
Dianne Hackborn94d69142009-09-28 22:14:42 -07003192 dispatchDetachedFromWindow();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003193 }
3194 }
3195 }
3196
Romain Guy29d89972010-09-22 16:10:57 -07003197 private void destroyHardwareRenderer() {
Romain Guyb051e892010-09-28 19:09:36 -07003198 if (mAttachInfo.mHardwareRenderer != null) {
3199 mAttachInfo.mHardwareRenderer.destroy(true);
3200 mAttachInfo.mHardwareRenderer = null;
Romain Guy29d89972010-09-22 16:10:57 -07003201 mAttachInfo.mHardwareAccelerated = false;
3202 }
3203 }
3204
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003205 public void dispatchFinishedEvent(int seq, boolean handled) {
3206 Message msg = obtainMessage(FINISHED_EVENT);
3207 msg.arg1 = seq;
3208 msg.arg2 = handled ? 1 : 0;
3209 sendMessage(msg);
3210 }
Mitsuru Oshima3d914922009-05-13 22:29:15 -07003211
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003212 public void dispatchResized(int w, int h, Rect coveredInsets,
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003213 Rect visibleInsets, boolean reportDraw, Configuration newConfig) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003214 if (DEBUG_LAYOUT) Log.v(TAG, "Resizing " + this + ": w=" + w
3215 + " h=" + h + " coveredInsets=" + coveredInsets.toShortString()
3216 + " visibleInsets=" + visibleInsets.toShortString()
3217 + " reportDraw=" + reportDraw);
3218 Message msg = obtainMessage(reportDraw ? RESIZED_REPORT :RESIZED);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07003219 if (mTranslator != null) {
3220 mTranslator.translateRectInScreenToAppWindow(coveredInsets);
3221 mTranslator.translateRectInScreenToAppWindow(visibleInsets);
3222 w *= mTranslator.applicationInvertedScale;
3223 h *= mTranslator.applicationInvertedScale;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07003224 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07003225 msg.arg1 = w;
3226 msg.arg2 = h;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08003227 ResizedInfo ri = new ResizedInfo();
3228 ri.coveredInsets = new Rect(coveredInsets);
3229 ri.visibleInsets = new Rect(visibleInsets);
3230 ri.newConfig = newConfig;
3231 msg.obj = ri;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003232 sendMessage(msg);
3233 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07003234
Jeff Brown3915bb82010-11-05 15:02:16 -07003235 private InputQueue.FinishedCallback mFinishedCallback;
Jeff Brown46b9ac02010-04-22 18:58:52 -07003236
3237 private final InputHandler mInputHandler = new InputHandler() {
Jeff Brown3915bb82010-11-05 15:02:16 -07003238 public void handleKey(KeyEvent event, InputQueue.FinishedCallback finishedCallback) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07003239 startInputEvent(finishedCallback);
Jeff Brown92ff1dd2010-08-11 16:16:06 -07003240 dispatchKey(event, true);
Jeff Brown46b9ac02010-04-22 18:58:52 -07003241 }
3242
Jeff Brown3915bb82010-11-05 15:02:16 -07003243 public void handleMotion(MotionEvent event, InputQueue.FinishedCallback finishedCallback) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07003244 startInputEvent(finishedCallback);
3245 dispatchMotion(event, true);
Jeff Brown46b9ac02010-04-22 18:58:52 -07003246 }
3247 };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003248
3249 public void dispatchKey(KeyEvent event) {
Jeff Brown92ff1dd2010-08-11 16:16:06 -07003250 dispatchKey(event, false);
3251 }
3252
3253 private void dispatchKey(KeyEvent event, boolean sendDone) {
3254 //noinspection ConstantConditions
3255 if (false && event.getAction() == KeyEvent.ACTION_DOWN) {
3256 if (event.getKeyCode() == KeyEvent.KEYCODE_CAMERA) {
Romain Guy812ccbe2010-06-01 14:07:24 -07003257 if (DBG) Log.d("keydisp", "===================================================");
3258 if (DBG) Log.d("keydisp", "Focused view Hierarchy is:");
3259
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003260 debug();
3261
Romain Guy812ccbe2010-06-01 14:07:24 -07003262 if (DBG) Log.d("keydisp", "===================================================");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003263 }
3264 }
3265
3266 Message msg = obtainMessage(DISPATCH_KEY);
3267 msg.obj = event;
Jeff Brown92ff1dd2010-08-11 16:16:06 -07003268 msg.arg1 = sendDone ? 1 : 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003269
3270 if (LOCAL_LOGV) Log.v(
Jeff Brownc5ed5912010-07-14 18:48:53 -07003271 TAG, "sending key " + event + " to " + mView);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003272
3273 sendMessageAtTime(msg, event.getEventTime());
3274 }
Jeff Brownc5ed5912010-07-14 18:48:53 -07003275
3276 public void dispatchMotion(MotionEvent event) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07003277 dispatchMotion(event, false);
3278 }
3279
3280 private void dispatchMotion(MotionEvent event, boolean sendDone) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07003281 int source = event.getSource();
3282 if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07003283 dispatchPointer(event, sendDone);
Jeff Brownc5ed5912010-07-14 18:48:53 -07003284 } else if ((source & InputDevice.SOURCE_CLASS_TRACKBALL) != 0) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07003285 dispatchTrackball(event, sendDone);
Jeff Brownc5ed5912010-07-14 18:48:53 -07003286 } else {
Jeff Browncb1404e2011-01-15 18:14:15 -08003287 dispatchGenericMotion(event, sendDone);
Jeff Brownc5ed5912010-07-14 18:48:53 -07003288 }
3289 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003290
Jeff Brown00fa7bd2010-07-02 15:37:36 -07003291 public void dispatchPointer(MotionEvent event) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07003292 dispatchPointer(event, false);
3293 }
3294
3295 private void dispatchPointer(MotionEvent event, boolean sendDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003296 Message msg = obtainMessage(DISPATCH_POINTER);
3297 msg.obj = event;
Jeff Brown93ed4e32010-09-23 13:51:48 -07003298 msg.arg1 = sendDone ? 1 : 0;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07003299 sendMessageAtTime(msg, event.getEventTime());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003300 }
3301
Jeff Brown00fa7bd2010-07-02 15:37:36 -07003302 public void dispatchTrackball(MotionEvent event) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07003303 dispatchTrackball(event, false);
3304 }
3305
3306 private void dispatchTrackball(MotionEvent event, boolean sendDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003307 Message msg = obtainMessage(DISPATCH_TRACKBALL);
3308 msg.obj = event;
Jeff Brown93ed4e32010-09-23 13:51:48 -07003309 msg.arg1 = sendDone ? 1 : 0;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07003310 sendMessageAtTime(msg, event.getEventTime());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003311 }
Jeff Browncb1404e2011-01-15 18:14:15 -08003312
3313 private void dispatchGenericMotion(MotionEvent event, boolean sendDone) {
3314 Message msg = obtainMessage(DISPATCH_GENERIC_MOTION);
3315 msg.obj = event;
3316 msg.arg1 = sendDone ? 1 : 0;
3317 sendMessageAtTime(msg, event.getEventTime());
3318 }
3319
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003320 public void dispatchAppVisibility(boolean visible) {
3321 Message msg = obtainMessage(DISPATCH_APP_VISIBILITY);
3322 msg.arg1 = visible ? 1 : 0;
3323 sendMessage(msg);
3324 }
3325
3326 public void dispatchGetNewSurface() {
3327 Message msg = obtainMessage(DISPATCH_GET_NEW_SURFACE);
3328 sendMessage(msg);
3329 }
3330
3331 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
3332 Message msg = Message.obtain();
3333 msg.what = WINDOW_FOCUS_CHANGED;
3334 msg.arg1 = hasFocus ? 1 : 0;
3335 msg.arg2 = inTouchMode ? 1 : 0;
3336 sendMessage(msg);
3337 }
3338
Dianne Hackbornffa42482009-09-23 22:20:11 -07003339 public void dispatchCloseSystemDialogs(String reason) {
3340 Message msg = Message.obtain();
3341 msg.what = CLOSE_SYSTEM_DIALOGS;
3342 msg.obj = reason;
3343 sendMessage(msg);
3344 }
Christopher Tatea53146c2010-09-07 11:57:52 -07003345
3346 public void dispatchDragEvent(DragEvent event) {
Chris Tate91e9bb32010-10-12 12:58:43 -07003347 final int what;
3348 if (event.getAction() == DragEvent.ACTION_DRAG_LOCATION) {
3349 what = DISPATCH_DRAG_LOCATION_EVENT;
3350 removeMessages(what);
3351 } else {
3352 what = DISPATCH_DRAG_EVENT;
3353 }
3354 Message msg = obtainMessage(what, event);
Christopher Tatea53146c2010-09-07 11:57:52 -07003355 sendMessage(msg);
3356 }
3357
Joe Onorato664644d2011-01-23 17:53:23 -08003358 public void dispatchSystemUiVisibilityChanged(int visibility) {
3359 sendMessage(obtainMessage(DISPATCH_SYSTEM_UI_VISIBILITY, visibility, 0));
3360 }
3361
svetoslavganov75986cf2009-05-14 22:28:01 -07003362 /**
3363 * The window is getting focus so if there is anything focused/selected
3364 * send an {@link AccessibilityEvent} to announce that.
3365 */
3366 private void sendAccessibilityEvents() {
3367 if (!AccessibilityManager.getInstance(mView.getContext()).isEnabled()) {
3368 return;
3369 }
3370 mView.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
3371 View focusedView = mView.findFocus();
3372 if (focusedView != null && focusedView != mView) {
3373 focusedView.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
3374 }
3375 }
3376
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003377 public boolean showContextMenuForChild(View originalView) {
3378 return false;
3379 }
3380
Adam Powell6e346362010-07-23 10:18:23 -07003381 public ActionMode startActionModeForChild(View originalView, ActionMode.Callback callback) {
3382 return null;
3383 }
3384
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003385 public void createContextMenu(ContextMenu menu) {
3386 }
3387
3388 public void childDrawableStateChanged(View child) {
3389 }
3390
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003391 void checkThread() {
3392 if (mThread != Thread.currentThread()) {
3393 throw new CalledFromWrongThreadException(
3394 "Only the original thread that created a view hierarchy can touch its views.");
3395 }
3396 }
3397
3398 public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
3399 // ViewRoot never intercepts touch event, so this can be a no-op
3400 }
3401
3402 public boolean requestChildRectangleOnScreen(View child, Rect rectangle,
3403 boolean immediate) {
3404 return scrollToRectOrFocus(rectangle, immediate);
3405 }
Romain Guy8506ab42009-06-11 17:35:47 -07003406
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07003407 class TakenSurfaceHolder extends BaseSurfaceHolder {
3408 @Override
3409 public boolean onAllowLockCanvas() {
3410 return mDrawingAllowed;
3411 }
3412
3413 @Override
3414 public void onRelayoutContainer() {
3415 // Not currently interesting -- from changing between fixed and layout size.
3416 }
3417
3418 public void setFormat(int format) {
3419 ((RootViewSurfaceTaker)mView).setSurfaceFormat(format);
3420 }
3421
3422 public void setType(int type) {
3423 ((RootViewSurfaceTaker)mView).setSurfaceType(type);
3424 }
3425
3426 @Override
3427 public void onUpdateSurface() {
3428 // We take care of format and type changes on our own.
3429 throw new IllegalStateException("Shouldn't be here");
3430 }
3431
3432 public boolean isCreating() {
3433 return mIsCreating;
3434 }
3435
3436 @Override
3437 public void setFixedSize(int width, int height) {
3438 throw new UnsupportedOperationException(
3439 "Currently only support sizing from layout");
3440 }
3441
3442 public void setKeepScreenOn(boolean screenOn) {
3443 ((RootViewSurfaceTaker)mView).setSurfaceKeepScreenOn(screenOn);
3444 }
3445 }
3446
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003447 static class InputMethodCallback extends IInputMethodCallback.Stub {
3448 private WeakReference<ViewRoot> mViewRoot;
3449
3450 public InputMethodCallback(ViewRoot viewRoot) {
3451 mViewRoot = new WeakReference<ViewRoot>(viewRoot);
3452 }
Romain Guy8506ab42009-06-11 17:35:47 -07003453
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003454 public void finishedEvent(int seq, boolean handled) {
3455 final ViewRoot viewRoot = mViewRoot.get();
3456 if (viewRoot != null) {
3457 viewRoot.dispatchFinishedEvent(seq, handled);
3458 }
3459 }
3460
3461 public void sessionCreated(IInputMethodSession session) throws RemoteException {
3462 // Stub -- not for use in the client.
3463 }
3464 }
Romain Guy8506ab42009-06-11 17:35:47 -07003465
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003466 static class W extends IWindow.Stub {
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07003467 private final WeakReference<ViewRoot> mViewRoot;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003468
Romain Guyfb8b7632010-08-23 21:05:08 -07003469 W(ViewRoot viewRoot) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003470 mViewRoot = new WeakReference<ViewRoot>(viewRoot);
3471 }
3472
Romain Guyfb8b7632010-08-23 21:05:08 -07003473 public void resized(int w, int h, Rect coveredInsets, Rect visibleInsets,
3474 boolean reportDraw, Configuration newConfig) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003475 final ViewRoot viewRoot = mViewRoot.get();
3476 if (viewRoot != null) {
Romain Guyfb8b7632010-08-23 21:05:08 -07003477 viewRoot.dispatchResized(w, h, coveredInsets, visibleInsets, reportDraw, newConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003478 }
3479 }
3480
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003481 public void dispatchAppVisibility(boolean visible) {
3482 final ViewRoot viewRoot = mViewRoot.get();
3483 if (viewRoot != null) {
3484 viewRoot.dispatchAppVisibility(visible);
3485 }
3486 }
3487
3488 public void dispatchGetNewSurface() {
3489 final ViewRoot viewRoot = mViewRoot.get();
3490 if (viewRoot != null) {
3491 viewRoot.dispatchGetNewSurface();
3492 }
3493 }
3494
3495 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
3496 final ViewRoot viewRoot = mViewRoot.get();
3497 if (viewRoot != null) {
3498 viewRoot.windowFocusChanged(hasFocus, inTouchMode);
3499 }
3500 }
3501
3502 private static int checkCallingPermission(String permission) {
3503 if (!Process.supportsProcesses()) {
3504 return PackageManager.PERMISSION_GRANTED;
3505 }
3506
3507 try {
3508 return ActivityManagerNative.getDefault().checkPermission(
3509 permission, Binder.getCallingPid(), Binder.getCallingUid());
3510 } catch (RemoteException e) {
3511 return PackageManager.PERMISSION_DENIED;
3512 }
3513 }
3514
3515 public void executeCommand(String command, String parameters, ParcelFileDescriptor out) {
3516 final ViewRoot viewRoot = mViewRoot.get();
3517 if (viewRoot != null) {
3518 final View view = viewRoot.mView;
3519 if (view != null) {
3520 if (checkCallingPermission(Manifest.permission.DUMP) !=
3521 PackageManager.PERMISSION_GRANTED) {
3522 throw new SecurityException("Insufficient permissions to invoke"
3523 + " executeCommand() from pid=" + Binder.getCallingPid()
3524 + ", uid=" + Binder.getCallingUid());
3525 }
3526
3527 OutputStream clientStream = null;
3528 try {
3529 clientStream = new ParcelFileDescriptor.AutoCloseOutputStream(out);
3530 ViewDebug.dispatchCommand(view, command, parameters, clientStream);
3531 } catch (IOException e) {
3532 e.printStackTrace();
3533 } finally {
3534 if (clientStream != null) {
3535 try {
3536 clientStream.close();
3537 } catch (IOException e) {
3538 e.printStackTrace();
3539 }
3540 }
3541 }
3542 }
3543 }
3544 }
Dianne Hackborn72c82ab2009-08-11 21:13:54 -07003545
Dianne Hackbornffa42482009-09-23 22:20:11 -07003546 public void closeSystemDialogs(String reason) {
3547 final ViewRoot viewRoot = mViewRoot.get();
3548 if (viewRoot != null) {
3549 viewRoot.dispatchCloseSystemDialogs(reason);
3550 }
3551 }
3552
Marco Nelissenbf6956b2009-11-09 15:21:13 -08003553 public void dispatchWallpaperOffsets(float x, float y, float xStep, float yStep,
3554 boolean sync) {
Dianne Hackborn19382ac2009-09-11 21:13:37 -07003555 if (sync) {
3556 try {
3557 sWindowSession.wallpaperOffsetsComplete(asBinder());
3558 } catch (RemoteException e) {
3559 }
3560 }
Dianne Hackborn72c82ab2009-08-11 21:13:54 -07003561 }
Dianne Hackborn75804932009-10-20 20:15:20 -07003562
3563 public void dispatchWallpaperCommand(String action, int x, int y,
3564 int z, Bundle extras, boolean sync) {
3565 if (sync) {
3566 try {
3567 sWindowSession.wallpaperCommandComplete(asBinder(), null);
3568 } catch (RemoteException e) {
3569 }
3570 }
3571 }
Christopher Tatea53146c2010-09-07 11:57:52 -07003572
3573 /* Drag/drop */
3574 public void dispatchDragEvent(DragEvent event) {
3575 final ViewRoot viewRoot = mViewRoot.get();
3576 if (viewRoot != null) {
3577 viewRoot.dispatchDragEvent(event);
3578 }
3579 }
Joe Onorato664644d2011-01-23 17:53:23 -08003580
3581 @Override
3582 public void dispatchSystemUiVisibilityChanged(int visibility) {
3583 final ViewRoot viewRoot = mViewRoot.get();
3584 if (viewRoot != null) {
3585 viewRoot.dispatchSystemUiVisibilityChanged(visibility);
3586 }
3587 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003588 }
3589
3590 /**
3591 * Maintains state information for a single trackball axis, generating
3592 * discrete (DPAD) movements based on raw trackball motion.
3593 */
3594 static final class TrackballAxis {
3595 /**
3596 * The maximum amount of acceleration we will apply.
3597 */
3598 static final float MAX_ACCELERATION = 20;
Romain Guy8506ab42009-06-11 17:35:47 -07003599
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003600 /**
3601 * The maximum amount of time (in milliseconds) between events in order
3602 * for us to consider the user to be doing fast trackball movements,
3603 * and thus apply an acceleration.
3604 */
3605 static final long FAST_MOVE_TIME = 150;
Romain Guy8506ab42009-06-11 17:35:47 -07003606
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003607 /**
3608 * Scaling factor to the time (in milliseconds) between events to how
3609 * much to multiple/divide the current acceleration. When movement
3610 * is < FAST_MOVE_TIME this multiplies the acceleration; when >
3611 * FAST_MOVE_TIME it divides it.
3612 */
3613 static final float ACCEL_MOVE_SCALING_FACTOR = (1.0f/40);
Romain Guy8506ab42009-06-11 17:35:47 -07003614
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003615 float position;
3616 float absPosition;
3617 float acceleration = 1;
3618 long lastMoveTime = 0;
3619 int step;
3620 int dir;
3621 int nonAccelMovement;
3622
3623 void reset(int _step) {
3624 position = 0;
3625 acceleration = 1;
3626 lastMoveTime = 0;
3627 step = _step;
3628 dir = 0;
3629 }
3630
3631 /**
3632 * Add trackball movement into the state. If the direction of movement
3633 * has been reversed, the state is reset before adding the
3634 * movement (so that you don't have to compensate for any previously
3635 * collected movement before see the result of the movement in the
3636 * new direction).
3637 *
3638 * @return Returns the absolute value of the amount of movement
3639 * collected so far.
3640 */
3641 float collect(float off, long time, String axis) {
3642 long normTime;
3643 if (off > 0) {
3644 normTime = (long)(off * FAST_MOVE_TIME);
3645 if (dir < 0) {
3646 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to positive!");
3647 position = 0;
3648 step = 0;
3649 acceleration = 1;
3650 lastMoveTime = 0;
3651 }
3652 dir = 1;
3653 } else if (off < 0) {
3654 normTime = (long)((-off) * FAST_MOVE_TIME);
3655 if (dir > 0) {
3656 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to negative!");
3657 position = 0;
3658 step = 0;
3659 acceleration = 1;
3660 lastMoveTime = 0;
3661 }
3662 dir = -1;
3663 } else {
3664 normTime = 0;
3665 }
Romain Guy8506ab42009-06-11 17:35:47 -07003666
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003667 // The number of milliseconds between each movement that is
3668 // considered "normal" and will not result in any acceleration
3669 // or deceleration, scaled by the offset we have here.
3670 if (normTime > 0) {
3671 long delta = time - lastMoveTime;
3672 lastMoveTime = time;
3673 float acc = acceleration;
3674 if (delta < normTime) {
3675 // The user is scrolling rapidly, so increase acceleration.
3676 float scale = (normTime-delta) * ACCEL_MOVE_SCALING_FACTOR;
3677 if (scale > 1) acc *= scale;
3678 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " accelerate: off="
3679 + off + " normTime=" + normTime + " delta=" + delta
3680 + " scale=" + scale + " acc=" + acc);
3681 acceleration = acc < MAX_ACCELERATION ? acc : MAX_ACCELERATION;
3682 } else {
3683 // The user is scrolling slowly, so decrease acceleration.
3684 float scale = (delta-normTime) * ACCEL_MOVE_SCALING_FACTOR;
3685 if (scale > 1) acc /= scale;
3686 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " deccelerate: off="
3687 + off + " normTime=" + normTime + " delta=" + delta
3688 + " scale=" + scale + " acc=" + acc);
3689 acceleration = acc > 1 ? acc : 1;
3690 }
3691 }
3692 position += off;
3693 return (absPosition = Math.abs(position));
3694 }
3695
3696 /**
3697 * Generate the number of discrete movement events appropriate for
3698 * the currently collected trackball movement.
3699 *
3700 * @param precision The minimum movement required to generate the
3701 * first discrete movement.
3702 *
3703 * @return Returns the number of discrete movements, either positive
3704 * or negative, or 0 if there is not enough trackball movement yet
3705 * for a discrete movement.
3706 */
3707 int generate(float precision) {
3708 int movement = 0;
3709 nonAccelMovement = 0;
3710 do {
3711 final int dir = position >= 0 ? 1 : -1;
3712 switch (step) {
3713 // If we are going to execute the first step, then we want
3714 // to do this as soon as possible instead of waiting for
3715 // a full movement, in order to make things look responsive.
3716 case 0:
3717 if (absPosition < precision) {
3718 return movement;
3719 }
3720 movement += dir;
3721 nonAccelMovement += dir;
3722 step = 1;
3723 break;
3724 // If we have generated the first movement, then we need
3725 // to wait for the second complete trackball motion before
3726 // generating the second discrete movement.
3727 case 1:
3728 if (absPosition < 2) {
3729 return movement;
3730 }
3731 movement += dir;
3732 nonAccelMovement += dir;
3733 position += dir > 0 ? -2 : 2;
3734 absPosition = Math.abs(position);
3735 step = 2;
3736 break;
3737 // After the first two, we generate discrete movements
3738 // consistently with the trackball, applying an acceleration
3739 // if the trackball is moving quickly. This is a simple
3740 // acceleration on top of what we already compute based
3741 // on how quickly the wheel is being turned, to apply
3742 // a longer increasing acceleration to continuous movement
3743 // in one direction.
3744 default:
3745 if (absPosition < 1) {
3746 return movement;
3747 }
3748 movement += dir;
3749 position += dir >= 0 ? -1 : 1;
3750 absPosition = Math.abs(position);
3751 float acc = acceleration;
3752 acc *= 1.1f;
3753 acceleration = acc < MAX_ACCELERATION ? acc : acceleration;
3754 break;
3755 }
3756 } while (true);
3757 }
3758 }
3759
3760 public static final class CalledFromWrongThreadException extends AndroidRuntimeException {
3761 public CalledFromWrongThreadException(String msg) {
3762 super(msg);
3763 }
3764 }
3765
3766 private SurfaceHolder mHolder = new SurfaceHolder() {
3767 // we only need a SurfaceHolder for opengl. it would be nice
3768 // to implement everything else though, especially the callback
3769 // support (opengl doesn't make use of it right now, but eventually
3770 // will).
3771 public Surface getSurface() {
3772 return mSurface;
3773 }
3774
3775 public boolean isCreating() {
3776 return false;
3777 }
3778
3779 public void addCallback(Callback callback) {
3780 }
3781
3782 public void removeCallback(Callback callback) {
3783 }
3784
3785 public void setFixedSize(int width, int height) {
3786 }
3787
3788 public void setSizeFromLayout() {
3789 }
3790
3791 public void setFormat(int format) {
3792 }
3793
3794 public void setType(int type) {
3795 }
3796
3797 public void setKeepScreenOn(boolean screenOn) {
3798 }
3799
3800 public Canvas lockCanvas() {
3801 return null;
3802 }
3803
3804 public Canvas lockCanvas(Rect dirty) {
3805 return null;
3806 }
3807
3808 public void unlockCanvasAndPost(Canvas canvas) {
3809 }
3810 public Rect getSurfaceFrame() {
3811 return null;
3812 }
3813 };
3814
3815 static RunQueue getRunQueue() {
3816 RunQueue rq = sRunQueues.get();
3817 if (rq != null) {
3818 return rq;
3819 }
3820 rq = new RunQueue();
3821 sRunQueues.set(rq);
3822 return rq;
3823 }
Romain Guy8506ab42009-06-11 17:35:47 -07003824
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003825 /**
3826 * @hide
3827 */
3828 static final class RunQueue {
3829 private final ArrayList<HandlerAction> mActions = new ArrayList<HandlerAction>();
3830
3831 void post(Runnable action) {
3832 postDelayed(action, 0);
3833 }
3834
3835 void postDelayed(Runnable action, long delayMillis) {
3836 HandlerAction handlerAction = new HandlerAction();
3837 handlerAction.action = action;
3838 handlerAction.delay = delayMillis;
3839
3840 synchronized (mActions) {
3841 mActions.add(handlerAction);
3842 }
3843 }
3844
3845 void removeCallbacks(Runnable action) {
3846 final HandlerAction handlerAction = new HandlerAction();
3847 handlerAction.action = action;
3848
3849 synchronized (mActions) {
3850 final ArrayList<HandlerAction> actions = mActions;
3851
3852 while (actions.remove(handlerAction)) {
3853 // Keep going
3854 }
3855 }
3856 }
3857
3858 void executeActions(Handler handler) {
3859 synchronized (mActions) {
3860 final ArrayList<HandlerAction> actions = mActions;
3861 final int count = actions.size();
3862
3863 for (int i = 0; i < count; i++) {
3864 final HandlerAction handlerAction = actions.get(i);
3865 handler.postDelayed(handlerAction.action, handlerAction.delay);
3866 }
3867
Romain Guy15df6702009-08-17 20:17:30 -07003868 actions.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003869 }
3870 }
3871
3872 private static class HandlerAction {
3873 Runnable action;
3874 long delay;
3875
3876 @Override
3877 public boolean equals(Object o) {
3878 if (this == o) return true;
3879 if (o == null || getClass() != o.getClass()) return false;
3880
3881 HandlerAction that = (HandlerAction) o;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003882 return !(action != null ? !action.equals(that.action) : that.action != null);
3883
3884 }
3885
3886 @Override
3887 public int hashCode() {
3888 int result = action != null ? action.hashCode() : 0;
3889 result = 31 * result + (int) (delay ^ (delay >>> 32));
3890 return result;
3891 }
3892 }
3893 }
3894
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003895 private static native void nativeShowFPS(Canvas canvas, int durationMillis);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003896}