blob: 77ba6fe0073ec2828145427380a83b62b311e1f3 [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
Dianne Hackborndc8a7f62010-05-10 11:29:34 -070019import com.android.internal.view.BaseSurfaceHolder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080020import com.android.internal.view.IInputMethodCallback;
21import com.android.internal.view.IInputMethodSession;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -070022import com.android.internal.view.RootViewSurfaceTaker;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080023
24import android.graphics.Canvas;
25import android.graphics.PixelFormat;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080026import android.graphics.PorterDuff;
27import android.graphics.Rect;
28import android.graphics.Region;
29import android.os.*;
30import android.os.Process;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080031import android.util.AndroidRuntimeException;
32import android.util.Config;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -070033import android.util.DisplayMetrics;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080034import android.util.Log;
35import android.util.EventLog;
Chet Haase949dbf72010-08-11 18:41:06 -070036import android.util.Slog;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080037import android.util.SparseArray;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080038import android.view.View.MeasureSpec;
svetoslavganov75986cf2009-05-14 22:28:01 -070039import android.view.accessibility.AccessibilityEvent;
40import android.view.accessibility.AccessibilityManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080041import android.view.inputmethod.InputConnection;
42import android.view.inputmethod.InputMethodManager;
43import android.widget.Scroller;
44import android.content.pm.PackageManager;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -070045import android.content.res.CompatibilityInfo;
Dianne Hackborne36d6e22010-02-17 19:46:25 -080046import android.content.res.Configuration;
Mitsuru Oshima38ed7d772009-07-21 14:39:34 -070047import android.content.res.Resources;
Dianne Hackborne36d6e22010-02-17 19:46:25 -080048import android.content.ComponentCallbacks;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080049import android.content.Context;
50import android.app.ActivityManagerNative;
51import android.Manifest;
52import android.media.AudioManager;
53
54import java.lang.ref.WeakReference;
55import java.io.IOException;
56import java.io.OutputStream;
57import java.util.ArrayList;
58
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080059/**
60 * The top of a view hierarchy, implementing the needed protocol between View
61 * and the WindowManager. This is for the most part an internal implementation
62 * detail of {@link WindowManagerImpl}.
63 *
64 * {@hide}
65 */
Romain Guy812ccbe2010-06-01 14:07:24 -070066@SuppressWarnings({"EmptyCatchBlock", "PointlessBooleanExpression"})
67public final class ViewRoot extends Handler implements ViewParent, View.AttachInfo.Callbacks {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080068 private static final String TAG = "ViewRoot";
69 private static final boolean DBG = false;
Mike Reedfd716532009-10-12 14:42:56 -040070 private static final boolean SHOW_FPS = false;
Romain Guy812ccbe2010-06-01 14:07:24 -070071 private static final boolean LOCAL_LOGV = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080072 /** @noinspection PointlessBooleanExpression*/
73 private static final boolean DEBUG_DRAW = false || LOCAL_LOGV;
74 private static final boolean DEBUG_LAYOUT = false || LOCAL_LOGV;
Christopher Tatefa9e7c02010-05-06 12:07:10 -070075 private static final boolean DEBUG_INPUT = true || LOCAL_LOGV;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080076 private static final boolean DEBUG_INPUT_RESIZE = false || LOCAL_LOGV;
77 private static final boolean DEBUG_ORIENTATION = false || LOCAL_LOGV;
78 private static final boolean DEBUG_TRACKBALL = false || LOCAL_LOGV;
79 private static final boolean DEBUG_IMF = false || LOCAL_LOGV;
Dianne Hackborn694f79b2010-03-17 19:44:59 -070080 private static final boolean DEBUG_CONFIGURATION = false || LOCAL_LOGV;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080081 private static final boolean WATCH_POINTER = false;
82
Michael Chan53071d62009-05-13 17:29:48 -070083 private static final boolean MEASURE_LATENCY = false;
84 private static LatencyTimer lt;
85
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080086 /**
87 * Maximum time we allow the user to roll the trackball enough to generate
88 * a key event, before resetting the counters.
89 */
90 static final int MAX_TRACKBALL_DELAY = 250;
91
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080092 static IWindowSession sWindowSession;
93
94 static final Object mStaticInit = new Object();
95 static boolean mInitialized = false;
96
97 static final ThreadLocal<RunQueue> sRunQueues = new ThreadLocal<RunQueue>();
98
Dianne Hackborn2a9094d2010-02-03 19:20:09 -080099 static final ArrayList<Runnable> sFirstDrawHandlers = new ArrayList<Runnable>();
100 static boolean sFirstDrawComplete = false;
101
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800102 static final ArrayList<ComponentCallbacks> sConfigCallbacks
103 = new ArrayList<ComponentCallbacks>();
104
Romain Guy8506ab42009-06-11 17:35:47 -0700105 private static int sDrawTime;
Romain Guy13922e02009-05-12 17:56:14 -0700106
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800107 long mLastTrackballTime = 0;
108 final TrackballAxis mTrackballAxisX = new TrackballAxis();
109 final TrackballAxis mTrackballAxisY = new TrackballAxis();
110
111 final int[] mTmpLocation = new int[2];
Romain Guy8506ab42009-06-11 17:35:47 -0700112
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800113 final InputMethodCallback mInputMethodCallback;
114 final SparseArray<Object> mPendingEvents = new SparseArray<Object>();
115 int mPendingEventSeq = 0;
Romain Guy8506ab42009-06-11 17:35:47 -0700116
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800117 final Thread mThread;
118
119 final WindowLeaked mLocation;
120
121 final WindowManager.LayoutParams mWindowAttributes = new WindowManager.LayoutParams();
122
123 final W mWindow;
124
125 View mView;
126 View mFocusedView;
127 View mRealFocusedView; // this is not set to null in touch mode
128 int mViewVisibility;
129 boolean mAppVisible = true;
130
Dianne Hackbornd76b67c2010-07-13 17:48:30 -0700131 SurfaceHolder.Callback2 mSurfaceHolderCallback;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700132 BaseSurfaceHolder mSurfaceHolder;
133 boolean mIsCreating;
134 boolean mDrawingAllowed;
135
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800136 final Region mTransparentRegion;
137 final Region mPreviousTransparentRegion;
138
139 int mWidth;
140 int mHeight;
141 Rect mDirty; // will be a graphics.Region soon
Romain Guybb93d552009-03-24 21:04:15 -0700142 boolean mIsAnimating;
Romain Guy8506ab42009-06-11 17:35:47 -0700143
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700144 CompatibilityInfo.Translator mTranslator;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800145
146 final View.AttachInfo mAttachInfo;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700147 InputChannel mInputChannel;
Dianne Hackborn1e4b9f32010-06-23 14:10:57 -0700148 InputQueue.Callback mInputQueueCallback;
149 InputQueue mInputQueue;
Dianne Hackborna95e4cb2010-06-18 18:09:33 -0700150
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800151 final Rect mTempRect; // used in the transaction to not thrash the heap.
152 final Rect mVisRect; // used to retrieve visible rect of focused view.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800153
154 boolean mTraversalScheduled;
155 boolean mWillDrawSoon;
156 boolean mLayoutRequested;
157 boolean mFirst;
158 boolean mReportNextDraw;
159 boolean mFullRedrawNeeded;
160 boolean mNewSurfaceNeeded;
161 boolean mHasHadWindowFocus;
162 boolean mLastWasImTarget;
163
164 boolean mWindowAttributesChanged = false;
165
166 // These can be accessed by any thread, must be protected with a lock.
Mathias Agopian5583dc62009-07-09 16:28:11 -0700167 // Surface can never be reassigned or cleared (use Surface.clear()).
168 private final Surface mSurface = new Surface();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800169
170 boolean mAdded;
171 boolean mAddedTouchMode;
172
173 /*package*/ int mAddNesting;
174
175 // These are accessed by multiple threads.
176 final Rect mWinFrame; // frame given by window manager.
177
178 final Rect mPendingVisibleInsets = new Rect();
179 final Rect mPendingContentInsets = new Rect();
180 final ViewTreeObserver.InternalInsetsInfo mLastGivenInsets
181 = new ViewTreeObserver.InternalInsetsInfo();
182
Dianne Hackborn694f79b2010-03-17 19:44:59 -0700183 final Configuration mLastConfiguration = new Configuration();
184 final Configuration mPendingConfiguration = new Configuration();
185
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800186 class ResizedInfo {
187 Rect coveredInsets;
188 Rect visibleInsets;
189 Configuration newConfig;
190 }
191
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800192 boolean mScrollMayChange;
193 int mSoftInputMode;
194 View mLastScrolledFocus;
195 int mScrollY;
196 int mCurScrollY;
197 Scroller mScroller;
Romain Guy8506ab42009-06-11 17:35:47 -0700198
Romain Guy8506ab42009-06-11 17:35:47 -0700199 final ViewConfiguration mViewConfiguration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800200
201 /**
202 * see {@link #playSoundEffect(int)}
203 */
204 AudioManager mAudioManager;
205
Dianne Hackborn11ea3342009-07-22 21:48:55 -0700206 private final int mDensity;
Adam Powellb08013c2010-09-16 16:28:11 -0700207
Dianne Hackborn4c62fc02009-08-08 20:40:27 -0700208 public static IWindowSession getWindowSession(Looper mainLooper) {
209 synchronized (mStaticInit) {
210 if (!mInitialized) {
211 try {
212 InputMethodManager imm = InputMethodManager.getInstance(mainLooper);
213 sWindowSession = IWindowManager.Stub.asInterface(
214 ServiceManager.getService("window"))
215 .openSession(imm.getClient(), imm.getInputContext());
216 mInitialized = true;
217 } catch (RemoteException e) {
218 }
219 }
220 return sWindowSession;
221 }
222 }
223
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800224 public ViewRoot(Context context) {
225 super();
226
Romain Guy812ccbe2010-06-01 14:07:24 -0700227 if (MEASURE_LATENCY) {
228 if (lt == null) {
229 lt = new LatencyTimer(100, 1000);
230 }
Michael Chan53071d62009-05-13 17:29:48 -0700231 }
232
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800233 // Initialize the statics when this class is first instantiated. This is
234 // done here instead of in the static block because Zygote does not
235 // allow the spawning of threads.
Dianne Hackborn4c62fc02009-08-08 20:40:27 -0700236 getWindowSession(context.getMainLooper());
237
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800238 mThread = Thread.currentThread();
239 mLocation = new WindowLeaked(null);
240 mLocation.fillInStackTrace();
241 mWidth = -1;
242 mHeight = -1;
243 mDirty = new Rect();
244 mTempRect = new Rect();
245 mVisRect = new Rect();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800246 mWinFrame = new Rect();
Romain Guyfb8b7632010-08-23 21:05:08 -0700247 mWindow = new W(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800248 mInputMethodCallback = new InputMethodCallback(this);
249 mViewVisibility = View.GONE;
250 mTransparentRegion = new Region();
251 mPreviousTransparentRegion = new Region();
252 mFirst = true; // true for the first time the view is added
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800253 mAdded = false;
254 mAttachInfo = new View.AttachInfo(sWindowSession, mWindow, this, this);
255 mViewConfiguration = ViewConfiguration.get(context);
Dianne Hackborn11ea3342009-07-22 21:48:55 -0700256 mDensity = context.getResources().getDisplayMetrics().densityDpi;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800257 }
258
Dianne Hackborn2a9094d2010-02-03 19:20:09 -0800259 public static void addFirstDrawHandler(Runnable callback) {
260 synchronized (sFirstDrawHandlers) {
261 if (!sFirstDrawComplete) {
262 sFirstDrawHandlers.add(callback);
263 }
264 }
265 }
266
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800267 public static void addConfigCallback(ComponentCallbacks callback) {
268 synchronized (sConfigCallbacks) {
269 sConfigCallbacks.add(callback);
270 }
271 }
272
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800273 // FIXME for perf testing only
274 private boolean mProfile = false;
275
276 /**
277 * Call this to profile the next traversal call.
278 * FIXME for perf testing only. Remove eventually
279 */
280 public void profile() {
281 mProfile = true;
282 }
283
284 /**
285 * Indicates whether we are in touch mode. Calling this method triggers an IPC
286 * call and should be avoided whenever possible.
287 *
288 * @return True, if the device is in touch mode, false otherwise.
289 *
290 * @hide
291 */
292 static boolean isInTouchMode() {
293 if (mInitialized) {
294 try {
295 return sWindowSession.getInTouchMode();
296 } catch (RemoteException e) {
297 }
298 }
299 return false;
300 }
301
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800302 /**
303 * We have one child
304 */
Romain Guye4d01122010-06-16 18:44:05 -0700305 public void setView(View view, WindowManager.LayoutParams attrs, View panelParentView) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800306 synchronized (this) {
307 if (mView == null) {
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700308 mView = view;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700309 mWindowAttributes.copyFrom(attrs);
Mitsuru Oshima1ecf5d22009-07-06 17:20:38 -0700310 attrs = mWindowAttributes;
Romain Guye4d01122010-06-16 18:44:05 -0700311
Romain Guy529b60a2010-08-03 18:05:47 -0700312 enableHardwareAcceleration(attrs);
Romain Guye4d01122010-06-16 18:44:05 -0700313
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700314 if (view instanceof RootViewSurfaceTaker) {
315 mSurfaceHolderCallback =
316 ((RootViewSurfaceTaker)view).willYouTakeTheSurface();
317 if (mSurfaceHolderCallback != null) {
318 mSurfaceHolder = new TakenSurfaceHolder();
Dianne Hackborn289b9b62010-07-09 11:44:11 -0700319 mSurfaceHolder.setFormat(PixelFormat.UNKNOWN);
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700320 }
321 }
Mitsuru Oshima38ed7d772009-07-21 14:39:34 -0700322 Resources resources = mView.getContext().getResources();
323 CompatibilityInfo compatibilityInfo = resources.getCompatibilityInfo();
Mitsuru Oshima589cebe2009-07-22 20:38:58 -0700324 mTranslator = compatibilityInfo.getTranslator();
Mitsuru Oshima38ed7d772009-07-21 14:39:34 -0700325
326 if (mTranslator != null || !compatibilityInfo.supportsScreen()) {
Mitsuru Oshima240f8a72009-07-22 20:39:14 -0700327 mSurface.setCompatibleDisplayMetrics(resources.getDisplayMetrics(),
328 mTranslator);
Mitsuru Oshima38ed7d772009-07-21 14:39:34 -0700329 }
330
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -0700331 boolean restore = false;
Romain Guy35b38ce2009-10-07 13:38:55 -0700332 if (mTranslator != null) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -0700333 restore = true;
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700334 attrs.backup();
335 mTranslator.translateWindowLayout(attrs);
Mitsuru Oshima3d914922009-05-13 22:29:15 -0700336 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700337 if (DEBUG_LAYOUT) Log.d(TAG, "WindowLayout in setView:" + attrs);
338
Mitsuru Oshima1ecf5d22009-07-06 17:20:38 -0700339 if (!compatibilityInfo.supportsScreen()) {
340 attrs.flags |= WindowManager.LayoutParams.FLAG_COMPATIBLE_WINDOW;
341 }
342
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800343 mSoftInputMode = attrs.softInputMode;
344 mWindowAttributesChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800345 mAttachInfo.mRootView = view;
Romain Guy35b38ce2009-10-07 13:38:55 -0700346 mAttachInfo.mScalingRequired = mTranslator != null;
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700347 mAttachInfo.mApplicationScale =
348 mTranslator == null ? 1.0f : mTranslator.applicationScale;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800349 if (panelParentView != null) {
350 mAttachInfo.mPanelParentWindowToken
351 = panelParentView.getApplicationWindowToken();
352 }
353 mAdded = true;
354 int res; /* = WindowManagerImpl.ADD_OKAY; */
Romain Guy8506ab42009-06-11 17:35:47 -0700355
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800356 // Schedule the first layout -before- adding to the window
357 // manager, to make sure we do the relayout before receiving
358 // any other events from the system.
359 requestLayout();
Jeff Brown46b9ac02010-04-22 18:58:52 -0700360 mInputChannel = new InputChannel();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800361 try {
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700362 res = sWindowSession.add(mWindow, mWindowAttributes,
Jeff Brown46b9ac02010-04-22 18:58:52 -0700363 getHostVisibility(), mAttachInfo.mContentInsets,
364 mInputChannel);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800365 } catch (RemoteException e) {
366 mAdded = false;
367 mView = null;
368 mAttachInfo.mRootView = null;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700369 mInputChannel = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800370 unscheduleTraversals();
371 throw new RuntimeException("Adding window failed", e);
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700372 } finally {
373 if (restore) {
374 attrs.restore();
375 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800376 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700377
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700378 if (mTranslator != null) {
379 mTranslator.translateRectInScreenToAppWindow(mAttachInfo.mContentInsets);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700380 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800381 mPendingContentInsets.set(mAttachInfo.mContentInsets);
382 mPendingVisibleInsets.set(0, 0, 0, 0);
Jeff Brownc5ed5912010-07-14 18:48:53 -0700383 if (Config.LOGV) Log.v(TAG, "Added window " + mWindow);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800384 if (res < WindowManagerImpl.ADD_OKAY) {
385 mView = null;
386 mAttachInfo.mRootView = null;
387 mAdded = false;
388 unscheduleTraversals();
389 switch (res) {
390 case WindowManagerImpl.ADD_BAD_APP_TOKEN:
391 case WindowManagerImpl.ADD_BAD_SUBWINDOW_TOKEN:
392 throw new WindowManagerImpl.BadTokenException(
393 "Unable to add window -- token " + attrs.token
394 + " is not valid; is your activity running?");
395 case WindowManagerImpl.ADD_NOT_APP_TOKEN:
396 throw new WindowManagerImpl.BadTokenException(
397 "Unable to add window -- token " + attrs.token
398 + " is not for an application");
399 case WindowManagerImpl.ADD_APP_EXITING:
400 throw new WindowManagerImpl.BadTokenException(
401 "Unable to add window -- app for token " + attrs.token
402 + " is exiting");
403 case WindowManagerImpl.ADD_DUPLICATE_ADD:
404 throw new WindowManagerImpl.BadTokenException(
405 "Unable to add window -- window " + mWindow
406 + " has already been added");
407 case WindowManagerImpl.ADD_STARTING_NOT_NEEDED:
408 // Silently ignore -- we would have just removed it
409 // right away, anyway.
410 return;
411 case WindowManagerImpl.ADD_MULTIPLE_SINGLETON:
412 throw new WindowManagerImpl.BadTokenException(
413 "Unable to add window " + mWindow +
414 " -- another window of this type already exists");
415 case WindowManagerImpl.ADD_PERMISSION_DENIED:
416 throw new WindowManagerImpl.BadTokenException(
417 "Unable to add window " + mWindow +
418 " -- permission denied for this window type");
419 }
420 throw new RuntimeException(
421 "Unable to add window -- unknown error code " + res);
422 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700423
Jeff Brown00fa7bd2010-07-02 15:37:36 -0700424 if (view instanceof RootViewSurfaceTaker) {
425 mInputQueueCallback =
426 ((RootViewSurfaceTaker)view).willYouTakeTheInputQueue();
427 }
428 if (mInputQueueCallback != null) {
429 mInputQueue = new InputQueue(mInputChannel);
430 mInputQueueCallback.onInputQueueCreated(mInputQueue);
431 } else {
432 InputQueue.registerInputChannel(mInputChannel, mInputHandler,
433 Looper.myQueue());
Jeff Brown46b9ac02010-04-22 18:58:52 -0700434 }
435
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800436 view.assignParent(this);
437 mAddedTouchMode = (res&WindowManagerImpl.ADD_FLAG_IN_TOUCH_MODE) != 0;
438 mAppVisible = (res&WindowManagerImpl.ADD_FLAG_APP_VISIBLE) != 0;
439 }
440 }
441 }
442
Romain Guy529b60a2010-08-03 18:05:47 -0700443 private void enableHardwareAcceleration(WindowManager.LayoutParams attrs) {
Romain Guye4d01122010-06-16 18:44:05 -0700444 // Only enable hardware acceleration if we are not in the system process
445 // The window manager creates ViewRoots to display animated preview windows
446 // of launching apps and we don't want those to be hardware accelerated
Romain Guy52339202010-09-03 16:04:46 -0700447 if (!HardwareRenderer.sRendererDisabled) {
Romain Guye4d01122010-06-16 18:44:05 -0700448 // Try to enable hardware acceleration if requested
Romain Guy529b60a2010-08-03 18:05:47 -0700449 if (attrs != null &&
450 (attrs.flags & WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED) != 0) {
Romain Guye4d01122010-06-16 18:44:05 -0700451 final boolean translucent = attrs.format != PixelFormat.OPAQUE;
Romain Guyb051e892010-09-28 19:09:36 -0700452 if (mAttachInfo.mHardwareRenderer != null) {
453 mAttachInfo.mHardwareRenderer.destroy(true);
Romain Guy4caa4ed2010-08-25 14:46:24 -0700454 }
Romain Guyb051e892010-09-28 19:09:36 -0700455 mAttachInfo.mHardwareRenderer = HardwareRenderer.createGlRenderer(2, translucent);
Romain Guy2bffd262010-09-12 17:40:02 -0700456 mAttachInfo.mHardwareAccelerated = true;
Romain Guye4d01122010-06-16 18:44:05 -0700457 }
458 }
459 }
460
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800461 public View getView() {
462 return mView;
463 }
464
465 final WindowLeaked getLocation() {
466 return mLocation;
467 }
468
469 void setLayoutParams(WindowManager.LayoutParams attrs, boolean newView) {
470 synchronized (this) {
The Android Open Source Project10592532009-03-18 17:39:46 -0700471 int oldSoftInputMode = mWindowAttributes.softInputMode;
Mitsuru Oshima5a2b91d2009-07-16 16:30:02 -0700472 // preserve compatible window flag if exists.
473 int compatibleWindowFlag =
474 mWindowAttributes.flags & WindowManager.LayoutParams.FLAG_COMPATIBLE_WINDOW;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800475 mWindowAttributes.copyFrom(attrs);
Mitsuru Oshima5a2b91d2009-07-16 16:30:02 -0700476 mWindowAttributes.flags |= compatibleWindowFlag;
477
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800478 if (newView) {
479 mSoftInputMode = attrs.softInputMode;
480 requestLayout();
481 }
The Android Open Source Project10592532009-03-18 17:39:46 -0700482 // Don't lose the mode we last auto-computed.
483 if ((attrs.softInputMode&WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST)
484 == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED) {
485 mWindowAttributes.softInputMode = (mWindowAttributes.softInputMode
486 & ~WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST)
487 | (oldSoftInputMode
488 & WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST);
489 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800490 mWindowAttributesChanged = true;
491 scheduleTraversals();
492 }
493 }
494
495 void handleAppVisibility(boolean visible) {
496 if (mAppVisible != visible) {
497 mAppVisible = visible;
498 scheduleTraversals();
499 }
500 }
501
502 void handleGetNewSurface() {
503 mNewSurfaceNeeded = true;
504 mFullRedrawNeeded = true;
505 scheduleTraversals();
506 }
507
508 /**
509 * {@inheritDoc}
510 */
511 public void requestLayout() {
512 checkThread();
513 mLayoutRequested = true;
514 scheduleTraversals();
515 }
516
517 /**
518 * {@inheritDoc}
519 */
520 public boolean isLayoutRequested() {
521 return mLayoutRequested;
522 }
523
524 public void invalidateChild(View child, Rect dirty) {
525 checkThread();
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700526 if (DEBUG_DRAW) Log.v(TAG, "Invalidate child: " + dirty);
527 if (mCurScrollY != 0 || mTranslator != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800528 mTempRect.set(dirty);
Romain Guy1e095972009-07-07 11:22:45 -0700529 dirty = mTempRect;
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700530 if (mCurScrollY != 0) {
Romain Guy1e095972009-07-07 11:22:45 -0700531 dirty.offset(0, -mCurScrollY);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700532 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700533 if (mTranslator != null) {
Romain Guy1e095972009-07-07 11:22:45 -0700534 mTranslator.translateRectInAppWindowToScreen(dirty);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700535 }
Romain Guy1e095972009-07-07 11:22:45 -0700536 if (mAttachInfo.mScalingRequired) {
537 dirty.inset(-1, -1);
538 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800539 }
540 mDirty.union(dirty);
541 if (!mWillDrawSoon) {
542 scheduleTraversals();
543 }
544 }
545
546 public ViewParent getParent() {
547 return null;
548 }
549
550 public ViewParent invalidateChildInParent(final int[] location, final Rect dirty) {
551 invalidateChild(null, dirty);
552 return null;
553 }
554
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700555 public boolean getChildVisibleRect(View child, Rect r, android.graphics.Point offset) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800556 if (child != mView) {
557 throw new RuntimeException("child is not mine, honest!");
558 }
559 // Note: don't apply scroll offset, because we want to know its
560 // visibility in the virtual canvas being given to the view hierarchy.
561 return r.intersect(0, 0, mWidth, mHeight);
562 }
563
564 public void bringChildToFront(View child) {
565 }
566
567 public void scheduleTraversals() {
568 if (!mTraversalScheduled) {
569 mTraversalScheduled = true;
570 sendEmptyMessage(DO_TRAVERSAL);
571 }
572 }
573
574 public void unscheduleTraversals() {
575 if (mTraversalScheduled) {
576 mTraversalScheduled = false;
577 removeMessages(DO_TRAVERSAL);
578 }
579 }
580
581 int getHostVisibility() {
582 return mAppVisible ? mView.getVisibility() : View.GONE;
583 }
Romain Guy8506ab42009-06-11 17:35:47 -0700584
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800585 private void performTraversals() {
586 // cache mView since it is used so much below...
587 final View host = mView;
588
589 if (DBG) {
590 System.out.println("======================================");
591 System.out.println("performTraversals");
592 host.debug();
593 }
594
595 if (host == null || !mAdded)
596 return;
597
598 mTraversalScheduled = false;
599 mWillDrawSoon = true;
600 boolean windowResizesToFitContent = false;
601 boolean fullRedrawNeeded = mFullRedrawNeeded;
602 boolean newSurface = false;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700603 boolean surfaceChanged = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800604 WindowManager.LayoutParams lp = mWindowAttributes;
605
606 int desiredWindowWidth;
607 int desiredWindowHeight;
608 int childWidthMeasureSpec;
609 int childHeightMeasureSpec;
610
611 final View.AttachInfo attachInfo = mAttachInfo;
612
613 final int viewVisibility = getHostVisibility();
614 boolean viewVisibilityChanged = mViewVisibility != viewVisibility
615 || mNewSurfaceNeeded;
616
617 WindowManager.LayoutParams params = null;
618 if (mWindowAttributesChanged) {
619 mWindowAttributesChanged = false;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700620 surfaceChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800621 params = lp;
622 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700623 Rect frame = mWinFrame;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800624 if (mFirst) {
625 fullRedrawNeeded = true;
626 mLayoutRequested = true;
627
Romain Guy8506ab42009-06-11 17:35:47 -0700628 DisplayMetrics packageMetrics =
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700629 mView.getContext().getResources().getDisplayMetrics();
630 desiredWindowWidth = packageMetrics.widthPixels;
631 desiredWindowHeight = packageMetrics.heightPixels;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800632
633 // For the very first time, tell the view hierarchy that it
634 // is attached to the window. Note that at this point the surface
635 // object is not initialized to its backing store, but soon it
636 // will be (assuming the window is visible).
637 attachInfo.mSurface = mSurface;
Dianne Hackborn289b9b62010-07-09 11:44:11 -0700638 attachInfo.mTranslucentWindow = PixelFormat.formatHasAlpha(lp.format);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800639 attachInfo.mHasWindowFocus = false;
640 attachInfo.mWindowVisibility = viewVisibility;
641 attachInfo.mRecomputeGlobalAttributes = false;
642 attachInfo.mKeepScreenOn = false;
643 viewVisibilityChanged = false;
Dianne Hackborn694f79b2010-03-17 19:44:59 -0700644 mLastConfiguration.setTo(host.getResources().getConfiguration());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800645 host.dispatchAttachedToWindow(attachInfo, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800646 //Log.i(TAG, "Screen on initialized: " + attachInfo.mKeepScreenOn);
svetoslavganov75986cf2009-05-14 22:28:01 -0700647
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800648 } else {
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700649 desiredWindowWidth = frame.width();
650 desiredWindowHeight = frame.height();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800651 if (desiredWindowWidth != mWidth || desiredWindowHeight != mHeight) {
Jeff Brownc5ed5912010-07-14 18:48:53 -0700652 if (DEBUG_ORIENTATION) Log.v(TAG,
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700653 "View " + host + " resized to: " + frame);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800654 fullRedrawNeeded = true;
655 mLayoutRequested = true;
656 windowResizesToFitContent = true;
657 }
658 }
659
660 if (viewVisibilityChanged) {
661 attachInfo.mWindowVisibility = viewVisibility;
662 host.dispatchWindowVisibilityChanged(viewVisibility);
663 if (viewVisibility != View.VISIBLE || mNewSurfaceNeeded) {
Romain Guyb051e892010-09-28 19:09:36 -0700664 if (mAttachInfo.mHardwareRenderer != null) {
665 mAttachInfo.mHardwareRenderer.destroy(false);
Romain Guy4caa4ed2010-08-25 14:46:24 -0700666 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800667 }
668 if (viewVisibility == View.GONE) {
669 // After making a window gone, we will count it as being
670 // shown for the first time the next time it gets focus.
671 mHasHadWindowFocus = false;
672 }
673 }
674
675 boolean insetsChanged = false;
Romain Guy8506ab42009-06-11 17:35:47 -0700676
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800677 if (mLayoutRequested) {
Romain Guy15df6702009-08-17 20:17:30 -0700678 // Execute enqueued actions on every layout in case a view that was detached
679 // enqueued an action after being detached
680 getRunQueue().executeActions(attachInfo.mHandler);
681
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800682 if (mFirst) {
683 host.fitSystemWindows(mAttachInfo.mContentInsets);
684 // make sure touch mode code executes by setting cached value
685 // to opposite of the added touch mode.
686 mAttachInfo.mInTouchMode = !mAddedTouchMode;
Romain Guy2d4cff62010-04-09 15:39:00 -0700687 ensureTouchModeLocally(mAddedTouchMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800688 } else {
689 if (!mAttachInfo.mContentInsets.equals(mPendingContentInsets)) {
690 mAttachInfo.mContentInsets.set(mPendingContentInsets);
691 host.fitSystemWindows(mAttachInfo.mContentInsets);
692 insetsChanged = true;
693 if (DEBUG_LAYOUT) Log.v(TAG, "Content insets changing to: "
694 + mAttachInfo.mContentInsets);
695 }
696 if (!mAttachInfo.mVisibleInsets.equals(mPendingVisibleInsets)) {
697 mAttachInfo.mVisibleInsets.set(mPendingVisibleInsets);
698 if (DEBUG_LAYOUT) Log.v(TAG, "Visible insets changing to: "
699 + mAttachInfo.mVisibleInsets);
700 }
701 if (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT
702 || lp.height == ViewGroup.LayoutParams.WRAP_CONTENT) {
703 windowResizesToFitContent = true;
704
Romain Guy8506ab42009-06-11 17:35:47 -0700705 DisplayMetrics packageMetrics =
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700706 mView.getContext().getResources().getDisplayMetrics();
707 desiredWindowWidth = packageMetrics.widthPixels;
708 desiredWindowHeight = packageMetrics.heightPixels;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800709 }
710 }
711
712 childWidthMeasureSpec = getRootMeasureSpec(desiredWindowWidth, lp.width);
713 childHeightMeasureSpec = getRootMeasureSpec(desiredWindowHeight, lp.height);
714
715 // Ask host how big it wants to be
Jeff Brownc5ed5912010-07-14 18:48:53 -0700716 if (DEBUG_ORIENTATION || DEBUG_LAYOUT) Log.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800717 "Measuring " + host + " in display " + desiredWindowWidth
718 + "x" + desiredWindowHeight + "...");
719 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
720
721 if (DBG) {
722 System.out.println("======================================");
723 System.out.println("performTraversals -- after measure");
724 host.debug();
725 }
726 }
727
728 if (attachInfo.mRecomputeGlobalAttributes) {
729 //Log.i(TAG, "Computing screen on!");
730 attachInfo.mRecomputeGlobalAttributes = false;
731 boolean oldVal = attachInfo.mKeepScreenOn;
732 attachInfo.mKeepScreenOn = false;
733 host.dispatchCollectViewAttributes(0);
734 if (attachInfo.mKeepScreenOn != oldVal) {
735 params = lp;
736 //Log.i(TAG, "Keep screen on changed: " + attachInfo.mKeepScreenOn);
737 }
738 }
739
740 if (mFirst || attachInfo.mViewVisibilityChanged) {
741 attachInfo.mViewVisibilityChanged = false;
742 int resizeMode = mSoftInputMode &
743 WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST;
744 // If we are in auto resize mode, then we need to determine
745 // what mode to use now.
746 if (resizeMode == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED) {
747 final int N = attachInfo.mScrollContainers.size();
748 for (int i=0; i<N; i++) {
749 if (attachInfo.mScrollContainers.get(i).isShown()) {
750 resizeMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE;
751 }
752 }
753 if (resizeMode == 0) {
754 resizeMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN;
755 }
756 if ((lp.softInputMode &
757 WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) != resizeMode) {
758 lp.softInputMode = (lp.softInputMode &
759 ~WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) |
760 resizeMode;
761 params = lp;
762 }
763 }
764 }
Romain Guy8506ab42009-06-11 17:35:47 -0700765
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800766 if (params != null && (host.mPrivateFlags & View.REQUEST_TRANSPARENT_REGIONS) != 0) {
767 if (!PixelFormat.formatHasAlpha(params.format)) {
768 params.format = PixelFormat.TRANSLUCENT;
769 }
770 }
771
772 boolean windowShouldResize = mLayoutRequested && windowResizesToFitContent
Romain Guy2e4f4262010-04-06 11:07:52 -0700773 && ((mWidth != host.mMeasuredWidth || mHeight != host.mMeasuredHeight)
774 || (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT &&
775 frame.width() < desiredWindowWidth && frame.width() != mWidth)
776 || (lp.height == ViewGroup.LayoutParams.WRAP_CONTENT &&
777 frame.height() < desiredWindowHeight && frame.height() != mHeight));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800778
779 final boolean computesInternalInsets =
780 attachInfo.mTreeObserver.hasComputeInternalInsetsListeners();
Romain Guy812ccbe2010-06-01 14:07:24 -0700781
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800782 boolean insetsPending = false;
783 int relayoutResult = 0;
Romain Guy812ccbe2010-06-01 14:07:24 -0700784
785 if (mFirst || windowShouldResize || insetsChanged ||
786 viewVisibilityChanged || params != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800787
788 if (viewVisibility == View.VISIBLE) {
789 // If this window is giving internal insets to the window
790 // manager, and it is being added or changing its visibility,
791 // then we want to first give the window manager "fake"
792 // insets to cause it to effectively ignore the content of
793 // the window during layout. This avoids it briefly causing
794 // other windows to resize/move based on the raw frame of the
795 // window, waiting until we can finish laying out this window
796 // and get back to the window manager with the ultimately
797 // computed insets.
Romain Guy812ccbe2010-06-01 14:07:24 -0700798 insetsPending = computesInternalInsets && (mFirst || viewVisibilityChanged);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800799 }
800
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700801 if (mSurfaceHolder != null) {
802 mSurfaceHolder.mSurfaceLock.lock();
803 mDrawingAllowed = true;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700804 }
Romain Guy812ccbe2010-06-01 14:07:24 -0700805
806 boolean hwIntialized = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800807 boolean contentInsetsChanged = false;
Romain Guy13922e02009-05-12 17:56:14 -0700808 boolean visibleInsetsChanged;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700809 boolean hadSurface = mSurface.isValid();
Romain Guy812ccbe2010-06-01 14:07:24 -0700810
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800811 try {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800812 int fl = 0;
813 if (params != null) {
814 fl = params.flags;
815 if (attachInfo.mKeepScreenOn) {
816 params.flags |= WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
817 }
818 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700819 if (DEBUG_LAYOUT) {
820 Log.i(TAG, "host=w:" + host.mMeasuredWidth + ", h:" +
821 host.mMeasuredHeight + ", params=" + params);
822 }
823 relayoutResult = relayoutWindow(params, viewVisibility, insetsPending);
824
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800825 if (params != null) {
826 params.flags = fl;
827 }
828
829 if (DEBUG_LAYOUT) Log.v(TAG, "relayout: frame=" + frame.toShortString()
830 + " content=" + mPendingContentInsets.toShortString()
831 + " visible=" + mPendingVisibleInsets.toShortString()
832 + " surface=" + mSurface);
Romain Guy8506ab42009-06-11 17:35:47 -0700833
Dianne Hackborn694f79b2010-03-17 19:44:59 -0700834 if (mPendingConfiguration.seq != 0) {
835 if (DEBUG_CONFIGURATION) Log.v(TAG, "Visible with new config: "
836 + mPendingConfiguration);
837 updateConfiguration(mPendingConfiguration, !mFirst);
838 mPendingConfiguration.seq = 0;
839 }
840
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800841 contentInsetsChanged = !mPendingContentInsets.equals(
842 mAttachInfo.mContentInsets);
843 visibleInsetsChanged = !mPendingVisibleInsets.equals(
844 mAttachInfo.mVisibleInsets);
845 if (contentInsetsChanged) {
846 mAttachInfo.mContentInsets.set(mPendingContentInsets);
847 host.fitSystemWindows(mAttachInfo.mContentInsets);
848 if (DEBUG_LAYOUT) Log.v(TAG, "Content insets changing to: "
849 + mAttachInfo.mContentInsets);
850 }
851 if (visibleInsetsChanged) {
852 mAttachInfo.mVisibleInsets.set(mPendingVisibleInsets);
853 if (DEBUG_LAYOUT) Log.v(TAG, "Visible insets changing to: "
854 + mAttachInfo.mVisibleInsets);
855 }
856
857 if (!hadSurface) {
858 if (mSurface.isValid()) {
859 // If we are creating a new surface, then we need to
860 // completely redraw it. Also, when we get to the
861 // point of drawing it we will hold off and schedule
862 // a new traversal instead. This is so we can tell the
863 // window manager about all of the windows being displayed
864 // before actually drawing them, so it can display then
865 // all at once.
866 newSurface = true;
867 fullRedrawNeeded = true;
Jack Palevich61a6e682009-10-09 17:37:50 -0700868 mPreviousTransparentRegion.setEmpty();
Romain Guy8506ab42009-06-11 17:35:47 -0700869
Romain Guyb051e892010-09-28 19:09:36 -0700870 if (mAttachInfo.mHardwareRenderer != null) {
871 hwIntialized = mAttachInfo.mHardwareRenderer.initialize(mHolder);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800872 }
873 }
874 } else if (!mSurface.isValid()) {
875 // If the surface has been removed, then reset the scroll
876 // positions.
877 mLastScrolledFocus = null;
878 mScrollY = mCurScrollY = 0;
879 if (mScroller != null) {
880 mScroller.abortAnimation();
881 }
882 }
883 } catch (RemoteException e) {
884 }
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700885
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800886 if (DEBUG_ORIENTATION) Log.v(
Jeff Brownc5ed5912010-07-14 18:48:53 -0700887 TAG, "Relayout returned: frame=" + frame + ", surface=" + mSurface);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800888
889 attachInfo.mWindowLeft = frame.left;
890 attachInfo.mWindowTop = frame.top;
891
892 // !!FIXME!! This next section handles the case where we did not get the
893 // window size we asked for. We should avoid this by getting a maximum size from
894 // the window session beforehand.
895 mWidth = frame.width();
896 mHeight = frame.height();
897
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700898 if (mSurfaceHolder != null) {
899 // The app owns the surface; tell it about what is going on.
900 if (mSurface.isValid()) {
901 // XXX .copyFrom() doesn't work!
902 //mSurfaceHolder.mSurface.copyFrom(mSurface);
903 mSurfaceHolder.mSurface = mSurface;
904 }
905 mSurfaceHolder.mSurfaceLock.unlock();
906 if (mSurface.isValid()) {
907 if (!hadSurface) {
908 mSurfaceHolder.ungetCallbacks();
909
910 mIsCreating = true;
911 mSurfaceHolderCallback.surfaceCreated(mSurfaceHolder);
912 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
913 if (callbacks != null) {
914 for (SurfaceHolder.Callback c : callbacks) {
915 c.surfaceCreated(mSurfaceHolder);
916 }
917 }
918 surfaceChanged = true;
919 }
920 if (surfaceChanged) {
921 mSurfaceHolderCallback.surfaceChanged(mSurfaceHolder,
922 lp.format, mWidth, mHeight);
923 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
924 if (callbacks != null) {
925 for (SurfaceHolder.Callback c : callbacks) {
926 c.surfaceChanged(mSurfaceHolder, lp.format,
927 mWidth, mHeight);
928 }
929 }
930 }
931 mIsCreating = false;
932 } else if (hadSurface) {
933 mSurfaceHolder.ungetCallbacks();
934 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
935 mSurfaceHolderCallback.surfaceDestroyed(mSurfaceHolder);
936 if (callbacks != null) {
937 for (SurfaceHolder.Callback c : callbacks) {
938 c.surfaceDestroyed(mSurfaceHolder);
939 }
940 }
941 mSurfaceHolder.mSurfaceLock.lock();
942 // Make surface invalid.
943 //mSurfaceHolder.mSurface.copyFrom(mSurface);
944 mSurfaceHolder.mSurface = new Surface();
945 mSurfaceHolder.mSurfaceLock.unlock();
946 }
947 }
Romain Guy53389bd2010-09-07 17:16:32 -0700948
Romain Guyb051e892010-09-28 19:09:36 -0700949 if (hwIntialized || (windowShouldResize && mAttachInfo.mHardwareRenderer != null)) {
950 mAttachInfo.mHardwareRenderer.setup(mWidth, mHeight);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800951 }
952
953 boolean focusChangedDueToTouchMode = ensureTouchModeLocally(
Romain Guy2d4cff62010-04-09 15:39:00 -0700954 (relayoutResult&WindowManagerImpl.RELAYOUT_IN_TOUCH_MODE) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800955 if (focusChangedDueToTouchMode || mWidth != host.mMeasuredWidth
956 || mHeight != host.mMeasuredHeight || contentInsetsChanged) {
957 childWidthMeasureSpec = getRootMeasureSpec(mWidth, lp.width);
958 childHeightMeasureSpec = getRootMeasureSpec(mHeight, lp.height);
959
960 if (DEBUG_LAYOUT) Log.v(TAG, "Ooops, something changed! mWidth="
961 + mWidth + " measuredWidth=" + host.mMeasuredWidth
962 + " mHeight=" + mHeight
963 + " measuredHeight" + host.mMeasuredHeight
964 + " coveredInsetsChanged=" + contentInsetsChanged);
Romain Guy8506ab42009-06-11 17:35:47 -0700965
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800966 // Ask host how big it wants to be
967 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
968
969 // Implementation of weights from WindowManager.LayoutParams
970 // We just grow the dimensions as needed and re-measure if
971 // needs be
972 int width = host.mMeasuredWidth;
973 int height = host.mMeasuredHeight;
974 boolean measureAgain = false;
975
976 if (lp.horizontalWeight > 0.0f) {
977 width += (int) ((mWidth - width) * lp.horizontalWeight);
978 childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(width,
979 MeasureSpec.EXACTLY);
980 measureAgain = true;
981 }
982 if (lp.verticalWeight > 0.0f) {
983 height += (int) ((mHeight - height) * lp.verticalWeight);
984 childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(height,
985 MeasureSpec.EXACTLY);
986 measureAgain = true;
987 }
988
989 if (measureAgain) {
990 if (DEBUG_LAYOUT) Log.v(TAG,
991 "And hey let's measure once more: width=" + width
992 + " height=" + height);
993 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
994 }
995
996 mLayoutRequested = true;
997 }
998 }
999
1000 final boolean didLayout = mLayoutRequested;
1001 boolean triggerGlobalLayoutListener = didLayout
1002 || attachInfo.mRecomputeGlobalAttributes;
1003 if (didLayout) {
1004 mLayoutRequested = false;
1005 mScrollMayChange = true;
1006 if (DEBUG_ORIENTATION || DEBUG_LAYOUT) Log.v(
Jeff Brownc5ed5912010-07-14 18:48:53 -07001007 TAG, "Laying out " + host + " to (" +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001008 host.mMeasuredWidth + ", " + host.mMeasuredHeight + ")");
Romain Guy13922e02009-05-12 17:56:14 -07001009 long startTime = 0L;
Romain Guy5429e1d2010-09-07 12:38:00 -07001010 if (ViewDebug.DEBUG_PROFILE_LAYOUT) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001011 startTime = SystemClock.elapsedRealtime();
1012 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001013 host.layout(0, 0, host.mMeasuredWidth, host.mMeasuredHeight);
1014
Romain Guy13922e02009-05-12 17:56:14 -07001015 if (Config.DEBUG && ViewDebug.consistencyCheckEnabled) {
1016 if (!host.dispatchConsistencyCheck(ViewDebug.CONSISTENCY_LAYOUT)) {
1017 throw new IllegalStateException("The view hierarchy is an inconsistent state,"
1018 + "please refer to the logs with the tag "
1019 + ViewDebug.CONSISTENCY_LOG_TAG + " for more infomation.");
1020 }
1021 }
1022
Romain Guy5429e1d2010-09-07 12:38:00 -07001023 if (ViewDebug.DEBUG_PROFILE_LAYOUT) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001024 EventLog.writeEvent(60001, SystemClock.elapsedRealtime() - startTime);
1025 }
1026
1027 // By this point all views have been sized and positionned
1028 // We can compute the transparent area
1029
1030 if ((host.mPrivateFlags & View.REQUEST_TRANSPARENT_REGIONS) != 0) {
1031 // start out transparent
1032 // TODO: AVOID THAT CALL BY CACHING THE RESULT?
1033 host.getLocationInWindow(mTmpLocation);
1034 mTransparentRegion.set(mTmpLocation[0], mTmpLocation[1],
1035 mTmpLocation[0] + host.mRight - host.mLeft,
1036 mTmpLocation[1] + host.mBottom - host.mTop);
1037
1038 host.gatherTransparentRegion(mTransparentRegion);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001039 if (mTranslator != null) {
1040 mTranslator.translateRegionInWindowToScreen(mTransparentRegion);
1041 }
1042
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001043 if (!mTransparentRegion.equals(mPreviousTransparentRegion)) {
1044 mPreviousTransparentRegion.set(mTransparentRegion);
1045 // reconfigure window manager
1046 try {
1047 sWindowSession.setTransparentRegion(mWindow, mTransparentRegion);
1048 } catch (RemoteException e) {
1049 }
1050 }
1051 }
1052
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001053 if (DBG) {
1054 System.out.println("======================================");
1055 System.out.println("performTraversals -- after setFrame");
1056 host.debug();
1057 }
1058 }
1059
1060 if (triggerGlobalLayoutListener) {
1061 attachInfo.mRecomputeGlobalAttributes = false;
1062 attachInfo.mTreeObserver.dispatchOnGlobalLayout();
1063 }
1064
1065 if (computesInternalInsets) {
1066 ViewTreeObserver.InternalInsetsInfo insets = attachInfo.mGivenInternalInsets;
1067 final Rect givenContent = attachInfo.mGivenInternalInsets.contentInsets;
1068 final Rect givenVisible = attachInfo.mGivenInternalInsets.visibleInsets;
1069 givenContent.left = givenContent.top = givenContent.right
1070 = givenContent.bottom = givenVisible.left = givenVisible.top
1071 = givenVisible.right = givenVisible.bottom = 0;
1072 attachInfo.mTreeObserver.dispatchOnComputeInternalInsets(insets);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001073 Rect contentInsets = insets.contentInsets;
1074 Rect visibleInsets = insets.visibleInsets;
1075 if (mTranslator != null) {
1076 contentInsets = mTranslator.getTranslatedContentInsets(contentInsets);
1077 visibleInsets = mTranslator.getTranslatedVisbileInsets(visibleInsets);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001078 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001079 if (insetsPending || !mLastGivenInsets.equals(insets)) {
1080 mLastGivenInsets.set(insets);
1081 try {
1082 sWindowSession.setInsets(mWindow, insets.mTouchableInsets,
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001083 contentInsets, visibleInsets);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001084 } catch (RemoteException e) {
1085 }
1086 }
1087 }
Romain Guy8506ab42009-06-11 17:35:47 -07001088
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001089 if (mFirst) {
1090 // handle first focus request
1091 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: mView.hasFocus()="
1092 + mView.hasFocus());
1093 if (mView != null) {
1094 if (!mView.hasFocus()) {
1095 mView.requestFocus(View.FOCUS_FORWARD);
1096 mFocusedView = mRealFocusedView = mView.findFocus();
1097 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: requested focused view="
1098 + mFocusedView);
1099 } else {
1100 mRealFocusedView = mView.findFocus();
1101 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: existing focused view="
1102 + mRealFocusedView);
1103 }
1104 }
1105 }
1106
1107 mFirst = false;
1108 mWillDrawSoon = false;
1109 mNewSurfaceNeeded = false;
1110 mViewVisibility = viewVisibility;
1111
1112 if (mAttachInfo.mHasWindowFocus) {
1113 final boolean imTarget = WindowManager.LayoutParams
1114 .mayUseInputMethod(mWindowAttributes.flags);
1115 if (imTarget != mLastWasImTarget) {
1116 mLastWasImTarget = imTarget;
1117 InputMethodManager imm = InputMethodManager.peekInstance();
1118 if (imm != null && imTarget) {
1119 imm.startGettingWindowFocus(mView);
1120 imm.onWindowFocus(mView, mView.findFocus(),
1121 mWindowAttributes.softInputMode,
1122 !mHasHadWindowFocus, mWindowAttributes.flags);
1123 }
1124 }
1125 }
Romain Guy8506ab42009-06-11 17:35:47 -07001126
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001127 boolean cancelDraw = attachInfo.mTreeObserver.dispatchOnPreDraw();
1128
1129 if (!cancelDraw && !newSurface) {
1130 mFullRedrawNeeded = false;
1131 draw(fullRedrawNeeded);
1132
1133 if ((relayoutResult&WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0
1134 || mReportNextDraw) {
1135 if (LOCAL_LOGV) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001136 Log.v(TAG, "FINISHED DRAWING: " + mWindowAttributes.getTitle());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001137 }
1138 mReportNextDraw = false;
Dianne Hackbornd76b67c2010-07-13 17:48:30 -07001139 if (mSurfaceHolder != null && mSurface.isValid()) {
1140 mSurfaceHolderCallback.surfaceRedrawNeeded(mSurfaceHolder);
1141 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
1142 if (callbacks != null) {
1143 for (SurfaceHolder.Callback c : callbacks) {
1144 if (c instanceof SurfaceHolder.Callback2) {
1145 ((SurfaceHolder.Callback2)c).surfaceRedrawNeeded(
1146 mSurfaceHolder);
1147 }
1148 }
1149 }
1150 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001151 try {
1152 sWindowSession.finishDrawing(mWindow);
1153 } catch (RemoteException e) {
1154 }
1155 }
1156 } else {
1157 // We were supposed to report when we are done drawing. Since we canceled the
1158 // draw, remember it here.
1159 if ((relayoutResult&WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0) {
1160 mReportNextDraw = true;
1161 }
1162 if (fullRedrawNeeded) {
1163 mFullRedrawNeeded = true;
1164 }
1165 // Try again
1166 scheduleTraversals();
1167 }
1168 }
1169
1170 public void requestTransparentRegion(View child) {
1171 // the test below should not fail unless someone is messing with us
1172 checkThread();
1173 if (mView == child) {
1174 mView.mPrivateFlags |= View.REQUEST_TRANSPARENT_REGIONS;
1175 // Need to make sure we re-evaluate the window attributes next
1176 // time around, to ensure the window has the correct format.
1177 mWindowAttributesChanged = true;
1178 }
1179 }
1180
1181 /**
1182 * Figures out the measure spec for the root view in a window based on it's
1183 * layout params.
1184 *
1185 * @param windowSize
1186 * The available width or height of the window
1187 *
1188 * @param rootDimension
1189 * The layout params for one dimension (width or height) of the
1190 * window.
1191 *
1192 * @return The measure spec to use to measure the root view.
1193 */
1194 private int getRootMeasureSpec(int windowSize, int rootDimension) {
1195 int measureSpec;
1196 switch (rootDimension) {
1197
Romain Guy980a9382010-01-08 15:06:28 -08001198 case ViewGroup.LayoutParams.MATCH_PARENT:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001199 // Window can't resize. Force root view to be windowSize.
1200 measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.EXACTLY);
1201 break;
1202 case ViewGroup.LayoutParams.WRAP_CONTENT:
1203 // Window can resize. Set max size for root view.
1204 measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.AT_MOST);
1205 break;
1206 default:
1207 // Window wants to be an exact size. Force root view to be that size.
1208 measureSpec = MeasureSpec.makeMeasureSpec(rootDimension, MeasureSpec.EXACTLY);
1209 break;
1210 }
1211 return measureSpec;
1212 }
1213
1214 private void draw(boolean fullRedrawNeeded) {
1215 Surface surface = mSurface;
1216 if (surface == null || !surface.isValid()) {
1217 return;
1218 }
1219
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001220 if (!sFirstDrawComplete) {
1221 synchronized (sFirstDrawHandlers) {
1222 sFirstDrawComplete = true;
Romain Guy812ccbe2010-06-01 14:07:24 -07001223 final int count = sFirstDrawHandlers.size();
1224 for (int i = 0; i< count; i++) {
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001225 post(sFirstDrawHandlers.get(i));
1226 }
1227 }
1228 }
1229
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001230 scrollToRectOrFocus(null, false);
1231
1232 if (mAttachInfo.mViewScrollChanged) {
1233 mAttachInfo.mViewScrollChanged = false;
1234 mAttachInfo.mTreeObserver.dispatchOnScrollChanged();
1235 }
Romain Guy8506ab42009-06-11 17:35:47 -07001236
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001237 int yoff;
Romain Guy5bcdff42009-05-14 21:27:18 -07001238 final boolean scrolling = mScroller != null && mScroller.computeScrollOffset();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001239 if (scrolling) {
1240 yoff = mScroller.getCurrY();
1241 } else {
1242 yoff = mScrollY;
1243 }
1244 if (mCurScrollY != yoff) {
1245 mCurScrollY = yoff;
1246 fullRedrawNeeded = true;
1247 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001248 float appScale = mAttachInfo.mApplicationScale;
1249 boolean scalingRequired = mAttachInfo.mScalingRequired;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001250
1251 Rect dirty = mDirty;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001252 if (mSurfaceHolder != null) {
1253 // The app owns the surface, we won't draw.
1254 dirty.setEmpty();
1255 return;
1256 }
Romain Guy58ef7fb2010-09-13 12:52:37 -07001257
1258 if (fullRedrawNeeded) {
1259 mAttachInfo.mIgnoreDirtyState = true;
1260 dirty.union(0, 0, (int) (mWidth * appScale + 0.5f), (int) (mHeight * appScale + 0.5f));
1261 }
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001262
Romain Guyb051e892010-09-28 19:09:36 -07001263 if (mAttachInfo.mHardwareRenderer != null && mAttachInfo.mHardwareRenderer.isEnabled()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001264 if (!dirty.isEmpty()) {
Romain Guyb051e892010-09-28 19:09:36 -07001265 mAttachInfo.mHardwareRenderer.draw(mView, mAttachInfo, yoff);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001266 }
Romain Guy812ccbe2010-06-01 14:07:24 -07001267
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001268 if (scrolling) {
1269 mFullRedrawNeeded = true;
1270 scheduleTraversals();
1271 }
Romain Guy812ccbe2010-06-01 14:07:24 -07001272
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001273 return;
1274 }
1275
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001276 if (DEBUG_ORIENTATION || DEBUG_DRAW) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001277 Log.v(TAG, "Draw " + mView + "/"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001278 + mWindowAttributes.getTitle()
1279 + ": dirty={" + dirty.left + "," + dirty.top
1280 + "," + dirty.right + "," + dirty.bottom + "} surface="
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001281 + surface + " surface.isValid()=" + surface.isValid() + ", appScale:" +
1282 appScale + ", width=" + mWidth + ", height=" + mHeight);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001283 }
1284
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001285 if (!dirty.isEmpty() || mIsAnimating) {
1286 Canvas canvas;
1287 try {
1288 int left = dirty.left;
1289 int top = dirty.top;
1290 int right = dirty.right;
1291 int bottom = dirty.bottom;
1292 canvas = surface.lockCanvas(dirty);
Romain Guy5bcdff42009-05-14 21:27:18 -07001293
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001294 if (left != dirty.left || top != dirty.top || right != dirty.right ||
1295 bottom != dirty.bottom) {
1296 mAttachInfo.mIgnoreDirtyState = true;
1297 }
1298
1299 // TODO: Do this in native
1300 canvas.setDensity(mDensity);
1301 } catch (Surface.OutOfResourcesException e) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001302 Log.e(TAG, "OutOfResourcesException locking surface", e);
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001303 // TODO: we should ask the window manager to do something!
1304 // for now we just do nothing
1305 return;
1306 } catch (IllegalArgumentException e) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001307 Log.e(TAG, "IllegalArgumentException locking surface", e);
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001308 // TODO: we should ask the window manager to do something!
1309 // for now we just do nothing
1310 return;
Romain Guy5bcdff42009-05-14 21:27:18 -07001311 }
1312
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001313 try {
1314 if (!dirty.isEmpty() || mIsAnimating) {
1315 long startTime = 0L;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001316
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001317 if (DEBUG_ORIENTATION || DEBUG_DRAW) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001318 Log.v(TAG, "Surface " + surface + " drawing to bitmap w="
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001319 + canvas.getWidth() + ", h=" + canvas.getHeight());
1320 //canvas.drawARGB(255, 255, 0, 0);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001321 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001322
Romain Guy5429e1d2010-09-07 12:38:00 -07001323 if (ViewDebug.DEBUG_PROFILE_DRAWING) {
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001324 startTime = SystemClock.elapsedRealtime();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001325 }
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001326
1327 // If this bitmap's format includes an alpha channel, we
1328 // need to clear it before drawing so that the child will
1329 // properly re-composite its drawing on a transparent
1330 // background. This automatically respects the clip/dirty region
1331 // or
1332 // If we are applying an offset, we need to clear the area
1333 // where the offset doesn't appear to avoid having garbage
1334 // left in the blank areas.
1335 if (!canvas.isOpaque() || yoff != 0) {
1336 canvas.drawColor(0, PorterDuff.Mode.CLEAR);
1337 }
1338
1339 dirty.setEmpty();
1340 mIsAnimating = false;
1341 mAttachInfo.mDrawingTime = SystemClock.uptimeMillis();
1342 mView.mPrivateFlags |= View.DRAWN;
1343
1344 if (DEBUG_DRAW) {
1345 Context cxt = mView.getContext();
1346 Log.i(TAG, "Drawing: package:" + cxt.getPackageName() +
1347 ", metrics=" + cxt.getResources().getDisplayMetrics() +
1348 ", compatibilityInfo=" + cxt.getResources().getCompatibilityInfo());
1349 }
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001350 try {
1351 canvas.translate(0, -yoff);
1352 if (mTranslator != null) {
1353 mTranslator.translateCanvas(canvas);
1354 }
1355 canvas.setScreenDensity(scalingRequired
1356 ? DisplayMetrics.DENSITY_DEVICE : 0);
1357 mView.draw(canvas);
1358 } finally {
1359 mAttachInfo.mIgnoreDirtyState = false;
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001360 }
1361
1362 if (Config.DEBUG && ViewDebug.consistencyCheckEnabled) {
1363 mView.dispatchConsistencyCheck(ViewDebug.CONSISTENCY_DRAWING);
1364 }
1365
Romain Guy5429e1d2010-09-07 12:38:00 -07001366 if (SHOW_FPS || ViewDebug.DEBUG_SHOW_FPS) {
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001367 int now = (int)SystemClock.elapsedRealtime();
1368 if (sDrawTime != 0) {
1369 nativeShowFPS(canvas, now - sDrawTime);
1370 }
1371 sDrawTime = now;
1372 }
1373
Romain Guy5429e1d2010-09-07 12:38:00 -07001374 if (ViewDebug.DEBUG_PROFILE_DRAWING) {
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001375 EventLog.writeEvent(60000, SystemClock.elapsedRealtime() - startTime);
1376 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001377 }
1378
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001379 } finally {
1380 surface.unlockCanvasAndPost(canvas);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001381 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001382 }
1383
1384 if (LOCAL_LOGV) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001385 Log.v(TAG, "Surface " + surface + " unlockCanvasAndPost");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001386 }
Romain Guy8506ab42009-06-11 17:35:47 -07001387
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001388 if (scrolling) {
1389 mFullRedrawNeeded = true;
1390 scheduleTraversals();
1391 }
1392 }
1393
1394 boolean scrollToRectOrFocus(Rect rectangle, boolean immediate) {
1395 final View.AttachInfo attachInfo = mAttachInfo;
1396 final Rect ci = attachInfo.mContentInsets;
1397 final Rect vi = attachInfo.mVisibleInsets;
1398 int scrollY = 0;
1399 boolean handled = false;
Romain Guy8506ab42009-06-11 17:35:47 -07001400
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001401 if (vi.left > ci.left || vi.top > ci.top
1402 || vi.right > ci.right || vi.bottom > ci.bottom) {
1403 // We'll assume that we aren't going to change the scroll
1404 // offset, since we want to avoid that unless it is actually
1405 // going to make the focus visible... otherwise we scroll
1406 // all over the place.
1407 scrollY = mScrollY;
1408 // We can be called for two different situations: during a draw,
1409 // to update the scroll position if the focus has changed (in which
1410 // case 'rectangle' is null), or in response to a
1411 // requestChildRectangleOnScreen() call (in which case 'rectangle'
1412 // is non-null and we just want to scroll to whatever that
1413 // rectangle is).
1414 View focus = mRealFocusedView;
Romain Guye8b16522009-07-14 13:06:42 -07001415
1416 // When in touch mode, focus points to the previously focused view,
1417 // which may have been removed from the view hierarchy. The following
Joe Onoratob71193b2009-11-24 18:34:42 -05001418 // line checks whether the view is still in our hierarchy.
1419 if (focus == null || focus.mAttachInfo != mAttachInfo) {
Romain Guye8b16522009-07-14 13:06:42 -07001420 mRealFocusedView = null;
1421 return false;
1422 }
1423
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001424 if (focus != mLastScrolledFocus) {
1425 // If the focus has changed, then ignore any requests to scroll
1426 // to a rectangle; first we want to make sure the entire focus
1427 // view is visible.
1428 rectangle = null;
1429 }
1430 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Eval scroll: focus=" + focus
1431 + " rectangle=" + rectangle + " ci=" + ci
1432 + " vi=" + vi);
1433 if (focus == mLastScrolledFocus && !mScrollMayChange
1434 && rectangle == null) {
1435 // Optimization: if the focus hasn't changed since last
1436 // time, and no layout has happened, then just leave things
1437 // as they are.
1438 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Keeping scroll y="
1439 + mScrollY + " vi=" + vi.toShortString());
1440 } else if (focus != null) {
1441 // We need to determine if the currently focused view is
1442 // within the visible part of the window and, if not, apply
1443 // a pan so it can be seen.
1444 mLastScrolledFocus = focus;
1445 mScrollMayChange = false;
1446 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Need to scroll?");
1447 // Try to find the rectangle from the focus view.
1448 if (focus.getGlobalVisibleRect(mVisRect, null)) {
1449 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Root w="
1450 + mView.getWidth() + " h=" + mView.getHeight()
1451 + " ci=" + ci.toShortString()
1452 + " vi=" + vi.toShortString());
1453 if (rectangle == null) {
1454 focus.getFocusedRect(mTempRect);
1455 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Focus " + focus
1456 + ": focusRect=" + mTempRect.toShortString());
Dianne Hackborn1c6a8942010-03-23 16:34:20 -07001457 if (mView instanceof ViewGroup) {
1458 ((ViewGroup) mView).offsetDescendantRectToMyCoords(
1459 focus, mTempRect);
1460 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001461 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1462 "Focus in window: focusRect="
1463 + mTempRect.toShortString()
1464 + " visRect=" + mVisRect.toShortString());
1465 } else {
1466 mTempRect.set(rectangle);
1467 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1468 "Request scroll to rect: "
1469 + mTempRect.toShortString()
1470 + " visRect=" + mVisRect.toShortString());
1471 }
1472 if (mTempRect.intersect(mVisRect)) {
1473 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1474 "Focus window visible rect: "
1475 + mTempRect.toShortString());
1476 if (mTempRect.height() >
1477 (mView.getHeight()-vi.top-vi.bottom)) {
1478 // If the focus simply is not going to fit, then
1479 // best is probably just to leave things as-is.
1480 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1481 "Too tall; leaving scrollY=" + scrollY);
1482 } else if ((mTempRect.top-scrollY) < vi.top) {
1483 scrollY -= vi.top - (mTempRect.top-scrollY);
1484 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1485 "Top covered; scrollY=" + scrollY);
1486 } else if ((mTempRect.bottom-scrollY)
1487 > (mView.getHeight()-vi.bottom)) {
1488 scrollY += (mTempRect.bottom-scrollY)
1489 - (mView.getHeight()-vi.bottom);
1490 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1491 "Bottom covered; scrollY=" + scrollY);
1492 }
1493 handled = true;
1494 }
1495 }
1496 }
1497 }
Romain Guy8506ab42009-06-11 17:35:47 -07001498
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001499 if (scrollY != mScrollY) {
1500 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Pan scroll changed: old="
1501 + mScrollY + " , new=" + scrollY);
1502 if (!immediate) {
1503 if (mScroller == null) {
1504 mScroller = new Scroller(mView.getContext());
1505 }
1506 mScroller.startScroll(0, mScrollY, 0, scrollY-mScrollY);
1507 } else if (mScroller != null) {
1508 mScroller.abortAnimation();
1509 }
1510 mScrollY = scrollY;
1511 }
Romain Guy8506ab42009-06-11 17:35:47 -07001512
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001513 return handled;
1514 }
Romain Guy8506ab42009-06-11 17:35:47 -07001515
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001516 public void requestChildFocus(View child, View focused) {
1517 checkThread();
1518 if (mFocusedView != focused) {
1519 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(mFocusedView, focused);
1520 scheduleTraversals();
1521 }
1522 mFocusedView = mRealFocusedView = focused;
1523 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Request child focus: focus now "
1524 + mFocusedView);
1525 }
1526
1527 public void clearChildFocus(View child) {
1528 checkThread();
1529
1530 View oldFocus = mFocusedView;
1531
1532 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Clearing child focus");
1533 mFocusedView = mRealFocusedView = null;
1534 if (mView != null && !mView.hasFocus()) {
1535 // If a view gets the focus, the listener will be invoked from requestChildFocus()
1536 if (!mView.requestFocus(View.FOCUS_FORWARD)) {
1537 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
1538 }
1539 } else if (oldFocus != null) {
1540 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
1541 }
1542 }
1543
1544
1545 public void focusableViewAvailable(View v) {
1546 checkThread();
1547
1548 if (mView != null && !mView.hasFocus()) {
1549 v.requestFocus();
1550 } else {
1551 // the one case where will transfer focus away from the current one
1552 // is if the current view is a view group that prefers to give focus
1553 // to its children first AND the view is a descendant of it.
1554 mFocusedView = mView.findFocus();
1555 boolean descendantsHaveDibsOnFocus =
1556 (mFocusedView instanceof ViewGroup) &&
1557 (((ViewGroup) mFocusedView).getDescendantFocusability() ==
1558 ViewGroup.FOCUS_AFTER_DESCENDANTS);
1559 if (descendantsHaveDibsOnFocus && isViewDescendantOf(v, mFocusedView)) {
1560 // If a view gets the focus, the listener will be invoked from requestChildFocus()
1561 v.requestFocus();
1562 }
1563 }
1564 }
1565
1566 public void recomputeViewAttributes(View child) {
1567 checkThread();
1568 if (mView == child) {
1569 mAttachInfo.mRecomputeGlobalAttributes = true;
1570 if (!mWillDrawSoon) {
1571 scheduleTraversals();
1572 }
1573 }
1574 }
1575
1576 void dispatchDetachedFromWindow() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001577 if (mView != null) {
1578 mView.dispatchDetachedFromWindow();
1579 }
1580
1581 mView = null;
1582 mAttachInfo.mRootView = null;
Mathias Agopian5583dc62009-07-09 16:28:11 -07001583 mAttachInfo.mSurface = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001584
Romain Guy29d89972010-09-22 16:10:57 -07001585 destroyHardwareRenderer();
Romain Guy4caa4ed2010-08-25 14:46:24 -07001586
Dianne Hackborn0586a1b2009-09-06 21:08:27 -07001587 mSurface.release();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001588
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001589 if (mInputChannel != null) {
1590 if (mInputQueueCallback != null) {
1591 mInputQueueCallback.onInputQueueDestroyed(mInputQueue);
1592 mInputQueueCallback = null;
1593 } else {
1594 InputQueue.unregisterInputChannel(mInputChannel);
Jeff Brown46b9ac02010-04-22 18:58:52 -07001595 }
1596 }
1597
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001598 try {
1599 sWindowSession.remove(mWindow);
1600 } catch (RemoteException e) {
1601 }
Jeff Brown349703e2010-06-22 01:27:15 -07001602
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001603 // Dispose the input channel after removing the window so the Window Manager
1604 // doesn't interpret the input channel being closed as an abnormal termination.
1605 if (mInputChannel != null) {
1606 mInputChannel.dispose();
1607 mInputChannel = null;
Jeff Brown349703e2010-06-22 01:27:15 -07001608 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001609 }
Romain Guy8506ab42009-06-11 17:35:47 -07001610
Dianne Hackborn694f79b2010-03-17 19:44:59 -07001611 void updateConfiguration(Configuration config, boolean force) {
1612 if (DEBUG_CONFIGURATION) Log.v(TAG,
1613 "Applying new config to window "
1614 + mWindowAttributes.getTitle()
1615 + ": " + config);
1616 synchronized (sConfigCallbacks) {
1617 for (int i=sConfigCallbacks.size()-1; i>=0; i--) {
1618 sConfigCallbacks.get(i).onConfigurationChanged(config);
1619 }
1620 }
1621 if (mView != null) {
1622 // At this point the resources have been updated to
1623 // have the most recent config, whatever that is. Use
1624 // the on in them which may be newer.
1625 if (mView != null) {
1626 config = mView.getResources().getConfiguration();
1627 }
1628 if (force || mLastConfiguration.diff(config) != 0) {
1629 mLastConfiguration.setTo(config);
1630 mView.dispatchConfigurationChanged(config);
1631 }
1632 }
1633 }
1634
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001635 /**
1636 * Return true if child is an ancestor of parent, (or equal to the parent).
1637 */
1638 private static boolean isViewDescendantOf(View child, View parent) {
1639 if (child == parent) {
1640 return true;
1641 }
1642
1643 final ViewParent theParent = child.getParent();
1644 return (theParent instanceof ViewGroup) && isViewDescendantOf((View) theParent, parent);
1645 }
1646
Romain Guycdb86672010-03-18 18:54:50 -07001647 private static void forceLayout(View view) {
1648 view.forceLayout();
1649 if (view instanceof ViewGroup) {
1650 ViewGroup group = (ViewGroup) view;
1651 final int count = group.getChildCount();
1652 for (int i = 0; i < count; i++) {
1653 forceLayout(group.getChildAt(i));
1654 }
1655 }
1656 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001657
1658 public final static int DO_TRAVERSAL = 1000;
1659 public final static int DIE = 1001;
1660 public final static int RESIZED = 1002;
1661 public final static int RESIZED_REPORT = 1003;
1662 public final static int WINDOW_FOCUS_CHANGED = 1004;
1663 public final static int DISPATCH_KEY = 1005;
1664 public final static int DISPATCH_POINTER = 1006;
1665 public final static int DISPATCH_TRACKBALL = 1007;
1666 public final static int DISPATCH_APP_VISIBILITY = 1008;
1667 public final static int DISPATCH_GET_NEW_SURFACE = 1009;
1668 public final static int FINISHED_EVENT = 1010;
1669 public final static int DISPATCH_KEY_FROM_IME = 1011;
1670 public final static int FINISH_INPUT_CONNECTION = 1012;
1671 public final static int CHECK_FOCUS = 1013;
Dianne Hackbornffa42482009-09-23 22:20:11 -07001672 public final static int CLOSE_SYSTEM_DIALOGS = 1014;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001673
1674 @Override
1675 public void handleMessage(Message msg) {
1676 switch (msg.what) {
1677 case View.AttachInfo.INVALIDATE_MSG:
1678 ((View) msg.obj).invalidate();
1679 break;
1680 case View.AttachInfo.INVALIDATE_RECT_MSG:
1681 final View.AttachInfo.InvalidateInfo info = (View.AttachInfo.InvalidateInfo) msg.obj;
1682 info.target.invalidate(info.left, info.top, info.right, info.bottom);
1683 info.release();
1684 break;
1685 case DO_TRAVERSAL:
1686 if (mProfile) {
1687 Debug.startMethodTracing("ViewRoot");
1688 }
1689
1690 performTraversals();
1691
1692 if (mProfile) {
1693 Debug.stopMethodTracing();
1694 mProfile = false;
1695 }
1696 break;
1697 case FINISHED_EVENT:
1698 handleFinishedEvent(msg.arg1, msg.arg2 != 0);
1699 break;
1700 case DISPATCH_KEY:
1701 if (LOCAL_LOGV) Log.v(
Jeff Brownc5ed5912010-07-14 18:48:53 -07001702 TAG, "Dispatching key "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001703 + msg.obj + " to " + mView);
Jeff Brown92ff1dd2010-08-11 16:16:06 -07001704 deliverKeyEvent((KeyEvent)msg.obj, msg.arg1 != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001705 break;
The Android Open Source Project10592532009-03-18 17:39:46 -07001706 case DISPATCH_POINTER: {
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001707 MotionEvent event = (MotionEvent) msg.obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001708 try {
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001709 deliverPointerEvent(event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001710 } finally {
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001711 event.recycle();
Jeff Brown93ed4e32010-09-23 13:51:48 -07001712 if (msg.arg1 != 0) {
1713 finishInputEvent();
1714 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001715 if (LOCAL_LOGV || WATCH_POINTER) Log.i(TAG, "Done dispatching!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001716 }
The Android Open Source Project10592532009-03-18 17:39:46 -07001717 } break;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001718 case DISPATCH_TRACKBALL: {
1719 MotionEvent event = (MotionEvent) msg.obj;
1720 try {
1721 deliverTrackballEvent(event);
1722 } finally {
1723 event.recycle();
Jeff Brown93ed4e32010-09-23 13:51:48 -07001724 if (msg.arg1 != 0) {
1725 finishInputEvent();
1726 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001727 }
1728 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001729 case DISPATCH_APP_VISIBILITY:
1730 handleAppVisibility(msg.arg1 != 0);
1731 break;
1732 case DISPATCH_GET_NEW_SURFACE:
1733 handleGetNewSurface();
1734 break;
1735 case RESIZED:
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001736 ResizedInfo ri = (ResizedInfo)msg.obj;
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001737
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001738 if (mWinFrame.width() == msg.arg1 && mWinFrame.height() == msg.arg2
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001739 && mPendingContentInsets.equals(ri.coveredInsets)
Dianne Hackbornd49258f2010-03-26 00:44:29 -07001740 && mPendingVisibleInsets.equals(ri.visibleInsets)
1741 && ((ResizedInfo)msg.obj).newConfig == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001742 break;
1743 }
1744 // fall through...
1745 case RESIZED_REPORT:
1746 if (mAdded) {
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001747 Configuration config = ((ResizedInfo)msg.obj).newConfig;
1748 if (config != null) {
Dianne Hackborn694f79b2010-03-17 19:44:59 -07001749 updateConfiguration(config, false);
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001750 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001751 mWinFrame.left = 0;
1752 mWinFrame.right = msg.arg1;
1753 mWinFrame.top = 0;
1754 mWinFrame.bottom = msg.arg2;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001755 mPendingContentInsets.set(((ResizedInfo)msg.obj).coveredInsets);
1756 mPendingVisibleInsets.set(((ResizedInfo)msg.obj).visibleInsets);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001757 if (msg.what == RESIZED_REPORT) {
1758 mReportNextDraw = true;
1759 }
Romain Guycdb86672010-03-18 18:54:50 -07001760
1761 if (mView != null) {
1762 forceLayout(mView);
1763 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001764 requestLayout();
1765 }
1766 break;
1767 case WINDOW_FOCUS_CHANGED: {
1768 if (mAdded) {
1769 boolean hasWindowFocus = msg.arg1 != 0;
1770 mAttachInfo.mHasWindowFocus = hasWindowFocus;
1771 if (hasWindowFocus) {
1772 boolean inTouchMode = msg.arg2 != 0;
Romain Guy2d4cff62010-04-09 15:39:00 -07001773 ensureTouchModeLocally(inTouchMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001774
Romain Guyb051e892010-09-28 19:09:36 -07001775 if (mAttachInfo.mHardwareRenderer != null) {
1776 mAttachInfo.mHardwareRenderer.initializeIfNeeded(mWidth, mHeight,
1777 mAttachInfo, mHolder);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001778 }
1779 }
Romain Guy8506ab42009-06-11 17:35:47 -07001780
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001781 mLastWasImTarget = WindowManager.LayoutParams
1782 .mayUseInputMethod(mWindowAttributes.flags);
Romain Guy8506ab42009-06-11 17:35:47 -07001783
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001784 InputMethodManager imm = InputMethodManager.peekInstance();
1785 if (mView != null) {
1786 if (hasWindowFocus && imm != null && mLastWasImTarget) {
1787 imm.startGettingWindowFocus(mView);
1788 }
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07001789 mAttachInfo.mKeyDispatchState.reset();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001790 mView.dispatchWindowFocusChanged(hasWindowFocus);
1791 }
svetoslavganov75986cf2009-05-14 22:28:01 -07001792
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001793 // Note: must be done after the focus change callbacks,
1794 // so all of the view state is set up correctly.
1795 if (hasWindowFocus) {
1796 if (imm != null && mLastWasImTarget) {
1797 imm.onWindowFocus(mView, mView.findFocus(),
1798 mWindowAttributes.softInputMode,
1799 !mHasHadWindowFocus, mWindowAttributes.flags);
1800 }
1801 // Clear the forward bit. We can just do this directly, since
1802 // the window manager doesn't care about it.
1803 mWindowAttributes.softInputMode &=
1804 ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
1805 ((WindowManager.LayoutParams)mView.getLayoutParams())
1806 .softInputMode &=
1807 ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
1808 mHasHadWindowFocus = true;
1809 }
svetoslavganov75986cf2009-05-14 22:28:01 -07001810
1811 if (hasWindowFocus && mView != null) {
1812 sendAccessibilityEvents();
1813 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001814 }
1815 } break;
1816 case DIE:
Dianne Hackborn94d69142009-09-28 22:14:42 -07001817 doDie();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001818 break;
The Android Open Source Project10592532009-03-18 17:39:46 -07001819 case DISPATCH_KEY_FROM_IME: {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001820 if (LOCAL_LOGV) Log.v(
Jeff Brownc5ed5912010-07-14 18:48:53 -07001821 TAG, "Dispatching key "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001822 + msg.obj + " from IME to " + mView);
The Android Open Source Project10592532009-03-18 17:39:46 -07001823 KeyEvent event = (KeyEvent)msg.obj;
1824 if ((event.getFlags()&KeyEvent.FLAG_FROM_SYSTEM) != 0) {
1825 // The IME is trying to say this event is from the
1826 // system! Bad bad bad!
Romain Guy812ccbe2010-06-01 14:07:24 -07001827 event = KeyEvent.changeFlags(event, event.getFlags() & ~KeyEvent.FLAG_FROM_SYSTEM);
The Android Open Source Project10592532009-03-18 17:39:46 -07001828 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001829 deliverKeyEventToViewHierarchy((KeyEvent)msg.obj, false);
The Android Open Source Project10592532009-03-18 17:39:46 -07001830 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001831 case FINISH_INPUT_CONNECTION: {
1832 InputMethodManager imm = InputMethodManager.peekInstance();
1833 if (imm != null) {
1834 imm.reportFinishInputConnection((InputConnection)msg.obj);
1835 }
1836 } break;
1837 case CHECK_FOCUS: {
1838 InputMethodManager imm = InputMethodManager.peekInstance();
1839 if (imm != null) {
1840 imm.checkFocus();
1841 }
1842 } break;
Dianne Hackbornffa42482009-09-23 22:20:11 -07001843 case CLOSE_SYSTEM_DIALOGS: {
1844 if (mView != null) {
1845 mView.onCloseSystemDialogs((String)msg.obj);
1846 }
1847 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001848 }
1849 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07001850
Jeff Brown93ed4e32010-09-23 13:51:48 -07001851 private void startInputEvent(Runnable finishedCallback) {
1852 if (mFinishedCallback != null) {
1853 Slog.w(TAG, "Received a new input event from the input queue but there is "
1854 + "already an unfinished input event in progress.");
1855 }
1856
1857 mFinishedCallback = finishedCallback;
1858 }
1859
1860 private void finishInputEvent() {
1861 if (LOCAL_LOGV) Log.v(TAG, "Telling window manager input event is finished");
Jeff Brown92ff1dd2010-08-11 16:16:06 -07001862
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001863 if (mFinishedCallback != null) {
1864 mFinishedCallback.run();
1865 mFinishedCallback = null;
Jeff Brown92ff1dd2010-08-11 16:16:06 -07001866 } else {
Jeff Brown93ed4e32010-09-23 13:51:48 -07001867 Slog.w(TAG, "Attempted to tell the input queue that the current input event "
1868 + "is finished but there is no input event actually in progress.");
Jeff Brown46b9ac02010-04-22 18:58:52 -07001869 }
1870 }
1871
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001872 /**
1873 * Something in the current window tells us we need to change the touch mode. For
1874 * example, we are not in touch mode, and the user touches the screen.
1875 *
1876 * If the touch mode has changed, tell the window manager, and handle it locally.
1877 *
1878 * @param inTouchMode Whether we want to be in touch mode.
1879 * @return True if the touch mode changed and focus changed was changed as a result
1880 */
1881 boolean ensureTouchMode(boolean inTouchMode) {
1882 if (DBG) Log.d("touchmode", "ensureTouchMode(" + inTouchMode + "), current "
1883 + "touch mode is " + mAttachInfo.mInTouchMode);
1884 if (mAttachInfo.mInTouchMode == inTouchMode) return false;
1885
1886 // tell the window manager
1887 try {
1888 sWindowSession.setInTouchMode(inTouchMode);
1889 } catch (RemoteException e) {
1890 throw new RuntimeException(e);
1891 }
1892
1893 // handle the change
Romain Guy2d4cff62010-04-09 15:39:00 -07001894 return ensureTouchModeLocally(inTouchMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001895 }
1896
1897 /**
1898 * Ensure that the touch mode for this window is set, and if it is changing,
1899 * take the appropriate action.
1900 * @param inTouchMode Whether we want to be in touch mode.
1901 * @return True if the touch mode changed and focus changed was changed as a result
1902 */
Romain Guy2d4cff62010-04-09 15:39:00 -07001903 private boolean ensureTouchModeLocally(boolean inTouchMode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001904 if (DBG) Log.d("touchmode", "ensureTouchModeLocally(" + inTouchMode + "), current "
1905 + "touch mode is " + mAttachInfo.mInTouchMode);
1906
1907 if (mAttachInfo.mInTouchMode == inTouchMode) return false;
1908
1909 mAttachInfo.mInTouchMode = inTouchMode;
1910 mAttachInfo.mTreeObserver.dispatchOnTouchModeChanged(inTouchMode);
1911
Romain Guy2d4cff62010-04-09 15:39:00 -07001912 return (inTouchMode) ? enterTouchMode() : leaveTouchMode();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001913 }
1914
1915 private boolean enterTouchMode() {
1916 if (mView != null) {
1917 if (mView.hasFocus()) {
1918 // note: not relying on mFocusedView here because this could
1919 // be when the window is first being added, and mFocused isn't
1920 // set yet.
1921 final View focused = mView.findFocus();
1922 if (focused != null && !focused.isFocusableInTouchMode()) {
1923
1924 final ViewGroup ancestorToTakeFocus =
1925 findAncestorToTakeFocusInTouchMode(focused);
1926 if (ancestorToTakeFocus != null) {
1927 // there is an ancestor that wants focus after its descendants that
1928 // is focusable in touch mode.. give it focus
1929 return ancestorToTakeFocus.requestFocus();
1930 } else {
1931 // nothing appropriate to have focus in touch mode, clear it out
1932 mView.unFocus();
1933 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(focused, null);
1934 mFocusedView = null;
1935 return true;
1936 }
1937 }
1938 }
1939 }
1940 return false;
1941 }
1942
1943
1944 /**
1945 * Find an ancestor of focused that wants focus after its descendants and is
1946 * focusable in touch mode.
1947 * @param focused The currently focused view.
1948 * @return An appropriate view, or null if no such view exists.
1949 */
1950 private ViewGroup findAncestorToTakeFocusInTouchMode(View focused) {
1951 ViewParent parent = focused.getParent();
1952 while (parent instanceof ViewGroup) {
1953 final ViewGroup vgParent = (ViewGroup) parent;
1954 if (vgParent.getDescendantFocusability() == ViewGroup.FOCUS_AFTER_DESCENDANTS
1955 && vgParent.isFocusableInTouchMode()) {
1956 return vgParent;
1957 }
1958 if (vgParent.isRootNamespace()) {
1959 return null;
1960 } else {
1961 parent = vgParent.getParent();
1962 }
1963 }
1964 return null;
1965 }
1966
1967 private boolean leaveTouchMode() {
1968 if (mView != null) {
1969 if (mView.hasFocus()) {
1970 // i learned the hard way to not trust mFocusedView :)
1971 mFocusedView = mView.findFocus();
1972 if (!(mFocusedView instanceof ViewGroup)) {
1973 // some view has focus, let it keep it
1974 return false;
1975 } else if (((ViewGroup)mFocusedView).getDescendantFocusability() !=
1976 ViewGroup.FOCUS_AFTER_DESCENDANTS) {
1977 // some view group has focus, and doesn't prefer its children
1978 // over itself for focus, so let them keep it.
1979 return false;
1980 }
1981 }
1982
1983 // find the best view to give focus to in this brave new non-touch-mode
1984 // world
1985 final View focused = focusSearch(null, View.FOCUS_DOWN);
1986 if (focused != null) {
1987 return focused.requestFocus(View.FOCUS_DOWN);
1988 }
1989 }
1990 return false;
1991 }
1992
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001993 private void deliverPointerEvent(MotionEvent event) {
1994 if (mTranslator != null) {
1995 mTranslator.translateEventInScreenToAppWindow(event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001996 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001997
1998 boolean handled;
1999 if (mView != null && mAdded) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002000
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002001 // enter touch mode on the down
2002 boolean isDown = event.getAction() == MotionEvent.ACTION_DOWN;
2003 if (isDown) {
2004 ensureTouchMode(true);
2005 }
2006 if(Config.LOGV) {
2007 captureMotionLog("captureDispatchPointer", event);
2008 }
2009 if (mCurScrollY != 0) {
2010 event.offsetLocation(0, mCurScrollY);
2011 }
2012 if (MEASURE_LATENCY) {
2013 lt.sample("A Dispatching TouchEvents", System.nanoTime() - event.getEventTimeNano());
2014 }
2015 handled = mView.dispatchTouchEvent(event);
2016 if (MEASURE_LATENCY) {
2017 lt.sample("B Dispatched TouchEvents ", System.nanoTime() - event.getEventTimeNano());
2018 }
2019 if (!handled && isDown) {
2020 int edgeSlop = mViewConfiguration.getScaledEdgeSlop();
2021
2022 final int edgeFlags = event.getEdgeFlags();
2023 int direction = View.FOCUS_UP;
2024 int x = (int)event.getX();
2025 int y = (int)event.getY();
2026 final int[] deltas = new int[2];
2027
2028 if ((edgeFlags & MotionEvent.EDGE_TOP) != 0) {
2029 direction = View.FOCUS_DOWN;
2030 if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
2031 deltas[0] = edgeSlop;
2032 x += edgeSlop;
2033 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
2034 deltas[0] = -edgeSlop;
2035 x -= edgeSlop;
2036 }
2037 } else if ((edgeFlags & MotionEvent.EDGE_BOTTOM) != 0) {
2038 direction = View.FOCUS_UP;
2039 if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
2040 deltas[0] = edgeSlop;
2041 x += edgeSlop;
2042 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
2043 deltas[0] = -edgeSlop;
2044 x -= edgeSlop;
2045 }
2046 } else if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
2047 direction = View.FOCUS_RIGHT;
2048 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
2049 direction = View.FOCUS_LEFT;
2050 }
2051
2052 if (edgeFlags != 0 && mView instanceof ViewGroup) {
2053 View nearest = FocusFinder.getInstance().findNearestTouchable(
2054 ((ViewGroup) mView), x, y, direction, deltas);
2055 if (nearest != null) {
2056 event.offsetLocation(deltas[0], deltas[1]);
2057 event.setEdgeFlags(0);
2058 mView.dispatchTouchEvent(event);
2059 }
2060 }
2061 }
2062 }
2063 }
2064
2065 private void deliverTrackballEvent(MotionEvent event) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002066 if (DEBUG_TRACKBALL) Log.v(TAG, "Motion event:" + event);
2067
2068 boolean handled = false;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002069 if (mView != null && mAdded) {
2070 handled = mView.dispatchTrackballEvent(event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002071 if (handled) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002072 // If we reach this, we delivered a trackball event to mView and
2073 // mView consumed it. Because we will not translate the trackball
2074 // event into a key event, touch mode will not exit, so we exit
2075 // touch mode here.
2076 ensureTouchMode(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002077 return;
2078 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002079
2080 // Otherwise we could do something here, like changing the focus
2081 // or something?
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002082 }
2083
2084 final TrackballAxis x = mTrackballAxisX;
2085 final TrackballAxis y = mTrackballAxisY;
2086
2087 long curTime = SystemClock.uptimeMillis();
2088 if ((mLastTrackballTime+MAX_TRACKBALL_DELAY) < curTime) {
2089 // It has been too long since the last movement,
2090 // so restart at the beginning.
2091 x.reset(0);
2092 y.reset(0);
2093 mLastTrackballTime = curTime;
2094 }
2095
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002096 final int action = event.getAction();
2097 final int metastate = event.getMetaState();
2098 switch (action) {
2099 case MotionEvent.ACTION_DOWN:
2100 x.reset(2);
2101 y.reset(2);
2102 deliverKeyEvent(new KeyEvent(curTime, curTime,
2103 KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_CENTER,
2104 0, metastate), false);
2105 break;
2106 case MotionEvent.ACTION_UP:
2107 x.reset(2);
2108 y.reset(2);
2109 deliverKeyEvent(new KeyEvent(curTime, curTime,
2110 KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_CENTER,
2111 0, metastate), false);
2112 break;
2113 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002114
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002115 if (DEBUG_TRACKBALL) Log.v(TAG, "TB X=" + x.position + " step="
2116 + x.step + " dir=" + x.dir + " acc=" + x.acceleration
2117 + " move=" + event.getX()
2118 + " / Y=" + y.position + " step="
2119 + y.step + " dir=" + y.dir + " acc=" + y.acceleration
2120 + " move=" + event.getY());
2121 final float xOff = x.collect(event.getX(), event.getEventTime(), "X");
2122 final float yOff = y.collect(event.getY(), event.getEventTime(), "Y");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002123
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002124 // Generate DPAD events based on the trackball movement.
2125 // We pick the axis that has moved the most as the direction of
2126 // the DPAD. When we generate DPAD events for one axis, then the
2127 // other axis is reset -- we don't want to perform DPAD jumps due
2128 // to slight movements in the trackball when making major movements
2129 // along the other axis.
2130 int keycode = 0;
2131 int movement = 0;
2132 float accel = 1;
2133 if (xOff > yOff) {
2134 movement = x.generate((2/event.getXPrecision()));
2135 if (movement != 0) {
2136 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_RIGHT
2137 : KeyEvent.KEYCODE_DPAD_LEFT;
2138 accel = x.acceleration;
2139 y.reset(2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002140 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002141 } else if (yOff > 0) {
2142 movement = y.generate((2/event.getYPrecision()));
2143 if (movement != 0) {
2144 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_DOWN
2145 : KeyEvent.KEYCODE_DPAD_UP;
2146 accel = y.acceleration;
2147 x.reset(2);
2148 }
2149 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002150
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002151 if (keycode != 0) {
2152 if (movement < 0) movement = -movement;
2153 int accelMovement = (int)(movement * accel);
2154 if (DEBUG_TRACKBALL) Log.v(TAG, "Move: movement=" + movement
2155 + " accelMovement=" + accelMovement
2156 + " accel=" + accel);
2157 if (accelMovement > movement) {
2158 if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: "
2159 + keycode);
2160 movement--;
2161 deliverKeyEvent(new KeyEvent(curTime, curTime,
2162 KeyEvent.ACTION_MULTIPLE, keycode,
2163 accelMovement-movement, metastate), false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002164 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002165 while (movement > 0) {
2166 if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: "
2167 + keycode);
2168 movement--;
2169 curTime = SystemClock.uptimeMillis();
2170 deliverKeyEvent(new KeyEvent(curTime, curTime,
2171 KeyEvent.ACTION_DOWN, keycode, 0, event.getMetaState()), false);
2172 deliverKeyEvent(new KeyEvent(curTime, curTime,
2173 KeyEvent.ACTION_UP, keycode, 0, metastate), false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002174 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002175 mLastTrackballTime = curTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002176 }
2177 }
2178
2179 /**
2180 * @param keyCode The key code
2181 * @return True if the key is directional.
2182 */
2183 static boolean isDirectional(int keyCode) {
2184 switch (keyCode) {
2185 case KeyEvent.KEYCODE_DPAD_LEFT:
2186 case KeyEvent.KEYCODE_DPAD_RIGHT:
2187 case KeyEvent.KEYCODE_DPAD_UP:
2188 case KeyEvent.KEYCODE_DPAD_DOWN:
2189 return true;
2190 }
2191 return false;
2192 }
2193
2194 /**
2195 * Returns true if this key is a keyboard key.
2196 * @param keyEvent The key event.
2197 * @return whether this key is a keyboard key.
2198 */
2199 private static boolean isKeyboardKey(KeyEvent keyEvent) {
2200 final int convertedKey = keyEvent.getUnicodeChar();
2201 return convertedKey > 0;
2202 }
2203
2204
2205
2206 /**
2207 * See if the key event means we should leave touch mode (and leave touch
2208 * mode if so).
2209 * @param event The key event.
2210 * @return Whether this key event should be consumed (meaning the act of
2211 * leaving touch mode alone is considered the event).
2212 */
2213 private boolean checkForLeavingTouchModeAndConsume(KeyEvent event) {
Adam Powell51a6bee2010-03-15 14:07:28 -07002214 final int action = event.getAction();
2215 if (action != KeyEvent.ACTION_DOWN && action != KeyEvent.ACTION_MULTIPLE) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002216 return false;
2217 }
2218 if ((event.getFlags()&KeyEvent.FLAG_KEEP_TOUCH_MODE) != 0) {
2219 return false;
2220 }
2221
2222 // only relevant if we are in touch mode
2223 if (!mAttachInfo.mInTouchMode) {
2224 return false;
2225 }
2226
2227 // if something like an edit text has focus and the user is typing,
2228 // leave touch mode
2229 //
2230 // note: the condition of not being a keyboard key is kind of a hacky
2231 // approximation of whether we think the focused view will want the
2232 // key; if we knew for sure whether the focused view would consume
2233 // the event, that would be better.
2234 if (isKeyboardKey(event) && mView != null && mView.hasFocus()) {
2235 mFocusedView = mView.findFocus();
2236 if ((mFocusedView instanceof ViewGroup)
2237 && ((ViewGroup) mFocusedView).getDescendantFocusability() ==
2238 ViewGroup.FOCUS_AFTER_DESCENDANTS) {
2239 // something has focus, but is holding it weakly as a container
2240 return false;
2241 }
2242 if (ensureTouchMode(false)) {
2243 throw new IllegalStateException("should not have changed focus "
2244 + "when leaving touch mode while a view has focus.");
2245 }
2246 return false;
2247 }
2248
2249 if (isDirectional(event.getKeyCode())) {
2250 // no view has focus, so we leave touch mode (and find something
2251 // to give focus to). the event is consumed if we were able to
2252 // find something to give focus to.
2253 return ensureTouchMode(false);
2254 }
2255 return false;
2256 }
2257
2258 /**
Romain Guy8506ab42009-06-11 17:35:47 -07002259 * log motion events
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002260 */
2261 private static void captureMotionLog(String subTag, MotionEvent ev) {
Romain Guy8506ab42009-06-11 17:35:47 -07002262 //check dynamic switch
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002263 if (ev == null ||
2264 SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_EVENT, 0) == 0) {
2265 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002266 }
Romain Guy8506ab42009-06-11 17:35:47 -07002267
2268 StringBuilder sb = new StringBuilder(subTag + ": ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002269 sb.append(ev.getDownTime()).append(',');
2270 sb.append(ev.getEventTime()).append(',');
2271 sb.append(ev.getAction()).append(',');
Romain Guy8506ab42009-06-11 17:35:47 -07002272 sb.append(ev.getX()).append(',');
2273 sb.append(ev.getY()).append(',');
2274 sb.append(ev.getPressure()).append(',');
2275 sb.append(ev.getSize()).append(',');
2276 sb.append(ev.getMetaState()).append(',');
2277 sb.append(ev.getXPrecision()).append(',');
2278 sb.append(ev.getYPrecision()).append(',');
2279 sb.append(ev.getDeviceId()).append(',');
2280 sb.append(ev.getEdgeFlags());
2281 Log.d(TAG, sb.toString());
2282 }
2283 /**
2284 * log motion events
2285 */
2286 private static void captureKeyLog(String subTag, KeyEvent ev) {
2287 //check dynamic switch
2288 if (ev == null ||
2289 SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_EVENT, 0) == 0) {
2290 return;
2291 }
2292 StringBuilder sb = new StringBuilder(subTag + ": ");
2293 sb.append(ev.getDownTime()).append(',');
2294 sb.append(ev.getEventTime()).append(',');
2295 sb.append(ev.getAction()).append(',');
2296 sb.append(ev.getKeyCode()).append(',');
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002297 sb.append(ev.getRepeatCount()).append(',');
2298 sb.append(ev.getMetaState()).append(',');
2299 sb.append(ev.getDeviceId()).append(',');
2300 sb.append(ev.getScanCode());
Romain Guy8506ab42009-06-11 17:35:47 -07002301 Log.d(TAG, sb.toString());
2302 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002303
2304 int enqueuePendingEvent(Object event, boolean sendDone) {
2305 int seq = mPendingEventSeq+1;
2306 if (seq < 0) seq = 0;
2307 mPendingEventSeq = seq;
2308 mPendingEvents.put(seq, event);
2309 return sendDone ? seq : -seq;
2310 }
2311
2312 Object retrievePendingEvent(int seq) {
2313 if (seq < 0) seq = -seq;
2314 Object event = mPendingEvents.get(seq);
2315 if (event != null) {
2316 mPendingEvents.remove(seq);
2317 }
2318 return event;
2319 }
Romain Guy8506ab42009-06-11 17:35:47 -07002320
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002321 private void deliverKeyEvent(KeyEvent event, boolean sendDone) {
2322 // If mView is null, we just consume the key event because it doesn't
2323 // make sense to do anything else with it.
Romain Guy812ccbe2010-06-01 14:07:24 -07002324 boolean handled = mView == null || mView.dispatchKeyEventPreIme(event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002325 if (handled) {
2326 if (sendDone) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07002327 finishInputEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002328 }
2329 return;
2330 }
2331 // If it is possible for this window to interact with the input
2332 // method window, then we want to first dispatch our key events
2333 // to the input method.
2334 if (mLastWasImTarget) {
2335 InputMethodManager imm = InputMethodManager.peekInstance();
2336 if (imm != null && mView != null) {
2337 int seq = enqueuePendingEvent(event, sendDone);
2338 if (DEBUG_IMF) Log.v(TAG, "Sending key event to IME: seq="
2339 + seq + " event=" + event);
2340 imm.dispatchKeyEvent(mView.getContext(), seq, event,
2341 mInputMethodCallback);
2342 return;
2343 }
2344 }
2345 deliverKeyEventToViewHierarchy(event, sendDone);
2346 }
2347
2348 void handleFinishedEvent(int seq, boolean handled) {
2349 final KeyEvent event = (KeyEvent)retrievePendingEvent(seq);
2350 if (DEBUG_IMF) Log.v(TAG, "IME finished event: seq=" + seq
2351 + " handled=" + handled + " event=" + event);
2352 if (event != null) {
2353 final boolean sendDone = seq >= 0;
2354 if (!handled) {
2355 deliverKeyEventToViewHierarchy(event, sendDone);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002356 } else if (sendDone) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07002357 finishInputEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002358 } else {
Jeff Brownc5ed5912010-07-14 18:48:53 -07002359 Log.w(TAG, "handleFinishedEvent(seq=" + seq
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002360 + " handled=" + handled + " ev=" + event
2361 + ") neither delivering nor finishing key");
2362 }
2363 }
2364 }
Romain Guy8506ab42009-06-11 17:35:47 -07002365
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002366 private void deliverKeyEventToViewHierarchy(KeyEvent event, boolean sendDone) {
2367 try {
2368 if (mView != null && mAdded) {
2369 final int action = event.getAction();
2370 boolean isDown = (action == KeyEvent.ACTION_DOWN);
2371
2372 if (checkForLeavingTouchModeAndConsume(event)) {
2373 return;
Romain Guy8506ab42009-06-11 17:35:47 -07002374 }
2375
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002376 if (Config.LOGV) {
2377 captureKeyLog("captureDispatchKeyEvent", event);
2378 }
2379 boolean keyHandled = mView.dispatchKeyEvent(event);
2380
2381 if (!keyHandled && isDown) {
2382 int direction = 0;
2383 switch (event.getKeyCode()) {
2384 case KeyEvent.KEYCODE_DPAD_LEFT:
2385 direction = View.FOCUS_LEFT;
2386 break;
2387 case KeyEvent.KEYCODE_DPAD_RIGHT:
2388 direction = View.FOCUS_RIGHT;
2389 break;
2390 case KeyEvent.KEYCODE_DPAD_UP:
2391 direction = View.FOCUS_UP;
2392 break;
2393 case KeyEvent.KEYCODE_DPAD_DOWN:
2394 direction = View.FOCUS_DOWN;
2395 break;
2396 }
2397
2398 if (direction != 0) {
2399
2400 View focused = mView != null ? mView.findFocus() : null;
2401 if (focused != null) {
2402 View v = focused.focusSearch(direction);
2403 boolean focusPassed = false;
2404 if (v != null && v != focused) {
2405 // do the math the get the interesting rect
2406 // of previous focused into the coord system of
2407 // newly focused view
2408 focused.getFocusedRect(mTempRect);
Dianne Hackborn1c6a8942010-03-23 16:34:20 -07002409 if (mView instanceof ViewGroup) {
2410 ((ViewGroup) mView).offsetDescendantRectToMyCoords(
2411 focused, mTempRect);
2412 ((ViewGroup) mView).offsetRectIntoDescendantCoords(
2413 v, mTempRect);
2414 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002415 focusPassed = v.requestFocus(direction, mTempRect);
2416 }
2417
2418 if (!focusPassed) {
2419 mView.dispatchUnhandledMove(focused, direction);
2420 } else {
2421 playSoundEffect(SoundEffectConstants.getContantForFocusDirection(direction));
2422 }
2423 }
2424 }
2425 }
2426 }
2427
2428 } finally {
2429 if (sendDone) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07002430 finishInputEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002431 }
2432 // Let the exception fall through -- the looper will catch
2433 // it and take care of the bad app for us.
2434 }
2435 }
2436
2437 private AudioManager getAudioManager() {
2438 if (mView == null) {
2439 throw new IllegalStateException("getAudioManager called when there is no mView");
2440 }
2441 if (mAudioManager == null) {
2442 mAudioManager = (AudioManager) mView.getContext().getSystemService(Context.AUDIO_SERVICE);
2443 }
2444 return mAudioManager;
2445 }
2446
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002447 private int relayoutWindow(WindowManager.LayoutParams params, int viewVisibility,
2448 boolean insetsPending) throws RemoteException {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002449
2450 float appScale = mAttachInfo.mApplicationScale;
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002451 boolean restore = false;
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002452 if (params != null && mTranslator != null) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07002453 restore = true;
2454 params.backup();
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002455 mTranslator.translateWindowLayout(params);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002456 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002457 if (params != null) {
2458 if (DBG) Log.d(TAG, "WindowLayout in layoutWindow:" + params);
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002459 }
Dianne Hackborn694f79b2010-03-17 19:44:59 -07002460 mPendingConfiguration.seq = 0;
Dianne Hackbornf123e492010-09-24 11:16:23 -07002461 //Log.d(TAG, ">>>>>> CALLING relayout");
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002462 int relayoutResult = sWindowSession.relayout(
2463 mWindow, params,
Mitsuru Oshima61324e52009-07-21 15:40:36 -07002464 (int) (mView.mMeasuredWidth * appScale + 0.5f),
2465 (int) (mView.mMeasuredHeight * appScale + 0.5f),
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002466 viewVisibility, insetsPending, mWinFrame,
Dianne Hackborn694f79b2010-03-17 19:44:59 -07002467 mPendingContentInsets, mPendingVisibleInsets,
2468 mPendingConfiguration, mSurface);
Dianne Hackbornf123e492010-09-24 11:16:23 -07002469 //Log.d(TAG, "<<<<<< BACK FROM relayout");
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002470 if (restore) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07002471 params.restore();
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002472 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002473
2474 if (mTranslator != null) {
2475 mTranslator.translateRectInScreenToAppWinFrame(mWinFrame);
2476 mTranslator.translateRectInScreenToAppWindow(mPendingContentInsets);
2477 mTranslator.translateRectInScreenToAppWindow(mPendingVisibleInsets);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002478 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002479 return relayoutResult;
2480 }
Romain Guy8506ab42009-06-11 17:35:47 -07002481
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002482 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002483 * {@inheritDoc}
2484 */
2485 public void playSoundEffect(int effectId) {
2486 checkThread();
2487
Jean-Michel Trivi13b18fd2010-05-05 09:18:15 -07002488 try {
2489 final AudioManager audioManager = getAudioManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002490
Jean-Michel Trivi13b18fd2010-05-05 09:18:15 -07002491 switch (effectId) {
2492 case SoundEffectConstants.CLICK:
2493 audioManager.playSoundEffect(AudioManager.FX_KEY_CLICK);
2494 return;
2495 case SoundEffectConstants.NAVIGATION_DOWN:
2496 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_DOWN);
2497 return;
2498 case SoundEffectConstants.NAVIGATION_LEFT:
2499 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_LEFT);
2500 return;
2501 case SoundEffectConstants.NAVIGATION_RIGHT:
2502 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_RIGHT);
2503 return;
2504 case SoundEffectConstants.NAVIGATION_UP:
2505 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_UP);
2506 return;
2507 default:
2508 throw new IllegalArgumentException("unknown effect id " + effectId +
2509 " not defined in " + SoundEffectConstants.class.getCanonicalName());
2510 }
2511 } catch (IllegalStateException e) {
2512 // Exception thrown by getAudioManager() when mView is null
2513 Log.e(TAG, "FATAL EXCEPTION when attempting to play sound effect: " + e);
2514 e.printStackTrace();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002515 }
2516 }
2517
2518 /**
2519 * {@inheritDoc}
2520 */
2521 public boolean performHapticFeedback(int effectId, boolean always) {
2522 try {
2523 return sWindowSession.performHapticFeedback(mWindow, effectId, always);
2524 } catch (RemoteException e) {
2525 return false;
2526 }
2527 }
2528
2529 /**
2530 * {@inheritDoc}
2531 */
2532 public View focusSearch(View focused, int direction) {
2533 checkThread();
2534 if (!(mView instanceof ViewGroup)) {
2535 return null;
2536 }
2537 return FocusFinder.getInstance().findNextFocus((ViewGroup) mView, focused, direction);
2538 }
2539
2540 public void debug() {
2541 mView.debug();
2542 }
2543
2544 public void die(boolean immediate) {
Dianne Hackborn94d69142009-09-28 22:14:42 -07002545 if (immediate) {
2546 doDie();
2547 } else {
2548 sendEmptyMessage(DIE);
2549 }
2550 }
2551
2552 void doDie() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002553 checkThread();
Jeff Brownb75fa302010-07-15 23:47:29 -07002554 if (LOCAL_LOGV) Log.v(TAG, "DIE in " + this + " of " + mSurface);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002555 synchronized (this) {
2556 if (mAdded && !mFirst) {
Romain Guy29d89972010-09-22 16:10:57 -07002557 destroyHardwareRenderer();
2558
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002559 int viewVisibility = mView.getVisibility();
2560 boolean viewVisibilityChanged = mViewVisibility != viewVisibility;
2561 if (mWindowAttributesChanged || viewVisibilityChanged) {
2562 // If layout params have been changed, first give them
2563 // to the window manager to make sure it has the correct
2564 // animation info.
2565 try {
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002566 if ((relayoutWindow(mWindowAttributes, viewVisibility, false)
2567 & WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002568 sWindowSession.finishDrawing(mWindow);
2569 }
2570 } catch (RemoteException e) {
2571 }
2572 }
2573
Dianne Hackborn0586a1b2009-09-06 21:08:27 -07002574 mSurface.release();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002575 }
2576 if (mAdded) {
2577 mAdded = false;
Dianne Hackborn94d69142009-09-28 22:14:42 -07002578 dispatchDetachedFromWindow();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002579 }
2580 }
2581 }
2582
Romain Guy29d89972010-09-22 16:10:57 -07002583 private void destroyHardwareRenderer() {
Romain Guyb051e892010-09-28 19:09:36 -07002584 if (mAttachInfo.mHardwareRenderer != null) {
2585 mAttachInfo.mHardwareRenderer.destroy(true);
2586 mAttachInfo.mHardwareRenderer = null;
Romain Guy29d89972010-09-22 16:10:57 -07002587 mAttachInfo.mHardwareAccelerated = false;
2588 }
2589 }
2590
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002591 public void dispatchFinishedEvent(int seq, boolean handled) {
2592 Message msg = obtainMessage(FINISHED_EVENT);
2593 msg.arg1 = seq;
2594 msg.arg2 = handled ? 1 : 0;
2595 sendMessage(msg);
2596 }
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002597
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002598 public void dispatchResized(int w, int h, Rect coveredInsets,
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002599 Rect visibleInsets, boolean reportDraw, Configuration newConfig) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002600 if (DEBUG_LAYOUT) Log.v(TAG, "Resizing " + this + ": w=" + w
2601 + " h=" + h + " coveredInsets=" + coveredInsets.toShortString()
2602 + " visibleInsets=" + visibleInsets.toShortString()
2603 + " reportDraw=" + reportDraw);
2604 Message msg = obtainMessage(reportDraw ? RESIZED_REPORT :RESIZED);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002605 if (mTranslator != null) {
2606 mTranslator.translateRectInScreenToAppWindow(coveredInsets);
2607 mTranslator.translateRectInScreenToAppWindow(visibleInsets);
2608 w *= mTranslator.applicationInvertedScale;
2609 h *= mTranslator.applicationInvertedScale;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002610 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002611 msg.arg1 = w;
2612 msg.arg2 = h;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002613 ResizedInfo ri = new ResizedInfo();
2614 ri.coveredInsets = new Rect(coveredInsets);
2615 ri.visibleInsets = new Rect(visibleInsets);
2616 ri.newConfig = newConfig;
2617 msg.obj = ri;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002618 sendMessage(msg);
2619 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002620
2621 private Runnable mFinishedCallback;
2622
2623 private final InputHandler mInputHandler = new InputHandler() {
2624 public void handleKey(KeyEvent event, Runnable finishedCallback) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07002625 startInputEvent(finishedCallback);
Jeff Brown92ff1dd2010-08-11 16:16:06 -07002626 dispatchKey(event, true);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002627 }
2628
Jeff Brownc5ed5912010-07-14 18:48:53 -07002629 public void handleMotion(MotionEvent event, Runnable finishedCallback) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07002630 startInputEvent(finishedCallback);
2631 dispatchMotion(event, true);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002632 }
2633 };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002634
2635 public void dispatchKey(KeyEvent event) {
Jeff Brown92ff1dd2010-08-11 16:16:06 -07002636 dispatchKey(event, false);
2637 }
2638
2639 private void dispatchKey(KeyEvent event, boolean sendDone) {
2640 //noinspection ConstantConditions
2641 if (false && event.getAction() == KeyEvent.ACTION_DOWN) {
2642 if (event.getKeyCode() == KeyEvent.KEYCODE_CAMERA) {
Romain Guy812ccbe2010-06-01 14:07:24 -07002643 if (DBG) Log.d("keydisp", "===================================================");
2644 if (DBG) Log.d("keydisp", "Focused view Hierarchy is:");
2645
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002646 debug();
2647
Romain Guy812ccbe2010-06-01 14:07:24 -07002648 if (DBG) Log.d("keydisp", "===================================================");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002649 }
2650 }
2651
2652 Message msg = obtainMessage(DISPATCH_KEY);
2653 msg.obj = event;
Jeff Brown92ff1dd2010-08-11 16:16:06 -07002654 msg.arg1 = sendDone ? 1 : 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002655
2656 if (LOCAL_LOGV) Log.v(
Jeff Brownc5ed5912010-07-14 18:48:53 -07002657 TAG, "sending key " + event + " to " + mView);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002658
2659 sendMessageAtTime(msg, event.getEventTime());
2660 }
Jeff Brownc5ed5912010-07-14 18:48:53 -07002661
2662 public void dispatchMotion(MotionEvent event) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07002663 dispatchMotion(event, false);
2664 }
2665
2666 private void dispatchMotion(MotionEvent event, boolean sendDone) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07002667 int source = event.getSource();
2668 if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07002669 dispatchPointer(event, sendDone);
Jeff Brownc5ed5912010-07-14 18:48:53 -07002670 } else if ((source & InputDevice.SOURCE_CLASS_TRACKBALL) != 0) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07002671 dispatchTrackball(event, sendDone);
Jeff Brownc5ed5912010-07-14 18:48:53 -07002672 } else {
2673 // TODO
2674 Log.v(TAG, "Dropping unsupported motion event (unimplemented): " + event);
Jeff Brown93ed4e32010-09-23 13:51:48 -07002675 if (sendDone) {
2676 finishInputEvent();
2677 }
Jeff Brownc5ed5912010-07-14 18:48:53 -07002678 }
2679 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002680
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002681 public void dispatchPointer(MotionEvent event) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07002682 dispatchPointer(event, false);
2683 }
2684
2685 private void dispatchPointer(MotionEvent event, boolean sendDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002686 Message msg = obtainMessage(DISPATCH_POINTER);
2687 msg.obj = event;
Jeff Brown93ed4e32010-09-23 13:51:48 -07002688 msg.arg1 = sendDone ? 1 : 0;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002689 sendMessageAtTime(msg, event.getEventTime());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002690 }
2691
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002692 public void dispatchTrackball(MotionEvent event) {
Jeff Brown93ed4e32010-09-23 13:51:48 -07002693 dispatchTrackball(event, false);
2694 }
2695
2696 private void dispatchTrackball(MotionEvent event, boolean sendDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002697 Message msg = obtainMessage(DISPATCH_TRACKBALL);
2698 msg.obj = event;
Jeff Brown93ed4e32010-09-23 13:51:48 -07002699 msg.arg1 = sendDone ? 1 : 0;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002700 sendMessageAtTime(msg, event.getEventTime());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002701 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002702
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002703 public void dispatchAppVisibility(boolean visible) {
2704 Message msg = obtainMessage(DISPATCH_APP_VISIBILITY);
2705 msg.arg1 = visible ? 1 : 0;
2706 sendMessage(msg);
2707 }
2708
2709 public void dispatchGetNewSurface() {
2710 Message msg = obtainMessage(DISPATCH_GET_NEW_SURFACE);
2711 sendMessage(msg);
2712 }
2713
2714 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
2715 Message msg = Message.obtain();
2716 msg.what = WINDOW_FOCUS_CHANGED;
2717 msg.arg1 = hasFocus ? 1 : 0;
2718 msg.arg2 = inTouchMode ? 1 : 0;
2719 sendMessage(msg);
2720 }
2721
Dianne Hackbornffa42482009-09-23 22:20:11 -07002722 public void dispatchCloseSystemDialogs(String reason) {
2723 Message msg = Message.obtain();
2724 msg.what = CLOSE_SYSTEM_DIALOGS;
2725 msg.obj = reason;
2726 sendMessage(msg);
2727 }
2728
svetoslavganov75986cf2009-05-14 22:28:01 -07002729 /**
2730 * The window is getting focus so if there is anything focused/selected
2731 * send an {@link AccessibilityEvent} to announce that.
2732 */
2733 private void sendAccessibilityEvents() {
2734 if (!AccessibilityManager.getInstance(mView.getContext()).isEnabled()) {
2735 return;
2736 }
2737 mView.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
2738 View focusedView = mView.findFocus();
2739 if (focusedView != null && focusedView != mView) {
2740 focusedView.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
2741 }
2742 }
2743
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002744 public boolean showContextMenuForChild(View originalView) {
2745 return false;
2746 }
2747
Adam Powell6e346362010-07-23 10:18:23 -07002748 public ActionMode startActionModeForChild(View originalView, ActionMode.Callback callback) {
2749 return null;
2750 }
2751
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002752 public void createContextMenu(ContextMenu menu) {
2753 }
2754
2755 public void childDrawableStateChanged(View child) {
2756 }
2757
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002758 void checkThread() {
2759 if (mThread != Thread.currentThread()) {
2760 throw new CalledFromWrongThreadException(
2761 "Only the original thread that created a view hierarchy can touch its views.");
2762 }
2763 }
2764
2765 public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
2766 // ViewRoot never intercepts touch event, so this can be a no-op
2767 }
2768
2769 public boolean requestChildRectangleOnScreen(View child, Rect rectangle,
2770 boolean immediate) {
2771 return scrollToRectOrFocus(rectangle, immediate);
2772 }
Romain Guy8506ab42009-06-11 17:35:47 -07002773
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07002774 class TakenSurfaceHolder extends BaseSurfaceHolder {
2775 @Override
2776 public boolean onAllowLockCanvas() {
2777 return mDrawingAllowed;
2778 }
2779
2780 @Override
2781 public void onRelayoutContainer() {
2782 // Not currently interesting -- from changing between fixed and layout size.
2783 }
2784
2785 public void setFormat(int format) {
2786 ((RootViewSurfaceTaker)mView).setSurfaceFormat(format);
2787 }
2788
2789 public void setType(int type) {
2790 ((RootViewSurfaceTaker)mView).setSurfaceType(type);
2791 }
2792
2793 @Override
2794 public void onUpdateSurface() {
2795 // We take care of format and type changes on our own.
2796 throw new IllegalStateException("Shouldn't be here");
2797 }
2798
2799 public boolean isCreating() {
2800 return mIsCreating;
2801 }
2802
2803 @Override
2804 public void setFixedSize(int width, int height) {
2805 throw new UnsupportedOperationException(
2806 "Currently only support sizing from layout");
2807 }
2808
2809 public void setKeepScreenOn(boolean screenOn) {
2810 ((RootViewSurfaceTaker)mView).setSurfaceKeepScreenOn(screenOn);
2811 }
2812 }
2813
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002814 static class InputMethodCallback extends IInputMethodCallback.Stub {
2815 private WeakReference<ViewRoot> mViewRoot;
2816
2817 public InputMethodCallback(ViewRoot viewRoot) {
2818 mViewRoot = new WeakReference<ViewRoot>(viewRoot);
2819 }
Romain Guy8506ab42009-06-11 17:35:47 -07002820
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002821 public void finishedEvent(int seq, boolean handled) {
2822 final ViewRoot viewRoot = mViewRoot.get();
2823 if (viewRoot != null) {
2824 viewRoot.dispatchFinishedEvent(seq, handled);
2825 }
2826 }
2827
2828 public void sessionCreated(IInputMethodSession session) throws RemoteException {
2829 // Stub -- not for use in the client.
2830 }
2831 }
Romain Guy8506ab42009-06-11 17:35:47 -07002832
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002833 static class W extends IWindow.Stub {
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002834 private final WeakReference<ViewRoot> mViewRoot;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002835
Romain Guyfb8b7632010-08-23 21:05:08 -07002836 W(ViewRoot viewRoot) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002837 mViewRoot = new WeakReference<ViewRoot>(viewRoot);
2838 }
2839
Romain Guyfb8b7632010-08-23 21:05:08 -07002840 public void resized(int w, int h, Rect coveredInsets, Rect visibleInsets,
2841 boolean reportDraw, Configuration newConfig) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002842 final ViewRoot viewRoot = mViewRoot.get();
2843 if (viewRoot != null) {
Romain Guyfb8b7632010-08-23 21:05:08 -07002844 viewRoot.dispatchResized(w, h, coveredInsets, visibleInsets, reportDraw, newConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002845 }
2846 }
2847
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002848 public void dispatchAppVisibility(boolean visible) {
2849 final ViewRoot viewRoot = mViewRoot.get();
2850 if (viewRoot != null) {
2851 viewRoot.dispatchAppVisibility(visible);
2852 }
2853 }
2854
2855 public void dispatchGetNewSurface() {
2856 final ViewRoot viewRoot = mViewRoot.get();
2857 if (viewRoot != null) {
2858 viewRoot.dispatchGetNewSurface();
2859 }
2860 }
2861
2862 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
2863 final ViewRoot viewRoot = mViewRoot.get();
2864 if (viewRoot != null) {
2865 viewRoot.windowFocusChanged(hasFocus, inTouchMode);
2866 }
2867 }
2868
2869 private static int checkCallingPermission(String permission) {
2870 if (!Process.supportsProcesses()) {
2871 return PackageManager.PERMISSION_GRANTED;
2872 }
2873
2874 try {
2875 return ActivityManagerNative.getDefault().checkPermission(
2876 permission, Binder.getCallingPid(), Binder.getCallingUid());
2877 } catch (RemoteException e) {
2878 return PackageManager.PERMISSION_DENIED;
2879 }
2880 }
2881
2882 public void executeCommand(String command, String parameters, ParcelFileDescriptor out) {
2883 final ViewRoot viewRoot = mViewRoot.get();
2884 if (viewRoot != null) {
2885 final View view = viewRoot.mView;
2886 if (view != null) {
2887 if (checkCallingPermission(Manifest.permission.DUMP) !=
2888 PackageManager.PERMISSION_GRANTED) {
2889 throw new SecurityException("Insufficient permissions to invoke"
2890 + " executeCommand() from pid=" + Binder.getCallingPid()
2891 + ", uid=" + Binder.getCallingUid());
2892 }
2893
2894 OutputStream clientStream = null;
2895 try {
2896 clientStream = new ParcelFileDescriptor.AutoCloseOutputStream(out);
2897 ViewDebug.dispatchCommand(view, command, parameters, clientStream);
2898 } catch (IOException e) {
2899 e.printStackTrace();
2900 } finally {
2901 if (clientStream != null) {
2902 try {
2903 clientStream.close();
2904 } catch (IOException e) {
2905 e.printStackTrace();
2906 }
2907 }
2908 }
2909 }
2910 }
2911 }
Dianne Hackborn72c82ab2009-08-11 21:13:54 -07002912
Dianne Hackbornffa42482009-09-23 22:20:11 -07002913 public void closeSystemDialogs(String reason) {
2914 final ViewRoot viewRoot = mViewRoot.get();
2915 if (viewRoot != null) {
2916 viewRoot.dispatchCloseSystemDialogs(reason);
2917 }
2918 }
2919
Marco Nelissenbf6956b2009-11-09 15:21:13 -08002920 public void dispatchWallpaperOffsets(float x, float y, float xStep, float yStep,
2921 boolean sync) {
Dianne Hackborn19382ac2009-09-11 21:13:37 -07002922 if (sync) {
2923 try {
2924 sWindowSession.wallpaperOffsetsComplete(asBinder());
2925 } catch (RemoteException e) {
2926 }
2927 }
Dianne Hackborn72c82ab2009-08-11 21:13:54 -07002928 }
Dianne Hackborn75804932009-10-20 20:15:20 -07002929
2930 public void dispatchWallpaperCommand(String action, int x, int y,
2931 int z, Bundle extras, boolean sync) {
2932 if (sync) {
2933 try {
2934 sWindowSession.wallpaperCommandComplete(asBinder(), null);
2935 } catch (RemoteException e) {
2936 }
2937 }
2938 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002939 }
2940
2941 /**
2942 * Maintains state information for a single trackball axis, generating
2943 * discrete (DPAD) movements based on raw trackball motion.
2944 */
2945 static final class TrackballAxis {
2946 /**
2947 * The maximum amount of acceleration we will apply.
2948 */
2949 static final float MAX_ACCELERATION = 20;
Romain Guy8506ab42009-06-11 17:35:47 -07002950
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002951 /**
2952 * The maximum amount of time (in milliseconds) between events in order
2953 * for us to consider the user to be doing fast trackball movements,
2954 * and thus apply an acceleration.
2955 */
2956 static final long FAST_MOVE_TIME = 150;
Romain Guy8506ab42009-06-11 17:35:47 -07002957
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002958 /**
2959 * Scaling factor to the time (in milliseconds) between events to how
2960 * much to multiple/divide the current acceleration. When movement
2961 * is < FAST_MOVE_TIME this multiplies the acceleration; when >
2962 * FAST_MOVE_TIME it divides it.
2963 */
2964 static final float ACCEL_MOVE_SCALING_FACTOR = (1.0f/40);
Romain Guy8506ab42009-06-11 17:35:47 -07002965
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002966 float position;
2967 float absPosition;
2968 float acceleration = 1;
2969 long lastMoveTime = 0;
2970 int step;
2971 int dir;
2972 int nonAccelMovement;
2973
2974 void reset(int _step) {
2975 position = 0;
2976 acceleration = 1;
2977 lastMoveTime = 0;
2978 step = _step;
2979 dir = 0;
2980 }
2981
2982 /**
2983 * Add trackball movement into the state. If the direction of movement
2984 * has been reversed, the state is reset before adding the
2985 * movement (so that you don't have to compensate for any previously
2986 * collected movement before see the result of the movement in the
2987 * new direction).
2988 *
2989 * @return Returns the absolute value of the amount of movement
2990 * collected so far.
2991 */
2992 float collect(float off, long time, String axis) {
2993 long normTime;
2994 if (off > 0) {
2995 normTime = (long)(off * FAST_MOVE_TIME);
2996 if (dir < 0) {
2997 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to positive!");
2998 position = 0;
2999 step = 0;
3000 acceleration = 1;
3001 lastMoveTime = 0;
3002 }
3003 dir = 1;
3004 } else if (off < 0) {
3005 normTime = (long)((-off) * FAST_MOVE_TIME);
3006 if (dir > 0) {
3007 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to negative!");
3008 position = 0;
3009 step = 0;
3010 acceleration = 1;
3011 lastMoveTime = 0;
3012 }
3013 dir = -1;
3014 } else {
3015 normTime = 0;
3016 }
Romain Guy8506ab42009-06-11 17:35:47 -07003017
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003018 // The number of milliseconds between each movement that is
3019 // considered "normal" and will not result in any acceleration
3020 // or deceleration, scaled by the offset we have here.
3021 if (normTime > 0) {
3022 long delta = time - lastMoveTime;
3023 lastMoveTime = time;
3024 float acc = acceleration;
3025 if (delta < normTime) {
3026 // The user is scrolling rapidly, so increase acceleration.
3027 float scale = (normTime-delta) * ACCEL_MOVE_SCALING_FACTOR;
3028 if (scale > 1) acc *= scale;
3029 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " accelerate: off="
3030 + off + " normTime=" + normTime + " delta=" + delta
3031 + " scale=" + scale + " acc=" + acc);
3032 acceleration = acc < MAX_ACCELERATION ? acc : MAX_ACCELERATION;
3033 } else {
3034 // The user is scrolling slowly, so decrease acceleration.
3035 float scale = (delta-normTime) * ACCEL_MOVE_SCALING_FACTOR;
3036 if (scale > 1) acc /= scale;
3037 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " deccelerate: off="
3038 + off + " normTime=" + normTime + " delta=" + delta
3039 + " scale=" + scale + " acc=" + acc);
3040 acceleration = acc > 1 ? acc : 1;
3041 }
3042 }
3043 position += off;
3044 return (absPosition = Math.abs(position));
3045 }
3046
3047 /**
3048 * Generate the number of discrete movement events appropriate for
3049 * the currently collected trackball movement.
3050 *
3051 * @param precision The minimum movement required to generate the
3052 * first discrete movement.
3053 *
3054 * @return Returns the number of discrete movements, either positive
3055 * or negative, or 0 if there is not enough trackball movement yet
3056 * for a discrete movement.
3057 */
3058 int generate(float precision) {
3059 int movement = 0;
3060 nonAccelMovement = 0;
3061 do {
3062 final int dir = position >= 0 ? 1 : -1;
3063 switch (step) {
3064 // If we are going to execute the first step, then we want
3065 // to do this as soon as possible instead of waiting for
3066 // a full movement, in order to make things look responsive.
3067 case 0:
3068 if (absPosition < precision) {
3069 return movement;
3070 }
3071 movement += dir;
3072 nonAccelMovement += dir;
3073 step = 1;
3074 break;
3075 // If we have generated the first movement, then we need
3076 // to wait for the second complete trackball motion before
3077 // generating the second discrete movement.
3078 case 1:
3079 if (absPosition < 2) {
3080 return movement;
3081 }
3082 movement += dir;
3083 nonAccelMovement += dir;
3084 position += dir > 0 ? -2 : 2;
3085 absPosition = Math.abs(position);
3086 step = 2;
3087 break;
3088 // After the first two, we generate discrete movements
3089 // consistently with the trackball, applying an acceleration
3090 // if the trackball is moving quickly. This is a simple
3091 // acceleration on top of what we already compute based
3092 // on how quickly the wheel is being turned, to apply
3093 // a longer increasing acceleration to continuous movement
3094 // in one direction.
3095 default:
3096 if (absPosition < 1) {
3097 return movement;
3098 }
3099 movement += dir;
3100 position += dir >= 0 ? -1 : 1;
3101 absPosition = Math.abs(position);
3102 float acc = acceleration;
3103 acc *= 1.1f;
3104 acceleration = acc < MAX_ACCELERATION ? acc : acceleration;
3105 break;
3106 }
3107 } while (true);
3108 }
3109 }
3110
3111 public static final class CalledFromWrongThreadException extends AndroidRuntimeException {
3112 public CalledFromWrongThreadException(String msg) {
3113 super(msg);
3114 }
3115 }
3116
3117 private SurfaceHolder mHolder = new SurfaceHolder() {
3118 // we only need a SurfaceHolder for opengl. it would be nice
3119 // to implement everything else though, especially the callback
3120 // support (opengl doesn't make use of it right now, but eventually
3121 // will).
3122 public Surface getSurface() {
3123 return mSurface;
3124 }
3125
3126 public boolean isCreating() {
3127 return false;
3128 }
3129
3130 public void addCallback(Callback callback) {
3131 }
3132
3133 public void removeCallback(Callback callback) {
3134 }
3135
3136 public void setFixedSize(int width, int height) {
3137 }
3138
3139 public void setSizeFromLayout() {
3140 }
3141
3142 public void setFormat(int format) {
3143 }
3144
3145 public void setType(int type) {
3146 }
3147
3148 public void setKeepScreenOn(boolean screenOn) {
3149 }
3150
3151 public Canvas lockCanvas() {
3152 return null;
3153 }
3154
3155 public Canvas lockCanvas(Rect dirty) {
3156 return null;
3157 }
3158
3159 public void unlockCanvasAndPost(Canvas canvas) {
3160 }
3161 public Rect getSurfaceFrame() {
3162 return null;
3163 }
3164 };
3165
3166 static RunQueue getRunQueue() {
3167 RunQueue rq = sRunQueues.get();
3168 if (rq != null) {
3169 return rq;
3170 }
3171 rq = new RunQueue();
3172 sRunQueues.set(rq);
3173 return rq;
3174 }
Romain Guy8506ab42009-06-11 17:35:47 -07003175
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003176 /**
3177 * @hide
3178 */
3179 static final class RunQueue {
3180 private final ArrayList<HandlerAction> mActions = new ArrayList<HandlerAction>();
3181
3182 void post(Runnable action) {
3183 postDelayed(action, 0);
3184 }
3185
3186 void postDelayed(Runnable action, long delayMillis) {
3187 HandlerAction handlerAction = new HandlerAction();
3188 handlerAction.action = action;
3189 handlerAction.delay = delayMillis;
3190
3191 synchronized (mActions) {
3192 mActions.add(handlerAction);
3193 }
3194 }
3195
3196 void removeCallbacks(Runnable action) {
3197 final HandlerAction handlerAction = new HandlerAction();
3198 handlerAction.action = action;
3199
3200 synchronized (mActions) {
3201 final ArrayList<HandlerAction> actions = mActions;
3202
3203 while (actions.remove(handlerAction)) {
3204 // Keep going
3205 }
3206 }
3207 }
3208
3209 void executeActions(Handler handler) {
3210 synchronized (mActions) {
3211 final ArrayList<HandlerAction> actions = mActions;
3212 final int count = actions.size();
3213
3214 for (int i = 0; i < count; i++) {
3215 final HandlerAction handlerAction = actions.get(i);
3216 handler.postDelayed(handlerAction.action, handlerAction.delay);
3217 }
3218
Romain Guy15df6702009-08-17 20:17:30 -07003219 actions.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003220 }
3221 }
3222
3223 private static class HandlerAction {
3224 Runnable action;
3225 long delay;
3226
3227 @Override
3228 public boolean equals(Object o) {
3229 if (this == o) return true;
3230 if (o == null || getClass() != o.getClass()) return false;
3231
3232 HandlerAction that = (HandlerAction) o;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003233 return !(action != null ? !action.equals(that.action) : that.action != null);
3234
3235 }
3236
3237 @Override
3238 public int hashCode() {
3239 int result = action != null ? action.hashCode() : 0;
3240 result = 31 * result + (int) (delay ^ (delay >>> 32));
3241 return result;
3242 }
3243 }
3244 }
3245
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003246 private static native void nativeShowFPS(Canvas canvas, int durationMillis);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003247}