blob: faa478309fc482e2e876724a68fe090a8b9c3f12 [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
92 static long sInstanceCount = 0;
93
94 static IWindowSession sWindowSession;
95
96 static final Object mStaticInit = new Object();
97 static boolean mInitialized = false;
98
99 static final ThreadLocal<RunQueue> sRunQueues = new ThreadLocal<RunQueue>();
100
Dianne Hackborn2a9094d2010-02-03 19:20:09 -0800101 static final ArrayList<Runnable> sFirstDrawHandlers = new ArrayList<Runnable>();
102 static boolean sFirstDrawComplete = false;
103
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800104 static final ArrayList<ComponentCallbacks> sConfigCallbacks
105 = new ArrayList<ComponentCallbacks>();
106
Romain Guy8506ab42009-06-11 17:35:47 -0700107 private static int sDrawTime;
Romain Guy13922e02009-05-12 17:56:14 -0700108
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800109 long mLastTrackballTime = 0;
110 final TrackballAxis mTrackballAxisX = new TrackballAxis();
111 final TrackballAxis mTrackballAxisY = new TrackballAxis();
112
113 final int[] mTmpLocation = new int[2];
Romain Guy8506ab42009-06-11 17:35:47 -0700114
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800115 final InputMethodCallback mInputMethodCallback;
116 final SparseArray<Object> mPendingEvents = new SparseArray<Object>();
117 int mPendingEventSeq = 0;
Romain Guy8506ab42009-06-11 17:35:47 -0700118
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800119 final Thread mThread;
120
121 final WindowLeaked mLocation;
122
123 final WindowManager.LayoutParams mWindowAttributes = new WindowManager.LayoutParams();
124
125 final W mWindow;
126
127 View mView;
128 View mFocusedView;
129 View mRealFocusedView; // this is not set to null in touch mode
130 int mViewVisibility;
131 boolean mAppVisible = true;
132
Dianne Hackbornd76b67c2010-07-13 17:48:30 -0700133 SurfaceHolder.Callback2 mSurfaceHolderCallback;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700134 BaseSurfaceHolder mSurfaceHolder;
135 boolean mIsCreating;
136 boolean mDrawingAllowed;
137
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800138 final Region mTransparentRegion;
139 final Region mPreviousTransparentRegion;
140
141 int mWidth;
142 int mHeight;
143 Rect mDirty; // will be a graphics.Region soon
Romain Guybb93d552009-03-24 21:04:15 -0700144 boolean mIsAnimating;
Romain Guy8506ab42009-06-11 17:35:47 -0700145
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700146 CompatibilityInfo.Translator mTranslator;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800147
148 final View.AttachInfo mAttachInfo;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700149 InputChannel mInputChannel;
Dianne Hackborn1e4b9f32010-06-23 14:10:57 -0700150 InputQueue.Callback mInputQueueCallback;
151 InputQueue mInputQueue;
Dianne Hackborna95e4cb2010-06-18 18:09:33 -0700152
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800153 final Rect mTempRect; // used in the transaction to not thrash the heap.
154 final Rect mVisRect; // used to retrieve visible rect of focused view.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800155
156 boolean mTraversalScheduled;
157 boolean mWillDrawSoon;
158 boolean mLayoutRequested;
159 boolean mFirst;
160 boolean mReportNextDraw;
161 boolean mFullRedrawNeeded;
162 boolean mNewSurfaceNeeded;
163 boolean mHasHadWindowFocus;
164 boolean mLastWasImTarget;
165
166 boolean mWindowAttributesChanged = false;
167
168 // These can be accessed by any thread, must be protected with a lock.
Mathias Agopian5583dc62009-07-09 16:28:11 -0700169 // Surface can never be reassigned or cleared (use Surface.clear()).
170 private final Surface mSurface = new Surface();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800171
172 boolean mAdded;
173 boolean mAddedTouchMode;
174
175 /*package*/ int mAddNesting;
176
177 // These are accessed by multiple threads.
178 final Rect mWinFrame; // frame given by window manager.
179
180 final Rect mPendingVisibleInsets = new Rect();
181 final Rect mPendingContentInsets = new Rect();
182 final ViewTreeObserver.InternalInsetsInfo mLastGivenInsets
183 = new ViewTreeObserver.InternalInsetsInfo();
184
Dianne Hackborn694f79b2010-03-17 19:44:59 -0700185 final Configuration mLastConfiguration = new Configuration();
186 final Configuration mPendingConfiguration = new Configuration();
187
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800188 class ResizedInfo {
189 Rect coveredInsets;
190 Rect visibleInsets;
191 Configuration newConfig;
192 }
193
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800194 boolean mScrollMayChange;
195 int mSoftInputMode;
196 View mLastScrolledFocus;
197 int mScrollY;
198 int mCurScrollY;
199 Scroller mScroller;
Romain Guy8506ab42009-06-11 17:35:47 -0700200
Romain Guy812ccbe2010-06-01 14:07:24 -0700201 HardwareRenderer mHwRenderer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800202
Romain Guy8506ab42009-06-11 17:35:47 -0700203 final ViewConfiguration mViewConfiguration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800204
205 /**
206 * see {@link #playSoundEffect(int)}
207 */
208 AudioManager mAudioManager;
209
Dianne Hackborn11ea3342009-07-22 21:48:55 -0700210 private final int mDensity;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700211
Dianne Hackborn4c62fc02009-08-08 20:40:27 -0700212 public static IWindowSession getWindowSession(Looper mainLooper) {
213 synchronized (mStaticInit) {
214 if (!mInitialized) {
215 try {
216 InputMethodManager imm = InputMethodManager.getInstance(mainLooper);
217 sWindowSession = IWindowManager.Stub.asInterface(
218 ServiceManager.getService("window"))
219 .openSession(imm.getClient(), imm.getInputContext());
220 mInitialized = true;
221 } catch (RemoteException e) {
222 }
223 }
224 return sWindowSession;
225 }
226 }
227
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800228 public ViewRoot(Context context) {
229 super();
230
Romain Guy812ccbe2010-06-01 14:07:24 -0700231 if (MEASURE_LATENCY) {
232 if (lt == null) {
233 lt = new LatencyTimer(100, 1000);
234 }
Michael Chan53071d62009-05-13 17:29:48 -0700235 }
236
Carl Shapiro82fe5642010-02-24 00:14:23 -0800237 // For debug only
238 //++sInstanceCount;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800239
240 // Initialize the statics when this class is first instantiated. This is
241 // done here instead of in the static block because Zygote does not
242 // allow the spawning of threads.
Dianne Hackborn4c62fc02009-08-08 20:40:27 -0700243 getWindowSession(context.getMainLooper());
244
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800245 mThread = Thread.currentThread();
246 mLocation = new WindowLeaked(null);
247 mLocation.fillInStackTrace();
248 mWidth = -1;
249 mHeight = -1;
250 mDirty = new Rect();
251 mTempRect = new Rect();
252 mVisRect = new Rect();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800253 mWinFrame = new Rect();
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -0700254 mWindow = new W(this, context);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800255 mInputMethodCallback = new InputMethodCallback(this);
256 mViewVisibility = View.GONE;
257 mTransparentRegion = new Region();
258 mPreviousTransparentRegion = new Region();
259 mFirst = true; // true for the first time the view is added
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800260 mAdded = false;
261 mAttachInfo = new View.AttachInfo(sWindowSession, mWindow, this, this);
262 mViewConfiguration = ViewConfiguration.get(context);
Dianne Hackborn11ea3342009-07-22 21:48:55 -0700263 mDensity = context.getResources().getDisplayMetrics().densityDpi;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800264 }
265
Carl Shapiro82fe5642010-02-24 00:14:23 -0800266 // For debug only
267 /*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800268 @Override
269 protected void finalize() throws Throwable {
270 super.finalize();
271 --sInstanceCount;
272 }
Carl Shapiro82fe5642010-02-24 00:14:23 -0800273 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800274
275 public static long getInstanceCount() {
276 return sInstanceCount;
277 }
278
Dianne Hackborn2a9094d2010-02-03 19:20:09 -0800279 public static void addFirstDrawHandler(Runnable callback) {
280 synchronized (sFirstDrawHandlers) {
281 if (!sFirstDrawComplete) {
282 sFirstDrawHandlers.add(callback);
283 }
284 }
285 }
286
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800287 public static void addConfigCallback(ComponentCallbacks callback) {
288 synchronized (sConfigCallbacks) {
289 sConfigCallbacks.add(callback);
290 }
291 }
292
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800293 // FIXME for perf testing only
294 private boolean mProfile = false;
295
296 /**
297 * Call this to profile the next traversal call.
298 * FIXME for perf testing only. Remove eventually
299 */
300 public void profile() {
301 mProfile = true;
302 }
303
304 /**
305 * Indicates whether we are in touch mode. Calling this method triggers an IPC
306 * call and should be avoided whenever possible.
307 *
308 * @return True, if the device is in touch mode, false otherwise.
309 *
310 * @hide
311 */
312 static boolean isInTouchMode() {
313 if (mInitialized) {
314 try {
315 return sWindowSession.getInTouchMode();
316 } catch (RemoteException e) {
317 }
318 }
319 return false;
320 }
321
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800322 /**
323 * We have one child
324 */
Romain Guye4d01122010-06-16 18:44:05 -0700325 public void setView(View view, WindowManager.LayoutParams attrs, View panelParentView) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800326 synchronized (this) {
327 if (mView == null) {
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700328 mView = view;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700329 mWindowAttributes.copyFrom(attrs);
Mitsuru Oshima1ecf5d22009-07-06 17:20:38 -0700330 attrs = mWindowAttributes;
Romain Guye4d01122010-06-16 18:44:05 -0700331
Romain Guy529b60a2010-08-03 18:05:47 -0700332 enableHardwareAcceleration(attrs);
Romain Guye4d01122010-06-16 18:44:05 -0700333
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700334 if (view instanceof RootViewSurfaceTaker) {
335 mSurfaceHolderCallback =
336 ((RootViewSurfaceTaker)view).willYouTakeTheSurface();
337 if (mSurfaceHolderCallback != null) {
338 mSurfaceHolder = new TakenSurfaceHolder();
Dianne Hackborn289b9b62010-07-09 11:44:11 -0700339 mSurfaceHolder.setFormat(PixelFormat.UNKNOWN);
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700340 }
341 }
Mitsuru Oshima38ed7d772009-07-21 14:39:34 -0700342 Resources resources = mView.getContext().getResources();
343 CompatibilityInfo compatibilityInfo = resources.getCompatibilityInfo();
Mitsuru Oshima589cebe2009-07-22 20:38:58 -0700344 mTranslator = compatibilityInfo.getTranslator();
Mitsuru Oshima38ed7d772009-07-21 14:39:34 -0700345
346 if (mTranslator != null || !compatibilityInfo.supportsScreen()) {
Mitsuru Oshima240f8a72009-07-22 20:39:14 -0700347 mSurface.setCompatibleDisplayMetrics(resources.getDisplayMetrics(),
348 mTranslator);
Mitsuru Oshima38ed7d772009-07-21 14:39:34 -0700349 }
350
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -0700351 boolean restore = false;
Romain Guy35b38ce2009-10-07 13:38:55 -0700352 if (mTranslator != null) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -0700353 restore = true;
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700354 attrs.backup();
355 mTranslator.translateWindowLayout(attrs);
Mitsuru Oshima3d914922009-05-13 22:29:15 -0700356 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700357 if (DEBUG_LAYOUT) Log.d(TAG, "WindowLayout in setView:" + attrs);
358
Mitsuru Oshima1ecf5d22009-07-06 17:20:38 -0700359 if (!compatibilityInfo.supportsScreen()) {
360 attrs.flags |= WindowManager.LayoutParams.FLAG_COMPATIBLE_WINDOW;
361 }
362
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800363 mSoftInputMode = attrs.softInputMode;
364 mWindowAttributesChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800365 mAttachInfo.mRootView = view;
Romain Guy35b38ce2009-10-07 13:38:55 -0700366 mAttachInfo.mScalingRequired = mTranslator != null;
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700367 mAttachInfo.mApplicationScale =
368 mTranslator == null ? 1.0f : mTranslator.applicationScale;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800369 if (panelParentView != null) {
370 mAttachInfo.mPanelParentWindowToken
371 = panelParentView.getApplicationWindowToken();
372 }
373 mAdded = true;
374 int res; /* = WindowManagerImpl.ADD_OKAY; */
Romain Guy8506ab42009-06-11 17:35:47 -0700375
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800376 // Schedule the first layout -before- adding to the window
377 // manager, to make sure we do the relayout before receiving
378 // any other events from the system.
379 requestLayout();
Jeff Brown46b9ac02010-04-22 18:58:52 -0700380 mInputChannel = new InputChannel();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800381 try {
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700382 res = sWindowSession.add(mWindow, mWindowAttributes,
Jeff Brown46b9ac02010-04-22 18:58:52 -0700383 getHostVisibility(), mAttachInfo.mContentInsets,
384 mInputChannel);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800385 } catch (RemoteException e) {
386 mAdded = false;
387 mView = null;
388 mAttachInfo.mRootView = null;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700389 mInputChannel = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800390 unscheduleTraversals();
391 throw new RuntimeException("Adding window failed", e);
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700392 } finally {
393 if (restore) {
394 attrs.restore();
395 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800396 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700397
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700398 if (mTranslator != null) {
399 mTranslator.translateRectInScreenToAppWindow(mAttachInfo.mContentInsets);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700400 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800401 mPendingContentInsets.set(mAttachInfo.mContentInsets);
402 mPendingVisibleInsets.set(0, 0, 0, 0);
Jeff Brownc5ed5912010-07-14 18:48:53 -0700403 if (Config.LOGV) Log.v(TAG, "Added window " + mWindow);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800404 if (res < WindowManagerImpl.ADD_OKAY) {
405 mView = null;
406 mAttachInfo.mRootView = null;
407 mAdded = false;
408 unscheduleTraversals();
409 switch (res) {
410 case WindowManagerImpl.ADD_BAD_APP_TOKEN:
411 case WindowManagerImpl.ADD_BAD_SUBWINDOW_TOKEN:
412 throw new WindowManagerImpl.BadTokenException(
413 "Unable to add window -- token " + attrs.token
414 + " is not valid; is your activity running?");
415 case WindowManagerImpl.ADD_NOT_APP_TOKEN:
416 throw new WindowManagerImpl.BadTokenException(
417 "Unable to add window -- token " + attrs.token
418 + " is not for an application");
419 case WindowManagerImpl.ADD_APP_EXITING:
420 throw new WindowManagerImpl.BadTokenException(
421 "Unable to add window -- app for token " + attrs.token
422 + " is exiting");
423 case WindowManagerImpl.ADD_DUPLICATE_ADD:
424 throw new WindowManagerImpl.BadTokenException(
425 "Unable to add window -- window " + mWindow
426 + " has already been added");
427 case WindowManagerImpl.ADD_STARTING_NOT_NEEDED:
428 // Silently ignore -- we would have just removed it
429 // right away, anyway.
430 return;
431 case WindowManagerImpl.ADD_MULTIPLE_SINGLETON:
432 throw new WindowManagerImpl.BadTokenException(
433 "Unable to add window " + mWindow +
434 " -- another window of this type already exists");
435 case WindowManagerImpl.ADD_PERMISSION_DENIED:
436 throw new WindowManagerImpl.BadTokenException(
437 "Unable to add window " + mWindow +
438 " -- permission denied for this window type");
439 }
440 throw new RuntimeException(
441 "Unable to add window -- unknown error code " + res);
442 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700443
Jeff Brown00fa7bd2010-07-02 15:37:36 -0700444 if (view instanceof RootViewSurfaceTaker) {
445 mInputQueueCallback =
446 ((RootViewSurfaceTaker)view).willYouTakeTheInputQueue();
447 }
448 if (mInputQueueCallback != null) {
449 mInputQueue = new InputQueue(mInputChannel);
450 mInputQueueCallback.onInputQueueCreated(mInputQueue);
451 } else {
452 InputQueue.registerInputChannel(mInputChannel, mInputHandler,
453 Looper.myQueue());
Jeff Brown46b9ac02010-04-22 18:58:52 -0700454 }
455
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800456 view.assignParent(this);
457 mAddedTouchMode = (res&WindowManagerImpl.ADD_FLAG_IN_TOUCH_MODE) != 0;
458 mAppVisible = (res&WindowManagerImpl.ADD_FLAG_APP_VISIBLE) != 0;
459 }
460 }
461 }
462
Romain Guy529b60a2010-08-03 18:05:47 -0700463 private void enableHardwareAcceleration(WindowManager.LayoutParams attrs) {
Romain Guye4d01122010-06-16 18:44:05 -0700464 // Only enable hardware acceleration if we are not in the system process
465 // The window manager creates ViewRoots to display animated preview windows
466 // of launching apps and we don't want those to be hardware accelerated
467 if (Process.myUid() != Process.SYSTEM_UID) {
468 // Try to enable hardware acceleration if requested
Romain Guy529b60a2010-08-03 18:05:47 -0700469 if (attrs != null &&
470 (attrs.flags & WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED) != 0) {
Romain Guye4d01122010-06-16 18:44:05 -0700471 final boolean translucent = attrs.format != PixelFormat.OPAQUE;
472 mHwRenderer = HardwareRenderer.createGlRenderer(2, translucent);
473 }
474 }
475 }
476
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800477 public View getView() {
478 return mView;
479 }
480
481 final WindowLeaked getLocation() {
482 return mLocation;
483 }
484
485 void setLayoutParams(WindowManager.LayoutParams attrs, boolean newView) {
486 synchronized (this) {
The Android Open Source Project10592532009-03-18 17:39:46 -0700487 int oldSoftInputMode = mWindowAttributes.softInputMode;
Mitsuru Oshima5a2b91d2009-07-16 16:30:02 -0700488 // preserve compatible window flag if exists.
489 int compatibleWindowFlag =
490 mWindowAttributes.flags & WindowManager.LayoutParams.FLAG_COMPATIBLE_WINDOW;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800491 mWindowAttributes.copyFrom(attrs);
Mitsuru Oshima5a2b91d2009-07-16 16:30:02 -0700492 mWindowAttributes.flags |= compatibleWindowFlag;
493
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800494 if (newView) {
495 mSoftInputMode = attrs.softInputMode;
496 requestLayout();
497 }
The Android Open Source Project10592532009-03-18 17:39:46 -0700498 // Don't lose the mode we last auto-computed.
499 if ((attrs.softInputMode&WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST)
500 == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED) {
501 mWindowAttributes.softInputMode = (mWindowAttributes.softInputMode
502 & ~WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST)
503 | (oldSoftInputMode
504 & WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST);
505 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800506 mWindowAttributesChanged = true;
507 scheduleTraversals();
508 }
509 }
510
511 void handleAppVisibility(boolean visible) {
512 if (mAppVisible != visible) {
513 mAppVisible = visible;
514 scheduleTraversals();
515 }
516 }
517
518 void handleGetNewSurface() {
519 mNewSurfaceNeeded = true;
520 mFullRedrawNeeded = true;
521 scheduleTraversals();
522 }
523
524 /**
525 * {@inheritDoc}
526 */
527 public void requestLayout() {
528 checkThread();
529 mLayoutRequested = true;
530 scheduleTraversals();
531 }
532
533 /**
534 * {@inheritDoc}
535 */
536 public boolean isLayoutRequested() {
537 return mLayoutRequested;
538 }
539
540 public void invalidateChild(View child, Rect dirty) {
541 checkThread();
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700542 if (DEBUG_DRAW) Log.v(TAG, "Invalidate child: " + dirty);
543 if (mCurScrollY != 0 || mTranslator != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800544 mTempRect.set(dirty);
Romain Guy1e095972009-07-07 11:22:45 -0700545 dirty = mTempRect;
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700546 if (mCurScrollY != 0) {
Romain Guy1e095972009-07-07 11:22:45 -0700547 dirty.offset(0, -mCurScrollY);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700548 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700549 if (mTranslator != null) {
Romain Guy1e095972009-07-07 11:22:45 -0700550 mTranslator.translateRectInAppWindowToScreen(dirty);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700551 }
Romain Guy1e095972009-07-07 11:22:45 -0700552 if (mAttachInfo.mScalingRequired) {
553 dirty.inset(-1, -1);
554 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800555 }
556 mDirty.union(dirty);
557 if (!mWillDrawSoon) {
558 scheduleTraversals();
559 }
560 }
561
562 public ViewParent getParent() {
563 return null;
564 }
565
566 public ViewParent invalidateChildInParent(final int[] location, final Rect dirty) {
567 invalidateChild(null, dirty);
568 return null;
569 }
570
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700571 public boolean getChildVisibleRect(View child, Rect r, android.graphics.Point offset) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800572 if (child != mView) {
573 throw new RuntimeException("child is not mine, honest!");
574 }
575 // Note: don't apply scroll offset, because we want to know its
576 // visibility in the virtual canvas being given to the view hierarchy.
577 return r.intersect(0, 0, mWidth, mHeight);
578 }
579
580 public void bringChildToFront(View child) {
581 }
582
583 public void scheduleTraversals() {
584 if (!mTraversalScheduled) {
585 mTraversalScheduled = true;
586 sendEmptyMessage(DO_TRAVERSAL);
587 }
588 }
589
590 public void unscheduleTraversals() {
591 if (mTraversalScheduled) {
592 mTraversalScheduled = false;
593 removeMessages(DO_TRAVERSAL);
594 }
595 }
596
597 int getHostVisibility() {
598 return mAppVisible ? mView.getVisibility() : View.GONE;
599 }
Romain Guy8506ab42009-06-11 17:35:47 -0700600
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800601 private void performTraversals() {
602 // cache mView since it is used so much below...
603 final View host = mView;
604
605 if (DBG) {
606 System.out.println("======================================");
607 System.out.println("performTraversals");
608 host.debug();
609 }
610
611 if (host == null || !mAdded)
612 return;
613
614 mTraversalScheduled = false;
615 mWillDrawSoon = true;
616 boolean windowResizesToFitContent = false;
617 boolean fullRedrawNeeded = mFullRedrawNeeded;
618 boolean newSurface = false;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700619 boolean surfaceChanged = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800620 WindowManager.LayoutParams lp = mWindowAttributes;
621
622 int desiredWindowWidth;
623 int desiredWindowHeight;
624 int childWidthMeasureSpec;
625 int childHeightMeasureSpec;
626
627 final View.AttachInfo attachInfo = mAttachInfo;
628
629 final int viewVisibility = getHostVisibility();
630 boolean viewVisibilityChanged = mViewVisibility != viewVisibility
631 || mNewSurfaceNeeded;
632
633 WindowManager.LayoutParams params = null;
634 if (mWindowAttributesChanged) {
635 mWindowAttributesChanged = false;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700636 surfaceChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800637 params = lp;
638 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700639 Rect frame = mWinFrame;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800640 if (mFirst) {
641 fullRedrawNeeded = true;
642 mLayoutRequested = true;
643
Romain Guy8506ab42009-06-11 17:35:47 -0700644 DisplayMetrics packageMetrics =
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700645 mView.getContext().getResources().getDisplayMetrics();
646 desiredWindowWidth = packageMetrics.widthPixels;
647 desiredWindowHeight = packageMetrics.heightPixels;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800648
649 // For the very first time, tell the view hierarchy that it
650 // is attached to the window. Note that at this point the surface
651 // object is not initialized to its backing store, but soon it
652 // will be (assuming the window is visible).
653 attachInfo.mSurface = mSurface;
Dianne Hackborn289b9b62010-07-09 11:44:11 -0700654 attachInfo.mTranslucentWindow = PixelFormat.formatHasAlpha(lp.format);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800655 attachInfo.mHasWindowFocus = false;
656 attachInfo.mWindowVisibility = viewVisibility;
657 attachInfo.mRecomputeGlobalAttributes = false;
658 attachInfo.mKeepScreenOn = false;
659 viewVisibilityChanged = false;
Dianne Hackborn694f79b2010-03-17 19:44:59 -0700660 mLastConfiguration.setTo(host.getResources().getConfiguration());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800661 host.dispatchAttachedToWindow(attachInfo, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800662 //Log.i(TAG, "Screen on initialized: " + attachInfo.mKeepScreenOn);
svetoslavganov75986cf2009-05-14 22:28:01 -0700663
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800664 } else {
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700665 desiredWindowWidth = frame.width();
666 desiredWindowHeight = frame.height();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800667 if (desiredWindowWidth != mWidth || desiredWindowHeight != mHeight) {
Jeff Brownc5ed5912010-07-14 18:48:53 -0700668 if (DEBUG_ORIENTATION) Log.v(TAG,
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700669 "View " + host + " resized to: " + frame);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800670 fullRedrawNeeded = true;
671 mLayoutRequested = true;
672 windowResizesToFitContent = true;
673 }
674 }
675
676 if (viewVisibilityChanged) {
677 attachInfo.mWindowVisibility = viewVisibility;
678 host.dispatchWindowVisibilityChanged(viewVisibility);
679 if (viewVisibility != View.VISIBLE || mNewSurfaceNeeded) {
Romain Guy812ccbe2010-06-01 14:07:24 -0700680 if (mHwRenderer != null) {
Romain Guy2d614592010-06-09 18:21:37 -0700681 mHwRenderer.destroy();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800682 }
683 }
684 if (viewVisibility == View.GONE) {
685 // After making a window gone, we will count it as being
686 // shown for the first time the next time it gets focus.
687 mHasHadWindowFocus = false;
688 }
689 }
690
691 boolean insetsChanged = false;
Romain Guy8506ab42009-06-11 17:35:47 -0700692
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800693 if (mLayoutRequested) {
Romain Guy15df6702009-08-17 20:17:30 -0700694 // Execute enqueued actions on every layout in case a view that was detached
695 // enqueued an action after being detached
696 getRunQueue().executeActions(attachInfo.mHandler);
697
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800698 if (mFirst) {
699 host.fitSystemWindows(mAttachInfo.mContentInsets);
700 // make sure touch mode code executes by setting cached value
701 // to opposite of the added touch mode.
702 mAttachInfo.mInTouchMode = !mAddedTouchMode;
Romain Guy2d4cff62010-04-09 15:39:00 -0700703 ensureTouchModeLocally(mAddedTouchMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800704 } else {
705 if (!mAttachInfo.mContentInsets.equals(mPendingContentInsets)) {
706 mAttachInfo.mContentInsets.set(mPendingContentInsets);
707 host.fitSystemWindows(mAttachInfo.mContentInsets);
708 insetsChanged = true;
709 if (DEBUG_LAYOUT) Log.v(TAG, "Content insets changing to: "
710 + mAttachInfo.mContentInsets);
711 }
712 if (!mAttachInfo.mVisibleInsets.equals(mPendingVisibleInsets)) {
713 mAttachInfo.mVisibleInsets.set(mPendingVisibleInsets);
714 if (DEBUG_LAYOUT) Log.v(TAG, "Visible insets changing to: "
715 + mAttachInfo.mVisibleInsets);
716 }
717 if (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT
718 || lp.height == ViewGroup.LayoutParams.WRAP_CONTENT) {
719 windowResizesToFitContent = true;
720
Romain Guy8506ab42009-06-11 17:35:47 -0700721 DisplayMetrics packageMetrics =
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700722 mView.getContext().getResources().getDisplayMetrics();
723 desiredWindowWidth = packageMetrics.widthPixels;
724 desiredWindowHeight = packageMetrics.heightPixels;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800725 }
726 }
727
728 childWidthMeasureSpec = getRootMeasureSpec(desiredWindowWidth, lp.width);
729 childHeightMeasureSpec = getRootMeasureSpec(desiredWindowHeight, lp.height);
730
731 // Ask host how big it wants to be
Jeff Brownc5ed5912010-07-14 18:48:53 -0700732 if (DEBUG_ORIENTATION || DEBUG_LAYOUT) Log.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800733 "Measuring " + host + " in display " + desiredWindowWidth
734 + "x" + desiredWindowHeight + "...");
735 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
736
737 if (DBG) {
738 System.out.println("======================================");
739 System.out.println("performTraversals -- after measure");
740 host.debug();
741 }
742 }
743
744 if (attachInfo.mRecomputeGlobalAttributes) {
745 //Log.i(TAG, "Computing screen on!");
746 attachInfo.mRecomputeGlobalAttributes = false;
747 boolean oldVal = attachInfo.mKeepScreenOn;
748 attachInfo.mKeepScreenOn = false;
749 host.dispatchCollectViewAttributes(0);
750 if (attachInfo.mKeepScreenOn != oldVal) {
751 params = lp;
752 //Log.i(TAG, "Keep screen on changed: " + attachInfo.mKeepScreenOn);
753 }
754 }
755
756 if (mFirst || attachInfo.mViewVisibilityChanged) {
757 attachInfo.mViewVisibilityChanged = false;
758 int resizeMode = mSoftInputMode &
759 WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST;
760 // If we are in auto resize mode, then we need to determine
761 // what mode to use now.
762 if (resizeMode == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED) {
763 final int N = attachInfo.mScrollContainers.size();
764 for (int i=0; i<N; i++) {
765 if (attachInfo.mScrollContainers.get(i).isShown()) {
766 resizeMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE;
767 }
768 }
769 if (resizeMode == 0) {
770 resizeMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN;
771 }
772 if ((lp.softInputMode &
773 WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) != resizeMode) {
774 lp.softInputMode = (lp.softInputMode &
775 ~WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) |
776 resizeMode;
777 params = lp;
778 }
779 }
780 }
Romain Guy8506ab42009-06-11 17:35:47 -0700781
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800782 if (params != null && (host.mPrivateFlags & View.REQUEST_TRANSPARENT_REGIONS) != 0) {
783 if (!PixelFormat.formatHasAlpha(params.format)) {
784 params.format = PixelFormat.TRANSLUCENT;
785 }
786 }
787
788 boolean windowShouldResize = mLayoutRequested && windowResizesToFitContent
Romain Guy2e4f4262010-04-06 11:07:52 -0700789 && ((mWidth != host.mMeasuredWidth || mHeight != host.mMeasuredHeight)
790 || (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT &&
791 frame.width() < desiredWindowWidth && frame.width() != mWidth)
792 || (lp.height == ViewGroup.LayoutParams.WRAP_CONTENT &&
793 frame.height() < desiredWindowHeight && frame.height() != mHeight));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800794
795 final boolean computesInternalInsets =
796 attachInfo.mTreeObserver.hasComputeInternalInsetsListeners();
Romain Guy812ccbe2010-06-01 14:07:24 -0700797
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800798 boolean insetsPending = false;
799 int relayoutResult = 0;
Romain Guy812ccbe2010-06-01 14:07:24 -0700800
801 if (mFirst || windowShouldResize || insetsChanged ||
802 viewVisibilityChanged || params != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800803
804 if (viewVisibility == View.VISIBLE) {
805 // If this window is giving internal insets to the window
806 // manager, and it is being added or changing its visibility,
807 // then we want to first give the window manager "fake"
808 // insets to cause it to effectively ignore the content of
809 // the window during layout. This avoids it briefly causing
810 // other windows to resize/move based on the raw frame of the
811 // window, waiting until we can finish laying out this window
812 // and get back to the window manager with the ultimately
813 // computed insets.
Romain Guy812ccbe2010-06-01 14:07:24 -0700814 insetsPending = computesInternalInsets && (mFirst || viewVisibilityChanged);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800815 }
816
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700817 if (mSurfaceHolder != null) {
818 mSurfaceHolder.mSurfaceLock.lock();
819 mDrawingAllowed = true;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700820 }
Romain Guy812ccbe2010-06-01 14:07:24 -0700821
822 boolean hwIntialized = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800823 boolean contentInsetsChanged = false;
Romain Guy13922e02009-05-12 17:56:14 -0700824 boolean visibleInsetsChanged;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700825 boolean hadSurface = mSurface.isValid();
Romain Guy812ccbe2010-06-01 14:07:24 -0700826
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800827 try {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800828 int fl = 0;
829 if (params != null) {
830 fl = params.flags;
831 if (attachInfo.mKeepScreenOn) {
832 params.flags |= WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
833 }
834 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700835 if (DEBUG_LAYOUT) {
836 Log.i(TAG, "host=w:" + host.mMeasuredWidth + ", h:" +
837 host.mMeasuredHeight + ", params=" + params);
838 }
839 relayoutResult = relayoutWindow(params, viewVisibility, insetsPending);
840
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800841 if (params != null) {
842 params.flags = fl;
843 }
844
845 if (DEBUG_LAYOUT) Log.v(TAG, "relayout: frame=" + frame.toShortString()
846 + " content=" + mPendingContentInsets.toShortString()
847 + " visible=" + mPendingVisibleInsets.toShortString()
848 + " surface=" + mSurface);
Romain Guy8506ab42009-06-11 17:35:47 -0700849
Dianne Hackborn694f79b2010-03-17 19:44:59 -0700850 if (mPendingConfiguration.seq != 0) {
851 if (DEBUG_CONFIGURATION) Log.v(TAG, "Visible with new config: "
852 + mPendingConfiguration);
853 updateConfiguration(mPendingConfiguration, !mFirst);
854 mPendingConfiguration.seq = 0;
855 }
856
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800857 contentInsetsChanged = !mPendingContentInsets.equals(
858 mAttachInfo.mContentInsets);
859 visibleInsetsChanged = !mPendingVisibleInsets.equals(
860 mAttachInfo.mVisibleInsets);
861 if (contentInsetsChanged) {
862 mAttachInfo.mContentInsets.set(mPendingContentInsets);
863 host.fitSystemWindows(mAttachInfo.mContentInsets);
864 if (DEBUG_LAYOUT) Log.v(TAG, "Content insets changing to: "
865 + mAttachInfo.mContentInsets);
866 }
867 if (visibleInsetsChanged) {
868 mAttachInfo.mVisibleInsets.set(mPendingVisibleInsets);
869 if (DEBUG_LAYOUT) Log.v(TAG, "Visible insets changing to: "
870 + mAttachInfo.mVisibleInsets);
871 }
872
873 if (!hadSurface) {
874 if (mSurface.isValid()) {
875 // If we are creating a new surface, then we need to
876 // completely redraw it. Also, when we get to the
877 // point of drawing it we will hold off and schedule
878 // a new traversal instead. This is so we can tell the
879 // window manager about all of the windows being displayed
880 // before actually drawing them, so it can display then
881 // all at once.
882 newSurface = true;
883 fullRedrawNeeded = true;
Jack Palevich61a6e682009-10-09 17:37:50 -0700884 mPreviousTransparentRegion.setEmpty();
Romain Guy8506ab42009-06-11 17:35:47 -0700885
Romain Guy812ccbe2010-06-01 14:07:24 -0700886 if (mHwRenderer != null) {
Romain Guy2d614592010-06-09 18:21:37 -0700887 hwIntialized = mHwRenderer.initialize(mHolder);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800888 }
889 }
890 } else if (!mSurface.isValid()) {
891 // If the surface has been removed, then reset the scroll
892 // positions.
893 mLastScrolledFocus = null;
894 mScrollY = mCurScrollY = 0;
895 if (mScroller != null) {
896 mScroller.abortAnimation();
897 }
898 }
899 } catch (RemoteException e) {
900 }
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700901
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800902 if (DEBUG_ORIENTATION) Log.v(
Jeff Brownc5ed5912010-07-14 18:48:53 -0700903 TAG, "Relayout returned: frame=" + frame + ", surface=" + mSurface);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800904
905 attachInfo.mWindowLeft = frame.left;
906 attachInfo.mWindowTop = frame.top;
907
908 // !!FIXME!! This next section handles the case where we did not get the
909 // window size we asked for. We should avoid this by getting a maximum size from
910 // the window session beforehand.
911 mWidth = frame.width();
912 mHeight = frame.height();
913
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700914 if (mSurfaceHolder != null) {
915 // The app owns the surface; tell it about what is going on.
916 if (mSurface.isValid()) {
917 // XXX .copyFrom() doesn't work!
918 //mSurfaceHolder.mSurface.copyFrom(mSurface);
919 mSurfaceHolder.mSurface = mSurface;
920 }
921 mSurfaceHolder.mSurfaceLock.unlock();
922 if (mSurface.isValid()) {
923 if (!hadSurface) {
924 mSurfaceHolder.ungetCallbacks();
925
926 mIsCreating = true;
927 mSurfaceHolderCallback.surfaceCreated(mSurfaceHolder);
928 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
929 if (callbacks != null) {
930 for (SurfaceHolder.Callback c : callbacks) {
931 c.surfaceCreated(mSurfaceHolder);
932 }
933 }
934 surfaceChanged = true;
935 }
936 if (surfaceChanged) {
937 mSurfaceHolderCallback.surfaceChanged(mSurfaceHolder,
938 lp.format, mWidth, mHeight);
939 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
940 if (callbacks != null) {
941 for (SurfaceHolder.Callback c : callbacks) {
942 c.surfaceChanged(mSurfaceHolder, lp.format,
943 mWidth, mHeight);
944 }
945 }
946 }
947 mIsCreating = false;
948 } else if (hadSurface) {
949 mSurfaceHolder.ungetCallbacks();
950 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
951 mSurfaceHolderCallback.surfaceDestroyed(mSurfaceHolder);
952 if (callbacks != null) {
953 for (SurfaceHolder.Callback c : callbacks) {
954 c.surfaceDestroyed(mSurfaceHolder);
955 }
956 }
957 mSurfaceHolder.mSurfaceLock.lock();
958 // Make surface invalid.
959 //mSurfaceHolder.mSurface.copyFrom(mSurface);
960 mSurfaceHolder.mSurface = new Surface();
961 mSurfaceHolder.mSurfaceLock.unlock();
962 }
963 }
964
Romain Guy812ccbe2010-06-01 14:07:24 -0700965 if (hwIntialized) {
Romain Guy2d614592010-06-09 18:21:37 -0700966 mHwRenderer.setup(mWidth, mHeight, mAttachInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800967 }
968
969 boolean focusChangedDueToTouchMode = ensureTouchModeLocally(
Romain Guy2d4cff62010-04-09 15:39:00 -0700970 (relayoutResult&WindowManagerImpl.RELAYOUT_IN_TOUCH_MODE) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800971 if (focusChangedDueToTouchMode || mWidth != host.mMeasuredWidth
972 || mHeight != host.mMeasuredHeight || contentInsetsChanged) {
973 childWidthMeasureSpec = getRootMeasureSpec(mWidth, lp.width);
974 childHeightMeasureSpec = getRootMeasureSpec(mHeight, lp.height);
975
976 if (DEBUG_LAYOUT) Log.v(TAG, "Ooops, something changed! mWidth="
977 + mWidth + " measuredWidth=" + host.mMeasuredWidth
978 + " mHeight=" + mHeight
979 + " measuredHeight" + host.mMeasuredHeight
980 + " coveredInsetsChanged=" + contentInsetsChanged);
Romain Guy8506ab42009-06-11 17:35:47 -0700981
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800982 // Ask host how big it wants to be
983 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
984
985 // Implementation of weights from WindowManager.LayoutParams
986 // We just grow the dimensions as needed and re-measure if
987 // needs be
988 int width = host.mMeasuredWidth;
989 int height = host.mMeasuredHeight;
990 boolean measureAgain = false;
991
992 if (lp.horizontalWeight > 0.0f) {
993 width += (int) ((mWidth - width) * lp.horizontalWeight);
994 childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(width,
995 MeasureSpec.EXACTLY);
996 measureAgain = true;
997 }
998 if (lp.verticalWeight > 0.0f) {
999 height += (int) ((mHeight - height) * lp.verticalWeight);
1000 childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(height,
1001 MeasureSpec.EXACTLY);
1002 measureAgain = true;
1003 }
1004
1005 if (measureAgain) {
1006 if (DEBUG_LAYOUT) Log.v(TAG,
1007 "And hey let's measure once more: width=" + width
1008 + " height=" + height);
1009 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
1010 }
1011
1012 mLayoutRequested = true;
1013 }
1014 }
1015
1016 final boolean didLayout = mLayoutRequested;
1017 boolean triggerGlobalLayoutListener = didLayout
1018 || attachInfo.mRecomputeGlobalAttributes;
1019 if (didLayout) {
1020 mLayoutRequested = false;
1021 mScrollMayChange = true;
1022 if (DEBUG_ORIENTATION || DEBUG_LAYOUT) Log.v(
Jeff Brownc5ed5912010-07-14 18:48:53 -07001023 TAG, "Laying out " + host + " to (" +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001024 host.mMeasuredWidth + ", " + host.mMeasuredHeight + ")");
Romain Guy13922e02009-05-12 17:56:14 -07001025 long startTime = 0L;
1026 if (Config.DEBUG && ViewDebug.profileLayout) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001027 startTime = SystemClock.elapsedRealtime();
1028 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001029 host.layout(0, 0, host.mMeasuredWidth, host.mMeasuredHeight);
1030
Romain Guy13922e02009-05-12 17:56:14 -07001031 if (Config.DEBUG && ViewDebug.consistencyCheckEnabled) {
1032 if (!host.dispatchConsistencyCheck(ViewDebug.CONSISTENCY_LAYOUT)) {
1033 throw new IllegalStateException("The view hierarchy is an inconsistent state,"
1034 + "please refer to the logs with the tag "
1035 + ViewDebug.CONSISTENCY_LOG_TAG + " for more infomation.");
1036 }
1037 }
1038
1039 if (Config.DEBUG && ViewDebug.profileLayout) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001040 EventLog.writeEvent(60001, SystemClock.elapsedRealtime() - startTime);
1041 }
1042
1043 // By this point all views have been sized and positionned
1044 // We can compute the transparent area
1045
1046 if ((host.mPrivateFlags & View.REQUEST_TRANSPARENT_REGIONS) != 0) {
1047 // start out transparent
1048 // TODO: AVOID THAT CALL BY CACHING THE RESULT?
1049 host.getLocationInWindow(mTmpLocation);
1050 mTransparentRegion.set(mTmpLocation[0], mTmpLocation[1],
1051 mTmpLocation[0] + host.mRight - host.mLeft,
1052 mTmpLocation[1] + host.mBottom - host.mTop);
1053
1054 host.gatherTransparentRegion(mTransparentRegion);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001055 if (mTranslator != null) {
1056 mTranslator.translateRegionInWindowToScreen(mTransparentRegion);
1057 }
1058
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001059 if (!mTransparentRegion.equals(mPreviousTransparentRegion)) {
1060 mPreviousTransparentRegion.set(mTransparentRegion);
1061 // reconfigure window manager
1062 try {
1063 sWindowSession.setTransparentRegion(mWindow, mTransparentRegion);
1064 } catch (RemoteException e) {
1065 }
1066 }
1067 }
1068
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001069 if (DBG) {
1070 System.out.println("======================================");
1071 System.out.println("performTraversals -- after setFrame");
1072 host.debug();
1073 }
1074 }
1075
1076 if (triggerGlobalLayoutListener) {
1077 attachInfo.mRecomputeGlobalAttributes = false;
1078 attachInfo.mTreeObserver.dispatchOnGlobalLayout();
1079 }
1080
1081 if (computesInternalInsets) {
1082 ViewTreeObserver.InternalInsetsInfo insets = attachInfo.mGivenInternalInsets;
1083 final Rect givenContent = attachInfo.mGivenInternalInsets.contentInsets;
1084 final Rect givenVisible = attachInfo.mGivenInternalInsets.visibleInsets;
1085 givenContent.left = givenContent.top = givenContent.right
1086 = givenContent.bottom = givenVisible.left = givenVisible.top
1087 = givenVisible.right = givenVisible.bottom = 0;
1088 attachInfo.mTreeObserver.dispatchOnComputeInternalInsets(insets);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001089 Rect contentInsets = insets.contentInsets;
1090 Rect visibleInsets = insets.visibleInsets;
1091 if (mTranslator != null) {
1092 contentInsets = mTranslator.getTranslatedContentInsets(contentInsets);
1093 visibleInsets = mTranslator.getTranslatedVisbileInsets(visibleInsets);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001094 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001095 if (insetsPending || !mLastGivenInsets.equals(insets)) {
1096 mLastGivenInsets.set(insets);
1097 try {
1098 sWindowSession.setInsets(mWindow, insets.mTouchableInsets,
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001099 contentInsets, visibleInsets);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001100 } catch (RemoteException e) {
1101 }
1102 }
1103 }
Romain Guy8506ab42009-06-11 17:35:47 -07001104
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001105 if (mFirst) {
1106 // handle first focus request
1107 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: mView.hasFocus()="
1108 + mView.hasFocus());
1109 if (mView != null) {
1110 if (!mView.hasFocus()) {
1111 mView.requestFocus(View.FOCUS_FORWARD);
1112 mFocusedView = mRealFocusedView = mView.findFocus();
1113 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: requested focused view="
1114 + mFocusedView);
1115 } else {
1116 mRealFocusedView = mView.findFocus();
1117 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: existing focused view="
1118 + mRealFocusedView);
1119 }
1120 }
1121 }
1122
1123 mFirst = false;
1124 mWillDrawSoon = false;
1125 mNewSurfaceNeeded = false;
1126 mViewVisibility = viewVisibility;
1127
1128 if (mAttachInfo.mHasWindowFocus) {
1129 final boolean imTarget = WindowManager.LayoutParams
1130 .mayUseInputMethod(mWindowAttributes.flags);
1131 if (imTarget != mLastWasImTarget) {
1132 mLastWasImTarget = imTarget;
1133 InputMethodManager imm = InputMethodManager.peekInstance();
1134 if (imm != null && imTarget) {
1135 imm.startGettingWindowFocus(mView);
1136 imm.onWindowFocus(mView, mView.findFocus(),
1137 mWindowAttributes.softInputMode,
1138 !mHasHadWindowFocus, mWindowAttributes.flags);
1139 }
1140 }
1141 }
Romain Guy8506ab42009-06-11 17:35:47 -07001142
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001143 boolean cancelDraw = attachInfo.mTreeObserver.dispatchOnPreDraw();
1144
1145 if (!cancelDraw && !newSurface) {
1146 mFullRedrawNeeded = false;
1147 draw(fullRedrawNeeded);
1148
1149 if ((relayoutResult&WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0
1150 || mReportNextDraw) {
1151 if (LOCAL_LOGV) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001152 Log.v(TAG, "FINISHED DRAWING: " + mWindowAttributes.getTitle());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001153 }
1154 mReportNextDraw = false;
Dianne Hackbornd76b67c2010-07-13 17:48:30 -07001155 if (mSurfaceHolder != null && mSurface.isValid()) {
1156 mSurfaceHolderCallback.surfaceRedrawNeeded(mSurfaceHolder);
1157 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
1158 if (callbacks != null) {
1159 for (SurfaceHolder.Callback c : callbacks) {
1160 if (c instanceof SurfaceHolder.Callback2) {
1161 ((SurfaceHolder.Callback2)c).surfaceRedrawNeeded(
1162 mSurfaceHolder);
1163 }
1164 }
1165 }
1166 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001167 try {
1168 sWindowSession.finishDrawing(mWindow);
1169 } catch (RemoteException e) {
1170 }
1171 }
1172 } else {
1173 // We were supposed to report when we are done drawing. Since we canceled the
1174 // draw, remember it here.
1175 if ((relayoutResult&WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0) {
1176 mReportNextDraw = true;
1177 }
1178 if (fullRedrawNeeded) {
1179 mFullRedrawNeeded = true;
1180 }
1181 // Try again
1182 scheduleTraversals();
1183 }
1184 }
1185
1186 public void requestTransparentRegion(View child) {
1187 // the test below should not fail unless someone is messing with us
1188 checkThread();
1189 if (mView == child) {
1190 mView.mPrivateFlags |= View.REQUEST_TRANSPARENT_REGIONS;
1191 // Need to make sure we re-evaluate the window attributes next
1192 // time around, to ensure the window has the correct format.
1193 mWindowAttributesChanged = true;
1194 }
1195 }
1196
1197 /**
1198 * Figures out the measure spec for the root view in a window based on it's
1199 * layout params.
1200 *
1201 * @param windowSize
1202 * The available width or height of the window
1203 *
1204 * @param rootDimension
1205 * The layout params for one dimension (width or height) of the
1206 * window.
1207 *
1208 * @return The measure spec to use to measure the root view.
1209 */
1210 private int getRootMeasureSpec(int windowSize, int rootDimension) {
1211 int measureSpec;
1212 switch (rootDimension) {
1213
Romain Guy980a9382010-01-08 15:06:28 -08001214 case ViewGroup.LayoutParams.MATCH_PARENT:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001215 // Window can't resize. Force root view to be windowSize.
1216 measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.EXACTLY);
1217 break;
1218 case ViewGroup.LayoutParams.WRAP_CONTENT:
1219 // Window can resize. Set max size for root view.
1220 measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.AT_MOST);
1221 break;
1222 default:
1223 // Window wants to be an exact size. Force root view to be that size.
1224 measureSpec = MeasureSpec.makeMeasureSpec(rootDimension, MeasureSpec.EXACTLY);
1225 break;
1226 }
1227 return measureSpec;
1228 }
1229
1230 private void draw(boolean fullRedrawNeeded) {
1231 Surface surface = mSurface;
1232 if (surface == null || !surface.isValid()) {
1233 return;
1234 }
1235
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001236 if (!sFirstDrawComplete) {
1237 synchronized (sFirstDrawHandlers) {
1238 sFirstDrawComplete = true;
Romain Guy812ccbe2010-06-01 14:07:24 -07001239 final int count = sFirstDrawHandlers.size();
1240 for (int i = 0; i< count; i++) {
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001241 post(sFirstDrawHandlers.get(i));
1242 }
1243 }
1244 }
1245
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001246 scrollToRectOrFocus(null, false);
1247
1248 if (mAttachInfo.mViewScrollChanged) {
1249 mAttachInfo.mViewScrollChanged = false;
1250 mAttachInfo.mTreeObserver.dispatchOnScrollChanged();
1251 }
Romain Guy8506ab42009-06-11 17:35:47 -07001252
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001253 int yoff;
Romain Guy5bcdff42009-05-14 21:27:18 -07001254 final boolean scrolling = mScroller != null && mScroller.computeScrollOffset();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001255 if (scrolling) {
1256 yoff = mScroller.getCurrY();
1257 } else {
1258 yoff = mScrollY;
1259 }
1260 if (mCurScrollY != yoff) {
1261 mCurScrollY = yoff;
1262 fullRedrawNeeded = true;
1263 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001264 float appScale = mAttachInfo.mApplicationScale;
1265 boolean scalingRequired = mAttachInfo.mScalingRequired;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001266
1267 Rect dirty = mDirty;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001268 if (mSurfaceHolder != null) {
1269 // The app owns the surface, we won't draw.
1270 dirty.setEmpty();
1271 return;
1272 }
1273
Romain Guy2d614592010-06-09 18:21:37 -07001274 if (mHwRenderer != null && mHwRenderer.isEnabled()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001275 if (!dirty.isEmpty()) {
Romain Guydbd77cd2010-07-09 10:36:05 -07001276 mHwRenderer.draw(mView, mAttachInfo, yoff);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001277 }
Romain Guy812ccbe2010-06-01 14:07:24 -07001278
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001279 if (scrolling) {
1280 mFullRedrawNeeded = true;
1281 scheduleTraversals();
1282 }
Romain Guy812ccbe2010-06-01 14:07:24 -07001283
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001284 return;
1285 }
1286
Romain Guy5bcdff42009-05-14 21:27:18 -07001287 if (fullRedrawNeeded) {
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001288 mAttachInfo.mIgnoreDirtyState = true;
Mitsuru Oshima61324e52009-07-21 15:40:36 -07001289 dirty.union(0, 0, (int) (mWidth * appScale + 0.5f), (int) (mHeight * appScale + 0.5f));
Romain Guy5bcdff42009-05-14 21:27:18 -07001290 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001291
1292 if (DEBUG_ORIENTATION || DEBUG_DRAW) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001293 Log.v(TAG, "Draw " + mView + "/"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001294 + mWindowAttributes.getTitle()
1295 + ": dirty={" + dirty.left + "," + dirty.top
1296 + "," + dirty.right + "," + dirty.bottom + "} surface="
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001297 + surface + " surface.isValid()=" + surface.isValid() + ", appScale:" +
1298 appScale + ", width=" + mWidth + ", height=" + mHeight);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001299 }
1300
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001301 if (!dirty.isEmpty() || mIsAnimating) {
1302 Canvas canvas;
1303 try {
1304 int left = dirty.left;
1305 int top = dirty.top;
1306 int right = dirty.right;
1307 int bottom = dirty.bottom;
1308 canvas = surface.lockCanvas(dirty);
Romain Guy5bcdff42009-05-14 21:27:18 -07001309
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001310 if (left != dirty.left || top != dirty.top || right != dirty.right ||
1311 bottom != dirty.bottom) {
1312 mAttachInfo.mIgnoreDirtyState = true;
1313 }
1314
1315 // TODO: Do this in native
1316 canvas.setDensity(mDensity);
1317 } catch (Surface.OutOfResourcesException e) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001318 Log.e(TAG, "OutOfResourcesException locking surface", e);
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001319 // TODO: we should ask the window manager to do something!
1320 // for now we just do nothing
1321 return;
1322 } catch (IllegalArgumentException e) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001323 Log.e(TAG, "IllegalArgumentException locking surface", e);
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001324 // TODO: we should ask the window manager to do something!
1325 // for now we just do nothing
1326 return;
Romain Guy5bcdff42009-05-14 21:27:18 -07001327 }
1328
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001329 try {
1330 if (!dirty.isEmpty() || mIsAnimating) {
1331 long startTime = 0L;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001332
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001333 if (DEBUG_ORIENTATION || DEBUG_DRAW) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001334 Log.v(TAG, "Surface " + surface + " drawing to bitmap w="
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001335 + canvas.getWidth() + ", h=" + canvas.getHeight());
1336 //canvas.drawARGB(255, 255, 0, 0);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001337 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001338
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001339 if (Config.DEBUG && ViewDebug.profileDrawing) {
1340 startTime = SystemClock.elapsedRealtime();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001341 }
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001342
1343 // If this bitmap's format includes an alpha channel, we
1344 // need to clear it before drawing so that the child will
1345 // properly re-composite its drawing on a transparent
1346 // background. This automatically respects the clip/dirty region
1347 // or
1348 // If we are applying an offset, we need to clear the area
1349 // where the offset doesn't appear to avoid having garbage
1350 // left in the blank areas.
1351 if (!canvas.isOpaque() || yoff != 0) {
1352 canvas.drawColor(0, PorterDuff.Mode.CLEAR);
1353 }
1354
1355 dirty.setEmpty();
1356 mIsAnimating = false;
1357 mAttachInfo.mDrawingTime = SystemClock.uptimeMillis();
1358 mView.mPrivateFlags |= View.DRAWN;
1359
1360 if (DEBUG_DRAW) {
1361 Context cxt = mView.getContext();
1362 Log.i(TAG, "Drawing: package:" + cxt.getPackageName() +
1363 ", metrics=" + cxt.getResources().getDisplayMetrics() +
1364 ", compatibilityInfo=" + cxt.getResources().getCompatibilityInfo());
1365 }
1366 int saveCount = canvas.save(Canvas.MATRIX_SAVE_FLAG);
1367 try {
1368 canvas.translate(0, -yoff);
1369 if (mTranslator != null) {
1370 mTranslator.translateCanvas(canvas);
1371 }
1372 canvas.setScreenDensity(scalingRequired
1373 ? DisplayMetrics.DENSITY_DEVICE : 0);
1374 mView.draw(canvas);
1375 } finally {
1376 mAttachInfo.mIgnoreDirtyState = false;
1377 canvas.restoreToCount(saveCount);
1378 }
1379
1380 if (Config.DEBUG && ViewDebug.consistencyCheckEnabled) {
1381 mView.dispatchConsistencyCheck(ViewDebug.CONSISTENCY_DRAWING);
1382 }
1383
1384 if (SHOW_FPS || Config.DEBUG && ViewDebug.showFps) {
1385 int now = (int)SystemClock.elapsedRealtime();
1386 if (sDrawTime != 0) {
1387 nativeShowFPS(canvas, now - sDrawTime);
1388 }
1389 sDrawTime = now;
1390 }
1391
1392 if (Config.DEBUG && ViewDebug.profileDrawing) {
1393 EventLog.writeEvent(60000, SystemClock.elapsedRealtime() - startTime);
1394 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001395 }
1396
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001397 } finally {
1398 surface.unlockCanvasAndPost(canvas);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001399 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001400 }
1401
1402 if (LOCAL_LOGV) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001403 Log.v(TAG, "Surface " + surface + " unlockCanvasAndPost");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001404 }
Romain Guy8506ab42009-06-11 17:35:47 -07001405
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001406 if (scrolling) {
1407 mFullRedrawNeeded = true;
1408 scheduleTraversals();
1409 }
1410 }
1411
1412 boolean scrollToRectOrFocus(Rect rectangle, boolean immediate) {
1413 final View.AttachInfo attachInfo = mAttachInfo;
1414 final Rect ci = attachInfo.mContentInsets;
1415 final Rect vi = attachInfo.mVisibleInsets;
1416 int scrollY = 0;
1417 boolean handled = false;
Romain Guy8506ab42009-06-11 17:35:47 -07001418
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001419 if (vi.left > ci.left || vi.top > ci.top
1420 || vi.right > ci.right || vi.bottom > ci.bottom) {
1421 // We'll assume that we aren't going to change the scroll
1422 // offset, since we want to avoid that unless it is actually
1423 // going to make the focus visible... otherwise we scroll
1424 // all over the place.
1425 scrollY = mScrollY;
1426 // We can be called for two different situations: during a draw,
1427 // to update the scroll position if the focus has changed (in which
1428 // case 'rectangle' is null), or in response to a
1429 // requestChildRectangleOnScreen() call (in which case 'rectangle'
1430 // is non-null and we just want to scroll to whatever that
1431 // rectangle is).
1432 View focus = mRealFocusedView;
Romain Guye8b16522009-07-14 13:06:42 -07001433
1434 // When in touch mode, focus points to the previously focused view,
1435 // which may have been removed from the view hierarchy. The following
Joe Onoratob71193b2009-11-24 18:34:42 -05001436 // line checks whether the view is still in our hierarchy.
1437 if (focus == null || focus.mAttachInfo != mAttachInfo) {
Romain Guye8b16522009-07-14 13:06:42 -07001438 mRealFocusedView = null;
1439 return false;
1440 }
1441
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001442 if (focus != mLastScrolledFocus) {
1443 // If the focus has changed, then ignore any requests to scroll
1444 // to a rectangle; first we want to make sure the entire focus
1445 // view is visible.
1446 rectangle = null;
1447 }
1448 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Eval scroll: focus=" + focus
1449 + " rectangle=" + rectangle + " ci=" + ci
1450 + " vi=" + vi);
1451 if (focus == mLastScrolledFocus && !mScrollMayChange
1452 && rectangle == null) {
1453 // Optimization: if the focus hasn't changed since last
1454 // time, and no layout has happened, then just leave things
1455 // as they are.
1456 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Keeping scroll y="
1457 + mScrollY + " vi=" + vi.toShortString());
1458 } else if (focus != null) {
1459 // We need to determine if the currently focused view is
1460 // within the visible part of the window and, if not, apply
1461 // a pan so it can be seen.
1462 mLastScrolledFocus = focus;
1463 mScrollMayChange = false;
1464 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Need to scroll?");
1465 // Try to find the rectangle from the focus view.
1466 if (focus.getGlobalVisibleRect(mVisRect, null)) {
1467 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Root w="
1468 + mView.getWidth() + " h=" + mView.getHeight()
1469 + " ci=" + ci.toShortString()
1470 + " vi=" + vi.toShortString());
1471 if (rectangle == null) {
1472 focus.getFocusedRect(mTempRect);
1473 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Focus " + focus
1474 + ": focusRect=" + mTempRect.toShortString());
Dianne Hackborn1c6a8942010-03-23 16:34:20 -07001475 if (mView instanceof ViewGroup) {
1476 ((ViewGroup) mView).offsetDescendantRectToMyCoords(
1477 focus, mTempRect);
1478 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001479 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1480 "Focus in window: focusRect="
1481 + mTempRect.toShortString()
1482 + " visRect=" + mVisRect.toShortString());
1483 } else {
1484 mTempRect.set(rectangle);
1485 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1486 "Request scroll to rect: "
1487 + mTempRect.toShortString()
1488 + " visRect=" + mVisRect.toShortString());
1489 }
1490 if (mTempRect.intersect(mVisRect)) {
1491 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1492 "Focus window visible rect: "
1493 + mTempRect.toShortString());
1494 if (mTempRect.height() >
1495 (mView.getHeight()-vi.top-vi.bottom)) {
1496 // If the focus simply is not going to fit, then
1497 // best is probably just to leave things as-is.
1498 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1499 "Too tall; leaving scrollY=" + scrollY);
1500 } else if ((mTempRect.top-scrollY) < vi.top) {
1501 scrollY -= vi.top - (mTempRect.top-scrollY);
1502 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1503 "Top covered; scrollY=" + scrollY);
1504 } else if ((mTempRect.bottom-scrollY)
1505 > (mView.getHeight()-vi.bottom)) {
1506 scrollY += (mTempRect.bottom-scrollY)
1507 - (mView.getHeight()-vi.bottom);
1508 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1509 "Bottom covered; scrollY=" + scrollY);
1510 }
1511 handled = true;
1512 }
1513 }
1514 }
1515 }
Romain Guy8506ab42009-06-11 17:35:47 -07001516
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001517 if (scrollY != mScrollY) {
1518 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Pan scroll changed: old="
1519 + mScrollY + " , new=" + scrollY);
1520 if (!immediate) {
1521 if (mScroller == null) {
1522 mScroller = new Scroller(mView.getContext());
1523 }
1524 mScroller.startScroll(0, mScrollY, 0, scrollY-mScrollY);
1525 } else if (mScroller != null) {
1526 mScroller.abortAnimation();
1527 }
1528 mScrollY = scrollY;
1529 }
Romain Guy8506ab42009-06-11 17:35:47 -07001530
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001531 return handled;
1532 }
Romain Guy8506ab42009-06-11 17:35:47 -07001533
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001534 public void requestChildFocus(View child, View focused) {
1535 checkThread();
1536 if (mFocusedView != focused) {
1537 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(mFocusedView, focused);
1538 scheduleTraversals();
1539 }
1540 mFocusedView = mRealFocusedView = focused;
1541 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Request child focus: focus now "
1542 + mFocusedView);
1543 }
1544
1545 public void clearChildFocus(View child) {
1546 checkThread();
1547
1548 View oldFocus = mFocusedView;
1549
1550 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Clearing child focus");
1551 mFocusedView = mRealFocusedView = null;
1552 if (mView != null && !mView.hasFocus()) {
1553 // If a view gets the focus, the listener will be invoked from requestChildFocus()
1554 if (!mView.requestFocus(View.FOCUS_FORWARD)) {
1555 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
1556 }
1557 } else if (oldFocus != null) {
1558 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
1559 }
1560 }
1561
1562
1563 public void focusableViewAvailable(View v) {
1564 checkThread();
1565
1566 if (mView != null && !mView.hasFocus()) {
1567 v.requestFocus();
1568 } else {
1569 // the one case where will transfer focus away from the current one
1570 // is if the current view is a view group that prefers to give focus
1571 // to its children first AND the view is a descendant of it.
1572 mFocusedView = mView.findFocus();
1573 boolean descendantsHaveDibsOnFocus =
1574 (mFocusedView instanceof ViewGroup) &&
1575 (((ViewGroup) mFocusedView).getDescendantFocusability() ==
1576 ViewGroup.FOCUS_AFTER_DESCENDANTS);
1577 if (descendantsHaveDibsOnFocus && isViewDescendantOf(v, mFocusedView)) {
1578 // If a view gets the focus, the listener will be invoked from requestChildFocus()
1579 v.requestFocus();
1580 }
1581 }
1582 }
1583
1584 public void recomputeViewAttributes(View child) {
1585 checkThread();
1586 if (mView == child) {
1587 mAttachInfo.mRecomputeGlobalAttributes = true;
1588 if (!mWillDrawSoon) {
1589 scheduleTraversals();
1590 }
1591 }
1592 }
1593
1594 void dispatchDetachedFromWindow() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001595 if (mView != null) {
1596 mView.dispatchDetachedFromWindow();
1597 }
1598
1599 mView = null;
1600 mAttachInfo.mRootView = null;
Mathias Agopian5583dc62009-07-09 16:28:11 -07001601 mAttachInfo.mSurface = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001602
Romain Guy812ccbe2010-06-01 14:07:24 -07001603 if (mHwRenderer != null) {
Romain Guy2d614592010-06-09 18:21:37 -07001604 mHwRenderer.destroy();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001605 }
Dianne Hackborn0586a1b2009-09-06 21:08:27 -07001606 mSurface.release();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001607
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001608 if (mInputChannel != null) {
1609 if (mInputQueueCallback != null) {
1610 mInputQueueCallback.onInputQueueDestroyed(mInputQueue);
1611 mInputQueueCallback = null;
1612 } else {
1613 InputQueue.unregisterInputChannel(mInputChannel);
Jeff Brown46b9ac02010-04-22 18:58:52 -07001614 }
1615 }
1616
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001617 try {
1618 sWindowSession.remove(mWindow);
1619 } catch (RemoteException e) {
1620 }
Jeff Brown349703e2010-06-22 01:27:15 -07001621
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001622 // Dispose the input channel after removing the window so the Window Manager
1623 // doesn't interpret the input channel being closed as an abnormal termination.
1624 if (mInputChannel != null) {
1625 mInputChannel.dispose();
1626 mInputChannel = null;
Jeff Brown349703e2010-06-22 01:27:15 -07001627 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001628 }
Romain Guy8506ab42009-06-11 17:35:47 -07001629
Dianne Hackborn694f79b2010-03-17 19:44:59 -07001630 void updateConfiguration(Configuration config, boolean force) {
1631 if (DEBUG_CONFIGURATION) Log.v(TAG,
1632 "Applying new config to window "
1633 + mWindowAttributes.getTitle()
1634 + ": " + config);
1635 synchronized (sConfigCallbacks) {
1636 for (int i=sConfigCallbacks.size()-1; i>=0; i--) {
1637 sConfigCallbacks.get(i).onConfigurationChanged(config);
1638 }
1639 }
1640 if (mView != null) {
1641 // At this point the resources have been updated to
1642 // have the most recent config, whatever that is. Use
1643 // the on in them which may be newer.
1644 if (mView != null) {
1645 config = mView.getResources().getConfiguration();
1646 }
1647 if (force || mLastConfiguration.diff(config) != 0) {
1648 mLastConfiguration.setTo(config);
1649 mView.dispatchConfigurationChanged(config);
1650 }
1651 }
1652 }
1653
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001654 /**
1655 * Return true if child is an ancestor of parent, (or equal to the parent).
1656 */
1657 private static boolean isViewDescendantOf(View child, View parent) {
1658 if (child == parent) {
1659 return true;
1660 }
1661
1662 final ViewParent theParent = child.getParent();
1663 return (theParent instanceof ViewGroup) && isViewDescendantOf((View) theParent, parent);
1664 }
1665
Romain Guycdb86672010-03-18 18:54:50 -07001666 private static void forceLayout(View view) {
1667 view.forceLayout();
1668 if (view instanceof ViewGroup) {
1669 ViewGroup group = (ViewGroup) view;
1670 final int count = group.getChildCount();
1671 for (int i = 0; i < count; i++) {
1672 forceLayout(group.getChildAt(i));
1673 }
1674 }
1675 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001676
1677 public final static int DO_TRAVERSAL = 1000;
1678 public final static int DIE = 1001;
1679 public final static int RESIZED = 1002;
1680 public final static int RESIZED_REPORT = 1003;
1681 public final static int WINDOW_FOCUS_CHANGED = 1004;
1682 public final static int DISPATCH_KEY = 1005;
1683 public final static int DISPATCH_POINTER = 1006;
1684 public final static int DISPATCH_TRACKBALL = 1007;
1685 public final static int DISPATCH_APP_VISIBILITY = 1008;
1686 public final static int DISPATCH_GET_NEW_SURFACE = 1009;
1687 public final static int FINISHED_EVENT = 1010;
1688 public final static int DISPATCH_KEY_FROM_IME = 1011;
1689 public final static int FINISH_INPUT_CONNECTION = 1012;
1690 public final static int CHECK_FOCUS = 1013;
Dianne Hackbornffa42482009-09-23 22:20:11 -07001691 public final static int CLOSE_SYSTEM_DIALOGS = 1014;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001692
1693 @Override
1694 public void handleMessage(Message msg) {
1695 switch (msg.what) {
1696 case View.AttachInfo.INVALIDATE_MSG:
1697 ((View) msg.obj).invalidate();
1698 break;
1699 case View.AttachInfo.INVALIDATE_RECT_MSG:
1700 final View.AttachInfo.InvalidateInfo info = (View.AttachInfo.InvalidateInfo) msg.obj;
1701 info.target.invalidate(info.left, info.top, info.right, info.bottom);
1702 info.release();
1703 break;
1704 case DO_TRAVERSAL:
1705 if (mProfile) {
1706 Debug.startMethodTracing("ViewRoot");
1707 }
1708
1709 performTraversals();
1710
1711 if (mProfile) {
1712 Debug.stopMethodTracing();
1713 mProfile = false;
1714 }
1715 break;
1716 case FINISHED_EVENT:
1717 handleFinishedEvent(msg.arg1, msg.arg2 != 0);
1718 break;
1719 case DISPATCH_KEY:
1720 if (LOCAL_LOGV) Log.v(
Jeff Brownc5ed5912010-07-14 18:48:53 -07001721 TAG, "Dispatching key "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001722 + msg.obj + " to " + mView);
Jeff Brown92ff1dd2010-08-11 16:16:06 -07001723 deliverKeyEvent((KeyEvent)msg.obj, msg.arg1 != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001724 break;
The Android Open Source Project10592532009-03-18 17:39:46 -07001725 case DISPATCH_POINTER: {
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001726 MotionEvent event = (MotionEvent) msg.obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001727 try {
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001728 deliverPointerEvent(event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001729 } finally {
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001730 event.recycle();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001731 if (LOCAL_LOGV || WATCH_POINTER) Log.i(TAG, "Done dispatching!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001732 }
The Android Open Source Project10592532009-03-18 17:39:46 -07001733 } break;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001734 case DISPATCH_TRACKBALL: {
1735 MotionEvent event = (MotionEvent) msg.obj;
1736 try {
1737 deliverTrackballEvent(event);
1738 } finally {
1739 event.recycle();
1740 }
1741 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001742 case DISPATCH_APP_VISIBILITY:
1743 handleAppVisibility(msg.arg1 != 0);
1744 break;
1745 case DISPATCH_GET_NEW_SURFACE:
1746 handleGetNewSurface();
1747 break;
1748 case RESIZED:
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001749 ResizedInfo ri = (ResizedInfo)msg.obj;
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001750
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001751 if (mWinFrame.width() == msg.arg1 && mWinFrame.height() == msg.arg2
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001752 && mPendingContentInsets.equals(ri.coveredInsets)
Dianne Hackbornd49258f2010-03-26 00:44:29 -07001753 && mPendingVisibleInsets.equals(ri.visibleInsets)
1754 && ((ResizedInfo)msg.obj).newConfig == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001755 break;
1756 }
1757 // fall through...
1758 case RESIZED_REPORT:
1759 if (mAdded) {
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001760 Configuration config = ((ResizedInfo)msg.obj).newConfig;
1761 if (config != null) {
Dianne Hackborn694f79b2010-03-17 19:44:59 -07001762 updateConfiguration(config, false);
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001763 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001764 mWinFrame.left = 0;
1765 mWinFrame.right = msg.arg1;
1766 mWinFrame.top = 0;
1767 mWinFrame.bottom = msg.arg2;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001768 mPendingContentInsets.set(((ResizedInfo)msg.obj).coveredInsets);
1769 mPendingVisibleInsets.set(((ResizedInfo)msg.obj).visibleInsets);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001770 if (msg.what == RESIZED_REPORT) {
1771 mReportNextDraw = true;
1772 }
Romain Guycdb86672010-03-18 18:54:50 -07001773
1774 if (mView != null) {
1775 forceLayout(mView);
1776 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001777 requestLayout();
1778 }
1779 break;
1780 case WINDOW_FOCUS_CHANGED: {
1781 if (mAdded) {
1782 boolean hasWindowFocus = msg.arg1 != 0;
1783 mAttachInfo.mHasWindowFocus = hasWindowFocus;
1784 if (hasWindowFocus) {
1785 boolean inTouchMode = msg.arg2 != 0;
Romain Guy2d4cff62010-04-09 15:39:00 -07001786 ensureTouchModeLocally(inTouchMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001787
Romain Guy812ccbe2010-06-01 14:07:24 -07001788 if (mHwRenderer != null) {
Romain Guy2d614592010-06-09 18:21:37 -07001789 mHwRenderer.initializeIfNeeded(mWidth, mHeight, mAttachInfo, mHolder);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001790 }
1791 }
Romain Guy8506ab42009-06-11 17:35:47 -07001792
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001793 mLastWasImTarget = WindowManager.LayoutParams
1794 .mayUseInputMethod(mWindowAttributes.flags);
Romain Guy8506ab42009-06-11 17:35:47 -07001795
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001796 InputMethodManager imm = InputMethodManager.peekInstance();
1797 if (mView != null) {
1798 if (hasWindowFocus && imm != null && mLastWasImTarget) {
1799 imm.startGettingWindowFocus(mView);
1800 }
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07001801 mAttachInfo.mKeyDispatchState.reset();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001802 mView.dispatchWindowFocusChanged(hasWindowFocus);
1803 }
svetoslavganov75986cf2009-05-14 22:28:01 -07001804
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001805 // Note: must be done after the focus change callbacks,
1806 // so all of the view state is set up correctly.
1807 if (hasWindowFocus) {
1808 if (imm != null && mLastWasImTarget) {
1809 imm.onWindowFocus(mView, mView.findFocus(),
1810 mWindowAttributes.softInputMode,
1811 !mHasHadWindowFocus, mWindowAttributes.flags);
1812 }
1813 // Clear the forward bit. We can just do this directly, since
1814 // the window manager doesn't care about it.
1815 mWindowAttributes.softInputMode &=
1816 ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
1817 ((WindowManager.LayoutParams)mView.getLayoutParams())
1818 .softInputMode &=
1819 ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
1820 mHasHadWindowFocus = true;
1821 }
svetoslavganov75986cf2009-05-14 22:28:01 -07001822
1823 if (hasWindowFocus && mView != null) {
1824 sendAccessibilityEvents();
1825 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001826 }
1827 } break;
1828 case DIE:
Dianne Hackborn94d69142009-09-28 22:14:42 -07001829 doDie();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001830 break;
The Android Open Source Project10592532009-03-18 17:39:46 -07001831 case DISPATCH_KEY_FROM_IME: {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001832 if (LOCAL_LOGV) Log.v(
Jeff Brownc5ed5912010-07-14 18:48:53 -07001833 TAG, "Dispatching key "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001834 + msg.obj + " from IME to " + mView);
The Android Open Source Project10592532009-03-18 17:39:46 -07001835 KeyEvent event = (KeyEvent)msg.obj;
1836 if ((event.getFlags()&KeyEvent.FLAG_FROM_SYSTEM) != 0) {
1837 // The IME is trying to say this event is from the
1838 // system! Bad bad bad!
Romain Guy812ccbe2010-06-01 14:07:24 -07001839 event = KeyEvent.changeFlags(event, event.getFlags() & ~KeyEvent.FLAG_FROM_SYSTEM);
The Android Open Source Project10592532009-03-18 17:39:46 -07001840 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001841 deliverKeyEventToViewHierarchy((KeyEvent)msg.obj, false);
The Android Open Source Project10592532009-03-18 17:39:46 -07001842 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001843 case FINISH_INPUT_CONNECTION: {
1844 InputMethodManager imm = InputMethodManager.peekInstance();
1845 if (imm != null) {
1846 imm.reportFinishInputConnection((InputConnection)msg.obj);
1847 }
1848 } break;
1849 case CHECK_FOCUS: {
1850 InputMethodManager imm = InputMethodManager.peekInstance();
1851 if (imm != null) {
1852 imm.checkFocus();
1853 }
1854 } break;
Dianne Hackbornffa42482009-09-23 22:20:11 -07001855 case CLOSE_SYSTEM_DIALOGS: {
1856 if (mView != null) {
1857 mView.onCloseSystemDialogs((String)msg.obj);
1858 }
1859 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001860 }
1861 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07001862
1863 private void finishKeyEvent(KeyEvent event) {
Jeff Brown92ff1dd2010-08-11 16:16:06 -07001864 if (LOCAL_LOGV) Log.v(TAG, "Telling window manager key is finished");
1865
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001866 if (mFinishedCallback != null) {
1867 mFinishedCallback.run();
1868 mFinishedCallback = null;
Jeff Brown92ff1dd2010-08-11 16:16:06 -07001869 } else {
1870 Slog.w(TAG, "Attempted to tell the input queue that the current key event "
1871 + "is finished but there is no key event actually in progress.");
Jeff Brown46b9ac02010-04-22 18:58:52 -07001872 }
1873 }
1874
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001875 /**
1876 * Something in the current window tells us we need to change the touch mode. For
1877 * example, we are not in touch mode, and the user touches the screen.
1878 *
1879 * If the touch mode has changed, tell the window manager, and handle it locally.
1880 *
1881 * @param inTouchMode Whether we want to be in touch mode.
1882 * @return True if the touch mode changed and focus changed was changed as a result
1883 */
1884 boolean ensureTouchMode(boolean inTouchMode) {
1885 if (DBG) Log.d("touchmode", "ensureTouchMode(" + inTouchMode + "), current "
1886 + "touch mode is " + mAttachInfo.mInTouchMode);
1887 if (mAttachInfo.mInTouchMode == inTouchMode) return false;
1888
1889 // tell the window manager
1890 try {
1891 sWindowSession.setInTouchMode(inTouchMode);
1892 } catch (RemoteException e) {
1893 throw new RuntimeException(e);
1894 }
1895
1896 // handle the change
Romain Guy2d4cff62010-04-09 15:39:00 -07001897 return ensureTouchModeLocally(inTouchMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001898 }
1899
1900 /**
1901 * Ensure that the touch mode for this window is set, and if it is changing,
1902 * take the appropriate action.
1903 * @param inTouchMode Whether we want to be in touch mode.
1904 * @return True if the touch mode changed and focus changed was changed as a result
1905 */
Romain Guy2d4cff62010-04-09 15:39:00 -07001906 private boolean ensureTouchModeLocally(boolean inTouchMode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001907 if (DBG) Log.d("touchmode", "ensureTouchModeLocally(" + inTouchMode + "), current "
1908 + "touch mode is " + mAttachInfo.mInTouchMode);
1909
1910 if (mAttachInfo.mInTouchMode == inTouchMode) return false;
1911
1912 mAttachInfo.mInTouchMode = inTouchMode;
1913 mAttachInfo.mTreeObserver.dispatchOnTouchModeChanged(inTouchMode);
1914
Romain Guy2d4cff62010-04-09 15:39:00 -07001915 return (inTouchMode) ? enterTouchMode() : leaveTouchMode();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001916 }
1917
1918 private boolean enterTouchMode() {
1919 if (mView != null) {
1920 if (mView.hasFocus()) {
1921 // note: not relying on mFocusedView here because this could
1922 // be when the window is first being added, and mFocused isn't
1923 // set yet.
1924 final View focused = mView.findFocus();
1925 if (focused != null && !focused.isFocusableInTouchMode()) {
1926
1927 final ViewGroup ancestorToTakeFocus =
1928 findAncestorToTakeFocusInTouchMode(focused);
1929 if (ancestorToTakeFocus != null) {
1930 // there is an ancestor that wants focus after its descendants that
1931 // is focusable in touch mode.. give it focus
1932 return ancestorToTakeFocus.requestFocus();
1933 } else {
1934 // nothing appropriate to have focus in touch mode, clear it out
1935 mView.unFocus();
1936 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(focused, null);
1937 mFocusedView = null;
1938 return true;
1939 }
1940 }
1941 }
1942 }
1943 return false;
1944 }
1945
1946
1947 /**
1948 * Find an ancestor of focused that wants focus after its descendants and is
1949 * focusable in touch mode.
1950 * @param focused The currently focused view.
1951 * @return An appropriate view, or null if no such view exists.
1952 */
1953 private ViewGroup findAncestorToTakeFocusInTouchMode(View focused) {
1954 ViewParent parent = focused.getParent();
1955 while (parent instanceof ViewGroup) {
1956 final ViewGroup vgParent = (ViewGroup) parent;
1957 if (vgParent.getDescendantFocusability() == ViewGroup.FOCUS_AFTER_DESCENDANTS
1958 && vgParent.isFocusableInTouchMode()) {
1959 return vgParent;
1960 }
1961 if (vgParent.isRootNamespace()) {
1962 return null;
1963 } else {
1964 parent = vgParent.getParent();
1965 }
1966 }
1967 return null;
1968 }
1969
1970 private boolean leaveTouchMode() {
1971 if (mView != null) {
1972 if (mView.hasFocus()) {
1973 // i learned the hard way to not trust mFocusedView :)
1974 mFocusedView = mView.findFocus();
1975 if (!(mFocusedView instanceof ViewGroup)) {
1976 // some view has focus, let it keep it
1977 return false;
1978 } else if (((ViewGroup)mFocusedView).getDescendantFocusability() !=
1979 ViewGroup.FOCUS_AFTER_DESCENDANTS) {
1980 // some view group has focus, and doesn't prefer its children
1981 // over itself for focus, so let them keep it.
1982 return false;
1983 }
1984 }
1985
1986 // find the best view to give focus to in this brave new non-touch-mode
1987 // world
1988 final View focused = focusSearch(null, View.FOCUS_DOWN);
1989 if (focused != null) {
1990 return focused.requestFocus(View.FOCUS_DOWN);
1991 }
1992 }
1993 return false;
1994 }
1995
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001996 private void deliverPointerEvent(MotionEvent event) {
1997 if (mTranslator != null) {
1998 mTranslator.translateEventInScreenToAppWindow(event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001999 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002000
2001 boolean handled;
2002 if (mView != null && mAdded) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002003
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002004 // enter touch mode on the down
2005 boolean isDown = event.getAction() == MotionEvent.ACTION_DOWN;
2006 if (isDown) {
2007 ensureTouchMode(true);
2008 }
2009 if(Config.LOGV) {
2010 captureMotionLog("captureDispatchPointer", event);
2011 }
2012 if (mCurScrollY != 0) {
2013 event.offsetLocation(0, mCurScrollY);
2014 }
2015 if (MEASURE_LATENCY) {
2016 lt.sample("A Dispatching TouchEvents", System.nanoTime() - event.getEventTimeNano());
2017 }
2018 handled = mView.dispatchTouchEvent(event);
2019 if (MEASURE_LATENCY) {
2020 lt.sample("B Dispatched TouchEvents ", System.nanoTime() - event.getEventTimeNano());
2021 }
2022 if (!handled && isDown) {
2023 int edgeSlop = mViewConfiguration.getScaledEdgeSlop();
2024
2025 final int edgeFlags = event.getEdgeFlags();
2026 int direction = View.FOCUS_UP;
2027 int x = (int)event.getX();
2028 int y = (int)event.getY();
2029 final int[] deltas = new int[2];
2030
2031 if ((edgeFlags & MotionEvent.EDGE_TOP) != 0) {
2032 direction = View.FOCUS_DOWN;
2033 if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
2034 deltas[0] = edgeSlop;
2035 x += edgeSlop;
2036 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
2037 deltas[0] = -edgeSlop;
2038 x -= edgeSlop;
2039 }
2040 } else if ((edgeFlags & MotionEvent.EDGE_BOTTOM) != 0) {
2041 direction = View.FOCUS_UP;
2042 if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
2043 deltas[0] = edgeSlop;
2044 x += edgeSlop;
2045 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
2046 deltas[0] = -edgeSlop;
2047 x -= edgeSlop;
2048 }
2049 } else if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
2050 direction = View.FOCUS_RIGHT;
2051 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
2052 direction = View.FOCUS_LEFT;
2053 }
2054
2055 if (edgeFlags != 0 && mView instanceof ViewGroup) {
2056 View nearest = FocusFinder.getInstance().findNearestTouchable(
2057 ((ViewGroup) mView), x, y, direction, deltas);
2058 if (nearest != null) {
2059 event.offsetLocation(deltas[0], deltas[1]);
2060 event.setEdgeFlags(0);
2061 mView.dispatchTouchEvent(event);
2062 }
2063 }
2064 }
2065 }
2066 }
2067
2068 private void deliverTrackballEvent(MotionEvent event) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002069 if (DEBUG_TRACKBALL) Log.v(TAG, "Motion event:" + event);
2070
2071 boolean handled = false;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002072 if (mView != null && mAdded) {
2073 handled = mView.dispatchTrackballEvent(event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002074 if (handled) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002075 // If we reach this, we delivered a trackball event to mView and
2076 // mView consumed it. Because we will not translate the trackball
2077 // event into a key event, touch mode will not exit, so we exit
2078 // touch mode here.
2079 ensureTouchMode(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002080 return;
2081 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002082
2083 // Otherwise we could do something here, like changing the focus
2084 // or something?
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002085 }
2086
2087 final TrackballAxis x = mTrackballAxisX;
2088 final TrackballAxis y = mTrackballAxisY;
2089
2090 long curTime = SystemClock.uptimeMillis();
2091 if ((mLastTrackballTime+MAX_TRACKBALL_DELAY) < curTime) {
2092 // It has been too long since the last movement,
2093 // so restart at the beginning.
2094 x.reset(0);
2095 y.reset(0);
2096 mLastTrackballTime = curTime;
2097 }
2098
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002099 final int action = event.getAction();
2100 final int metastate = event.getMetaState();
2101 switch (action) {
2102 case MotionEvent.ACTION_DOWN:
2103 x.reset(2);
2104 y.reset(2);
2105 deliverKeyEvent(new KeyEvent(curTime, curTime,
2106 KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_CENTER,
2107 0, metastate), false);
2108 break;
2109 case MotionEvent.ACTION_UP:
2110 x.reset(2);
2111 y.reset(2);
2112 deliverKeyEvent(new KeyEvent(curTime, curTime,
2113 KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_CENTER,
2114 0, metastate), false);
2115 break;
2116 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002117
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002118 if (DEBUG_TRACKBALL) Log.v(TAG, "TB X=" + x.position + " step="
2119 + x.step + " dir=" + x.dir + " acc=" + x.acceleration
2120 + " move=" + event.getX()
2121 + " / Y=" + y.position + " step="
2122 + y.step + " dir=" + y.dir + " acc=" + y.acceleration
2123 + " move=" + event.getY());
2124 final float xOff = x.collect(event.getX(), event.getEventTime(), "X");
2125 final float yOff = y.collect(event.getY(), event.getEventTime(), "Y");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002126
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002127 // Generate DPAD events based on the trackball movement.
2128 // We pick the axis that has moved the most as the direction of
2129 // the DPAD. When we generate DPAD events for one axis, then the
2130 // other axis is reset -- we don't want to perform DPAD jumps due
2131 // to slight movements in the trackball when making major movements
2132 // along the other axis.
2133 int keycode = 0;
2134 int movement = 0;
2135 float accel = 1;
2136 if (xOff > yOff) {
2137 movement = x.generate((2/event.getXPrecision()));
2138 if (movement != 0) {
2139 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_RIGHT
2140 : KeyEvent.KEYCODE_DPAD_LEFT;
2141 accel = x.acceleration;
2142 y.reset(2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002143 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002144 } else if (yOff > 0) {
2145 movement = y.generate((2/event.getYPrecision()));
2146 if (movement != 0) {
2147 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_DOWN
2148 : KeyEvent.KEYCODE_DPAD_UP;
2149 accel = y.acceleration;
2150 x.reset(2);
2151 }
2152 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002153
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002154 if (keycode != 0) {
2155 if (movement < 0) movement = -movement;
2156 int accelMovement = (int)(movement * accel);
2157 if (DEBUG_TRACKBALL) Log.v(TAG, "Move: movement=" + movement
2158 + " accelMovement=" + accelMovement
2159 + " accel=" + accel);
2160 if (accelMovement > movement) {
2161 if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: "
2162 + keycode);
2163 movement--;
2164 deliverKeyEvent(new KeyEvent(curTime, curTime,
2165 KeyEvent.ACTION_MULTIPLE, keycode,
2166 accelMovement-movement, metastate), false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002167 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002168 while (movement > 0) {
2169 if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: "
2170 + keycode);
2171 movement--;
2172 curTime = SystemClock.uptimeMillis();
2173 deliverKeyEvent(new KeyEvent(curTime, curTime,
2174 KeyEvent.ACTION_DOWN, keycode, 0, event.getMetaState()), false);
2175 deliverKeyEvent(new KeyEvent(curTime, curTime,
2176 KeyEvent.ACTION_UP, keycode, 0, metastate), false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002177 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002178 mLastTrackballTime = curTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002179 }
2180 }
2181
2182 /**
2183 * @param keyCode The key code
2184 * @return True if the key is directional.
2185 */
2186 static boolean isDirectional(int keyCode) {
2187 switch (keyCode) {
2188 case KeyEvent.KEYCODE_DPAD_LEFT:
2189 case KeyEvent.KEYCODE_DPAD_RIGHT:
2190 case KeyEvent.KEYCODE_DPAD_UP:
2191 case KeyEvent.KEYCODE_DPAD_DOWN:
2192 return true;
2193 }
2194 return false;
2195 }
2196
2197 /**
2198 * Returns true if this key is a keyboard key.
2199 * @param keyEvent The key event.
2200 * @return whether this key is a keyboard key.
2201 */
2202 private static boolean isKeyboardKey(KeyEvent keyEvent) {
2203 final int convertedKey = keyEvent.getUnicodeChar();
2204 return convertedKey > 0;
2205 }
2206
2207
2208
2209 /**
2210 * See if the key event means we should leave touch mode (and leave touch
2211 * mode if so).
2212 * @param event The key event.
2213 * @return Whether this key event should be consumed (meaning the act of
2214 * leaving touch mode alone is considered the event).
2215 */
2216 private boolean checkForLeavingTouchModeAndConsume(KeyEvent event) {
Adam Powell51a6bee2010-03-15 14:07:28 -07002217 final int action = event.getAction();
2218 if (action != KeyEvent.ACTION_DOWN && action != KeyEvent.ACTION_MULTIPLE) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002219 return false;
2220 }
2221 if ((event.getFlags()&KeyEvent.FLAG_KEEP_TOUCH_MODE) != 0) {
2222 return false;
2223 }
2224
2225 // only relevant if we are in touch mode
2226 if (!mAttachInfo.mInTouchMode) {
2227 return false;
2228 }
2229
2230 // if something like an edit text has focus and the user is typing,
2231 // leave touch mode
2232 //
2233 // note: the condition of not being a keyboard key is kind of a hacky
2234 // approximation of whether we think the focused view will want the
2235 // key; if we knew for sure whether the focused view would consume
2236 // the event, that would be better.
2237 if (isKeyboardKey(event) && mView != null && mView.hasFocus()) {
2238 mFocusedView = mView.findFocus();
2239 if ((mFocusedView instanceof ViewGroup)
2240 && ((ViewGroup) mFocusedView).getDescendantFocusability() ==
2241 ViewGroup.FOCUS_AFTER_DESCENDANTS) {
2242 // something has focus, but is holding it weakly as a container
2243 return false;
2244 }
2245 if (ensureTouchMode(false)) {
2246 throw new IllegalStateException("should not have changed focus "
2247 + "when leaving touch mode while a view has focus.");
2248 }
2249 return false;
2250 }
2251
2252 if (isDirectional(event.getKeyCode())) {
2253 // no view has focus, so we leave touch mode (and find something
2254 // to give focus to). the event is consumed if we were able to
2255 // find something to give focus to.
2256 return ensureTouchMode(false);
2257 }
2258 return false;
2259 }
2260
2261 /**
Romain Guy8506ab42009-06-11 17:35:47 -07002262 * log motion events
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002263 */
2264 private static void captureMotionLog(String subTag, MotionEvent ev) {
Romain Guy8506ab42009-06-11 17:35:47 -07002265 //check dynamic switch
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002266 if (ev == null ||
2267 SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_EVENT, 0) == 0) {
2268 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002269 }
Romain Guy8506ab42009-06-11 17:35:47 -07002270
2271 StringBuilder sb = new StringBuilder(subTag + ": ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002272 sb.append(ev.getDownTime()).append(',');
2273 sb.append(ev.getEventTime()).append(',');
2274 sb.append(ev.getAction()).append(',');
Romain Guy8506ab42009-06-11 17:35:47 -07002275 sb.append(ev.getX()).append(',');
2276 sb.append(ev.getY()).append(',');
2277 sb.append(ev.getPressure()).append(',');
2278 sb.append(ev.getSize()).append(',');
2279 sb.append(ev.getMetaState()).append(',');
2280 sb.append(ev.getXPrecision()).append(',');
2281 sb.append(ev.getYPrecision()).append(',');
2282 sb.append(ev.getDeviceId()).append(',');
2283 sb.append(ev.getEdgeFlags());
2284 Log.d(TAG, sb.toString());
2285 }
2286 /**
2287 * log motion events
2288 */
2289 private static void captureKeyLog(String subTag, KeyEvent ev) {
2290 //check dynamic switch
2291 if (ev == null ||
2292 SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_EVENT, 0) == 0) {
2293 return;
2294 }
2295 StringBuilder sb = new StringBuilder(subTag + ": ");
2296 sb.append(ev.getDownTime()).append(',');
2297 sb.append(ev.getEventTime()).append(',');
2298 sb.append(ev.getAction()).append(',');
2299 sb.append(ev.getKeyCode()).append(',');
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002300 sb.append(ev.getRepeatCount()).append(',');
2301 sb.append(ev.getMetaState()).append(',');
2302 sb.append(ev.getDeviceId()).append(',');
2303 sb.append(ev.getScanCode());
Romain Guy8506ab42009-06-11 17:35:47 -07002304 Log.d(TAG, sb.toString());
2305 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002306
2307 int enqueuePendingEvent(Object event, boolean sendDone) {
2308 int seq = mPendingEventSeq+1;
2309 if (seq < 0) seq = 0;
2310 mPendingEventSeq = seq;
2311 mPendingEvents.put(seq, event);
2312 return sendDone ? seq : -seq;
2313 }
2314
2315 Object retrievePendingEvent(int seq) {
2316 if (seq < 0) seq = -seq;
2317 Object event = mPendingEvents.get(seq);
2318 if (event != null) {
2319 mPendingEvents.remove(seq);
2320 }
2321 return event;
2322 }
Romain Guy8506ab42009-06-11 17:35:47 -07002323
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002324 private void deliverKeyEvent(KeyEvent event, boolean sendDone) {
2325 // If mView is null, we just consume the key event because it doesn't
2326 // make sense to do anything else with it.
Romain Guy812ccbe2010-06-01 14:07:24 -07002327 boolean handled = mView == null || mView.dispatchKeyEventPreIme(event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002328 if (handled) {
2329 if (sendDone) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002330 finishKeyEvent(event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002331 }
2332 return;
2333 }
2334 // If it is possible for this window to interact with the input
2335 // method window, then we want to first dispatch our key events
2336 // to the input method.
2337 if (mLastWasImTarget) {
2338 InputMethodManager imm = InputMethodManager.peekInstance();
2339 if (imm != null && mView != null) {
2340 int seq = enqueuePendingEvent(event, sendDone);
2341 if (DEBUG_IMF) Log.v(TAG, "Sending key event to IME: seq="
2342 + seq + " event=" + event);
2343 imm.dispatchKeyEvent(mView.getContext(), seq, event,
2344 mInputMethodCallback);
2345 return;
2346 }
2347 }
2348 deliverKeyEventToViewHierarchy(event, sendDone);
2349 }
2350
2351 void handleFinishedEvent(int seq, boolean handled) {
2352 final KeyEvent event = (KeyEvent)retrievePendingEvent(seq);
2353 if (DEBUG_IMF) Log.v(TAG, "IME finished event: seq=" + seq
2354 + " handled=" + handled + " event=" + event);
2355 if (event != null) {
2356 final boolean sendDone = seq >= 0;
2357 if (!handled) {
2358 deliverKeyEventToViewHierarchy(event, sendDone);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002359 } else if (sendDone) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002360 finishKeyEvent(event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002361 } else {
Jeff Brownc5ed5912010-07-14 18:48:53 -07002362 Log.w(TAG, "handleFinishedEvent(seq=" + seq
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002363 + " handled=" + handled + " ev=" + event
2364 + ") neither delivering nor finishing key");
2365 }
2366 }
2367 }
Romain Guy8506ab42009-06-11 17:35:47 -07002368
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002369 private void deliverKeyEventToViewHierarchy(KeyEvent event, boolean sendDone) {
2370 try {
2371 if (mView != null && mAdded) {
2372 final int action = event.getAction();
2373 boolean isDown = (action == KeyEvent.ACTION_DOWN);
2374
2375 if (checkForLeavingTouchModeAndConsume(event)) {
2376 return;
Romain Guy8506ab42009-06-11 17:35:47 -07002377 }
2378
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002379 if (Config.LOGV) {
2380 captureKeyLog("captureDispatchKeyEvent", event);
2381 }
2382 boolean keyHandled = mView.dispatchKeyEvent(event);
2383
2384 if (!keyHandled && isDown) {
2385 int direction = 0;
2386 switch (event.getKeyCode()) {
2387 case KeyEvent.KEYCODE_DPAD_LEFT:
2388 direction = View.FOCUS_LEFT;
2389 break;
2390 case KeyEvent.KEYCODE_DPAD_RIGHT:
2391 direction = View.FOCUS_RIGHT;
2392 break;
2393 case KeyEvent.KEYCODE_DPAD_UP:
2394 direction = View.FOCUS_UP;
2395 break;
2396 case KeyEvent.KEYCODE_DPAD_DOWN:
2397 direction = View.FOCUS_DOWN;
2398 break;
2399 }
2400
2401 if (direction != 0) {
2402
2403 View focused = mView != null ? mView.findFocus() : null;
2404 if (focused != null) {
2405 View v = focused.focusSearch(direction);
2406 boolean focusPassed = false;
2407 if (v != null && v != focused) {
2408 // do the math the get the interesting rect
2409 // of previous focused into the coord system of
2410 // newly focused view
2411 focused.getFocusedRect(mTempRect);
Dianne Hackborn1c6a8942010-03-23 16:34:20 -07002412 if (mView instanceof ViewGroup) {
2413 ((ViewGroup) mView).offsetDescendantRectToMyCoords(
2414 focused, mTempRect);
2415 ((ViewGroup) mView).offsetRectIntoDescendantCoords(
2416 v, mTempRect);
2417 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002418 focusPassed = v.requestFocus(direction, mTempRect);
2419 }
2420
2421 if (!focusPassed) {
2422 mView.dispatchUnhandledMove(focused, direction);
2423 } else {
2424 playSoundEffect(SoundEffectConstants.getContantForFocusDirection(direction));
2425 }
2426 }
2427 }
2428 }
2429 }
2430
2431 } finally {
2432 if (sendDone) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002433 finishKeyEvent(event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002434 }
2435 // Let the exception fall through -- the looper will catch
2436 // it and take care of the bad app for us.
2437 }
2438 }
2439
2440 private AudioManager getAudioManager() {
2441 if (mView == null) {
2442 throw new IllegalStateException("getAudioManager called when there is no mView");
2443 }
2444 if (mAudioManager == null) {
2445 mAudioManager = (AudioManager) mView.getContext().getSystemService(Context.AUDIO_SERVICE);
2446 }
2447 return mAudioManager;
2448 }
2449
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002450 private int relayoutWindow(WindowManager.LayoutParams params, int viewVisibility,
2451 boolean insetsPending) throws RemoteException {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002452
2453 float appScale = mAttachInfo.mApplicationScale;
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002454 boolean restore = false;
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002455 if (params != null && mTranslator != null) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07002456 restore = true;
2457 params.backup();
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002458 mTranslator.translateWindowLayout(params);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002459 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002460 if (params != null) {
2461 if (DBG) Log.d(TAG, "WindowLayout in layoutWindow:" + params);
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002462 }
Dianne Hackborn694f79b2010-03-17 19:44:59 -07002463 mPendingConfiguration.seq = 0;
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002464 int relayoutResult = sWindowSession.relayout(
2465 mWindow, params,
Mitsuru Oshima61324e52009-07-21 15:40:36 -07002466 (int) (mView.mMeasuredWidth * appScale + 0.5f),
2467 (int) (mView.mMeasuredHeight * appScale + 0.5f),
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002468 viewVisibility, insetsPending, mWinFrame,
Dianne Hackborn694f79b2010-03-17 19:44:59 -07002469 mPendingContentInsets, mPendingVisibleInsets,
2470 mPendingConfiguration, mSurface);
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002471 if (restore) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07002472 params.restore();
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002473 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002474
2475 if (mTranslator != null) {
2476 mTranslator.translateRectInScreenToAppWinFrame(mWinFrame);
2477 mTranslator.translateRectInScreenToAppWindow(mPendingContentInsets);
2478 mTranslator.translateRectInScreenToAppWindow(mPendingVisibleInsets);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002479 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002480 return relayoutResult;
2481 }
Romain Guy8506ab42009-06-11 17:35:47 -07002482
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002483 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002484 * {@inheritDoc}
2485 */
2486 public void playSoundEffect(int effectId) {
2487 checkThread();
2488
Jean-Michel Trivi13b18fd2010-05-05 09:18:15 -07002489 try {
2490 final AudioManager audioManager = getAudioManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002491
Jean-Michel Trivi13b18fd2010-05-05 09:18:15 -07002492 switch (effectId) {
2493 case SoundEffectConstants.CLICK:
2494 audioManager.playSoundEffect(AudioManager.FX_KEY_CLICK);
2495 return;
2496 case SoundEffectConstants.NAVIGATION_DOWN:
2497 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_DOWN);
2498 return;
2499 case SoundEffectConstants.NAVIGATION_LEFT:
2500 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_LEFT);
2501 return;
2502 case SoundEffectConstants.NAVIGATION_RIGHT:
2503 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_RIGHT);
2504 return;
2505 case SoundEffectConstants.NAVIGATION_UP:
2506 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_UP);
2507 return;
2508 default:
2509 throw new IllegalArgumentException("unknown effect id " + effectId +
2510 " not defined in " + SoundEffectConstants.class.getCanonicalName());
2511 }
2512 } catch (IllegalStateException e) {
2513 // Exception thrown by getAudioManager() when mView is null
2514 Log.e(TAG, "FATAL EXCEPTION when attempting to play sound effect: " + e);
2515 e.printStackTrace();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002516 }
2517 }
2518
2519 /**
2520 * {@inheritDoc}
2521 */
2522 public boolean performHapticFeedback(int effectId, boolean always) {
2523 try {
2524 return sWindowSession.performHapticFeedback(mWindow, effectId, always);
2525 } catch (RemoteException e) {
2526 return false;
2527 }
2528 }
2529
2530 /**
2531 * {@inheritDoc}
2532 */
2533 public View focusSearch(View focused, int direction) {
2534 checkThread();
2535 if (!(mView instanceof ViewGroup)) {
2536 return null;
2537 }
2538 return FocusFinder.getInstance().findNextFocus((ViewGroup) mView, focused, direction);
2539 }
2540
2541 public void debug() {
2542 mView.debug();
2543 }
2544
2545 public void die(boolean immediate) {
Dianne Hackborn94d69142009-09-28 22:14:42 -07002546 if (immediate) {
2547 doDie();
2548 } else {
2549 sendEmptyMessage(DIE);
2550 }
2551 }
2552
2553 void doDie() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002554 checkThread();
Jeff Brownb75fa302010-07-15 23:47:29 -07002555 if (LOCAL_LOGV) Log.v(TAG, "DIE in " + this + " of " + mSurface);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002556 synchronized (this) {
2557 if (mAdded && !mFirst) {
2558 int viewVisibility = mView.getVisibility();
2559 boolean viewVisibilityChanged = mViewVisibility != viewVisibility;
2560 if (mWindowAttributesChanged || viewVisibilityChanged) {
2561 // If layout params have been changed, first give them
2562 // to the window manager to make sure it has the correct
2563 // animation info.
2564 try {
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002565 if ((relayoutWindow(mWindowAttributes, viewVisibility, false)
2566 & WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002567 sWindowSession.finishDrawing(mWindow);
2568 }
2569 } catch (RemoteException e) {
2570 }
2571 }
2572
Dianne Hackborn0586a1b2009-09-06 21:08:27 -07002573 mSurface.release();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002574 }
2575 if (mAdded) {
2576 mAdded = false;
Dianne Hackborn94d69142009-09-28 22:14:42 -07002577 dispatchDetachedFromWindow();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002578 }
2579 }
2580 }
2581
2582 public void dispatchFinishedEvent(int seq, boolean handled) {
2583 Message msg = obtainMessage(FINISHED_EVENT);
2584 msg.arg1 = seq;
2585 msg.arg2 = handled ? 1 : 0;
2586 sendMessage(msg);
2587 }
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002588
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002589 public void dispatchResized(int w, int h, Rect coveredInsets,
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002590 Rect visibleInsets, boolean reportDraw, Configuration newConfig) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002591 if (DEBUG_LAYOUT) Log.v(TAG, "Resizing " + this + ": w=" + w
2592 + " h=" + h + " coveredInsets=" + coveredInsets.toShortString()
2593 + " visibleInsets=" + visibleInsets.toShortString()
2594 + " reportDraw=" + reportDraw);
2595 Message msg = obtainMessage(reportDraw ? RESIZED_REPORT :RESIZED);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002596 if (mTranslator != null) {
2597 mTranslator.translateRectInScreenToAppWindow(coveredInsets);
2598 mTranslator.translateRectInScreenToAppWindow(visibleInsets);
2599 w *= mTranslator.applicationInvertedScale;
2600 h *= mTranslator.applicationInvertedScale;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002601 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002602 msg.arg1 = w;
2603 msg.arg2 = h;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002604 ResizedInfo ri = new ResizedInfo();
2605 ri.coveredInsets = new Rect(coveredInsets);
2606 ri.visibleInsets = new Rect(visibleInsets);
2607 ri.newConfig = newConfig;
2608 msg.obj = ri;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002609 sendMessage(msg);
2610 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002611
2612 private Runnable mFinishedCallback;
2613
2614 private final InputHandler mInputHandler = new InputHandler() {
2615 public void handleKey(KeyEvent event, Runnable finishedCallback) {
Jeff Brown92ff1dd2010-08-11 16:16:06 -07002616 if (mFinishedCallback != null) {
2617 Slog.w(TAG, "Received a new key event from the input queue but there is "
2618 + "already an unfinished key event in progress.");
2619 }
2620
Jeff Brown46b9ac02010-04-22 18:58:52 -07002621 mFinishedCallback = finishedCallback;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002622
Jeff Brown92ff1dd2010-08-11 16:16:06 -07002623 dispatchKey(event, true);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002624 }
2625
Jeff Brownc5ed5912010-07-14 18:48:53 -07002626 public void handleMotion(MotionEvent event, Runnable finishedCallback) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002627 finishedCallback.run();
2628
Jeff Brownc5ed5912010-07-14 18:48:53 -07002629 dispatchMotion(event);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002630 }
2631 };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002632
2633 public void dispatchKey(KeyEvent event) {
Jeff Brown92ff1dd2010-08-11 16:16:06 -07002634 dispatchKey(event, false);
2635 }
2636
2637 private void dispatchKey(KeyEvent event, boolean sendDone) {
2638 //noinspection ConstantConditions
2639 if (false && event.getAction() == KeyEvent.ACTION_DOWN) {
2640 if (event.getKeyCode() == KeyEvent.KEYCODE_CAMERA) {
Romain Guy812ccbe2010-06-01 14:07:24 -07002641 if (DBG) Log.d("keydisp", "===================================================");
2642 if (DBG) Log.d("keydisp", "Focused view Hierarchy is:");
2643
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002644 debug();
2645
Romain Guy812ccbe2010-06-01 14:07:24 -07002646 if (DBG) Log.d("keydisp", "===================================================");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002647 }
2648 }
2649
2650 Message msg = obtainMessage(DISPATCH_KEY);
2651 msg.obj = event;
Jeff Brown92ff1dd2010-08-11 16:16:06 -07002652 msg.arg1 = sendDone ? 1 : 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002653
2654 if (LOCAL_LOGV) Log.v(
Jeff Brownc5ed5912010-07-14 18:48:53 -07002655 TAG, "sending key " + event + " to " + mView);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002656
2657 sendMessageAtTime(msg, event.getEventTime());
2658 }
Jeff Brownc5ed5912010-07-14 18:48:53 -07002659
2660 public void dispatchMotion(MotionEvent event) {
2661 int source = event.getSource();
2662 if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
2663 dispatchPointer(event);
2664 } else if ((source & InputDevice.SOURCE_CLASS_TRACKBALL) != 0) {
2665 dispatchTrackball(event);
2666 } else {
2667 // TODO
2668 Log.v(TAG, "Dropping unsupported motion event (unimplemented): " + event);
2669 }
2670 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002671
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002672 public void dispatchPointer(MotionEvent event) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002673 Message msg = obtainMessage(DISPATCH_POINTER);
2674 msg.obj = event;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002675 sendMessageAtTime(msg, event.getEventTime());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002676 }
2677
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002678 public void dispatchTrackball(MotionEvent event) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002679 Message msg = obtainMessage(DISPATCH_TRACKBALL);
2680 msg.obj = event;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002681 sendMessageAtTime(msg, event.getEventTime());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002682 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002683
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002684 public void dispatchAppVisibility(boolean visible) {
2685 Message msg = obtainMessage(DISPATCH_APP_VISIBILITY);
2686 msg.arg1 = visible ? 1 : 0;
2687 sendMessage(msg);
2688 }
2689
2690 public void dispatchGetNewSurface() {
2691 Message msg = obtainMessage(DISPATCH_GET_NEW_SURFACE);
2692 sendMessage(msg);
2693 }
2694
2695 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
2696 Message msg = Message.obtain();
2697 msg.what = WINDOW_FOCUS_CHANGED;
2698 msg.arg1 = hasFocus ? 1 : 0;
2699 msg.arg2 = inTouchMode ? 1 : 0;
2700 sendMessage(msg);
2701 }
2702
Dianne Hackbornffa42482009-09-23 22:20:11 -07002703 public void dispatchCloseSystemDialogs(String reason) {
2704 Message msg = Message.obtain();
2705 msg.what = CLOSE_SYSTEM_DIALOGS;
2706 msg.obj = reason;
2707 sendMessage(msg);
2708 }
2709
svetoslavganov75986cf2009-05-14 22:28:01 -07002710 /**
2711 * The window is getting focus so if there is anything focused/selected
2712 * send an {@link AccessibilityEvent} to announce that.
2713 */
2714 private void sendAccessibilityEvents() {
2715 if (!AccessibilityManager.getInstance(mView.getContext()).isEnabled()) {
2716 return;
2717 }
2718 mView.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
2719 View focusedView = mView.findFocus();
2720 if (focusedView != null && focusedView != mView) {
2721 focusedView.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
2722 }
2723 }
2724
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002725 public boolean showContextMenuForChild(View originalView) {
2726 return false;
2727 }
2728
Adam Powell6e346362010-07-23 10:18:23 -07002729 public ActionMode startActionModeForChild(View originalView, ActionMode.Callback callback) {
2730 return null;
2731 }
2732
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002733 public void createContextMenu(ContextMenu menu) {
2734 }
2735
2736 public void childDrawableStateChanged(View child) {
2737 }
2738
2739 protected Rect getWindowFrame() {
2740 return mWinFrame;
2741 }
2742
2743 void checkThread() {
2744 if (mThread != Thread.currentThread()) {
2745 throw new CalledFromWrongThreadException(
2746 "Only the original thread that created a view hierarchy can touch its views.");
2747 }
2748 }
2749
2750 public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
2751 // ViewRoot never intercepts touch event, so this can be a no-op
2752 }
2753
2754 public boolean requestChildRectangleOnScreen(View child, Rect rectangle,
2755 boolean immediate) {
2756 return scrollToRectOrFocus(rectangle, immediate);
2757 }
Romain Guy8506ab42009-06-11 17:35:47 -07002758
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07002759 class TakenSurfaceHolder extends BaseSurfaceHolder {
2760 @Override
2761 public boolean onAllowLockCanvas() {
2762 return mDrawingAllowed;
2763 }
2764
2765 @Override
2766 public void onRelayoutContainer() {
2767 // Not currently interesting -- from changing between fixed and layout size.
2768 }
2769
2770 public void setFormat(int format) {
2771 ((RootViewSurfaceTaker)mView).setSurfaceFormat(format);
2772 }
2773
2774 public void setType(int type) {
2775 ((RootViewSurfaceTaker)mView).setSurfaceType(type);
2776 }
2777
2778 @Override
2779 public void onUpdateSurface() {
2780 // We take care of format and type changes on our own.
2781 throw new IllegalStateException("Shouldn't be here");
2782 }
2783
2784 public boolean isCreating() {
2785 return mIsCreating;
2786 }
2787
2788 @Override
2789 public void setFixedSize(int width, int height) {
2790 throw new UnsupportedOperationException(
2791 "Currently only support sizing from layout");
2792 }
2793
2794 public void setKeepScreenOn(boolean screenOn) {
2795 ((RootViewSurfaceTaker)mView).setSurfaceKeepScreenOn(screenOn);
2796 }
2797 }
2798
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002799 static class InputMethodCallback extends IInputMethodCallback.Stub {
2800 private WeakReference<ViewRoot> mViewRoot;
2801
2802 public InputMethodCallback(ViewRoot viewRoot) {
2803 mViewRoot = new WeakReference<ViewRoot>(viewRoot);
2804 }
Romain Guy8506ab42009-06-11 17:35:47 -07002805
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002806 public void finishedEvent(int seq, boolean handled) {
2807 final ViewRoot viewRoot = mViewRoot.get();
2808 if (viewRoot != null) {
2809 viewRoot.dispatchFinishedEvent(seq, handled);
2810 }
2811 }
2812
2813 public void sessionCreated(IInputMethodSession session) throws RemoteException {
2814 // Stub -- not for use in the client.
2815 }
2816 }
Romain Guy8506ab42009-06-11 17:35:47 -07002817
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002818 static class W extends IWindow.Stub {
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002819 private final WeakReference<ViewRoot> mViewRoot;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002820
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002821 public W(ViewRoot viewRoot, Context context) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002822 mViewRoot = new WeakReference<ViewRoot>(viewRoot);
2823 }
2824
2825 public void resized(int w, int h, Rect coveredInsets,
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002826 Rect visibleInsets, boolean reportDraw, Configuration newConfig) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002827 final ViewRoot viewRoot = mViewRoot.get();
2828 if (viewRoot != null) {
2829 viewRoot.dispatchResized(w, h, coveredInsets,
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002830 visibleInsets, reportDraw, newConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002831 }
2832 }
2833
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002834 public void dispatchAppVisibility(boolean visible) {
2835 final ViewRoot viewRoot = mViewRoot.get();
2836 if (viewRoot != null) {
2837 viewRoot.dispatchAppVisibility(visible);
2838 }
2839 }
2840
2841 public void dispatchGetNewSurface() {
2842 final ViewRoot viewRoot = mViewRoot.get();
2843 if (viewRoot != null) {
2844 viewRoot.dispatchGetNewSurface();
2845 }
2846 }
2847
2848 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
2849 final ViewRoot viewRoot = mViewRoot.get();
2850 if (viewRoot != null) {
2851 viewRoot.windowFocusChanged(hasFocus, inTouchMode);
2852 }
2853 }
2854
2855 private static int checkCallingPermission(String permission) {
2856 if (!Process.supportsProcesses()) {
2857 return PackageManager.PERMISSION_GRANTED;
2858 }
2859
2860 try {
2861 return ActivityManagerNative.getDefault().checkPermission(
2862 permission, Binder.getCallingPid(), Binder.getCallingUid());
2863 } catch (RemoteException e) {
2864 return PackageManager.PERMISSION_DENIED;
2865 }
2866 }
2867
2868 public void executeCommand(String command, String parameters, ParcelFileDescriptor out) {
2869 final ViewRoot viewRoot = mViewRoot.get();
2870 if (viewRoot != null) {
2871 final View view = viewRoot.mView;
2872 if (view != null) {
2873 if (checkCallingPermission(Manifest.permission.DUMP) !=
2874 PackageManager.PERMISSION_GRANTED) {
2875 throw new SecurityException("Insufficient permissions to invoke"
2876 + " executeCommand() from pid=" + Binder.getCallingPid()
2877 + ", uid=" + Binder.getCallingUid());
2878 }
2879
2880 OutputStream clientStream = null;
2881 try {
2882 clientStream = new ParcelFileDescriptor.AutoCloseOutputStream(out);
2883 ViewDebug.dispatchCommand(view, command, parameters, clientStream);
2884 } catch (IOException e) {
2885 e.printStackTrace();
2886 } finally {
2887 if (clientStream != null) {
2888 try {
2889 clientStream.close();
2890 } catch (IOException e) {
2891 e.printStackTrace();
2892 }
2893 }
2894 }
2895 }
2896 }
2897 }
Dianne Hackborn72c82ab2009-08-11 21:13:54 -07002898
Dianne Hackbornffa42482009-09-23 22:20:11 -07002899 public void closeSystemDialogs(String reason) {
2900 final ViewRoot viewRoot = mViewRoot.get();
2901 if (viewRoot != null) {
2902 viewRoot.dispatchCloseSystemDialogs(reason);
2903 }
2904 }
2905
Marco Nelissenbf6956b2009-11-09 15:21:13 -08002906 public void dispatchWallpaperOffsets(float x, float y, float xStep, float yStep,
2907 boolean sync) {
Dianne Hackborn19382ac2009-09-11 21:13:37 -07002908 if (sync) {
2909 try {
2910 sWindowSession.wallpaperOffsetsComplete(asBinder());
2911 } catch (RemoteException e) {
2912 }
2913 }
Dianne Hackborn72c82ab2009-08-11 21:13:54 -07002914 }
Dianne Hackborn75804932009-10-20 20:15:20 -07002915
2916 public void dispatchWallpaperCommand(String action, int x, int y,
2917 int z, Bundle extras, boolean sync) {
2918 if (sync) {
2919 try {
2920 sWindowSession.wallpaperCommandComplete(asBinder(), null);
2921 } catch (RemoteException e) {
2922 }
2923 }
2924 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002925 }
2926
2927 /**
2928 * Maintains state information for a single trackball axis, generating
2929 * discrete (DPAD) movements based on raw trackball motion.
2930 */
2931 static final class TrackballAxis {
2932 /**
2933 * The maximum amount of acceleration we will apply.
2934 */
2935 static final float MAX_ACCELERATION = 20;
Romain Guy8506ab42009-06-11 17:35:47 -07002936
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002937 /**
2938 * The maximum amount of time (in milliseconds) between events in order
2939 * for us to consider the user to be doing fast trackball movements,
2940 * and thus apply an acceleration.
2941 */
2942 static final long FAST_MOVE_TIME = 150;
Romain Guy8506ab42009-06-11 17:35:47 -07002943
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002944 /**
2945 * Scaling factor to the time (in milliseconds) between events to how
2946 * much to multiple/divide the current acceleration. When movement
2947 * is < FAST_MOVE_TIME this multiplies the acceleration; when >
2948 * FAST_MOVE_TIME it divides it.
2949 */
2950 static final float ACCEL_MOVE_SCALING_FACTOR = (1.0f/40);
Romain Guy8506ab42009-06-11 17:35:47 -07002951
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002952 float position;
2953 float absPosition;
2954 float acceleration = 1;
2955 long lastMoveTime = 0;
2956 int step;
2957 int dir;
2958 int nonAccelMovement;
2959
2960 void reset(int _step) {
2961 position = 0;
2962 acceleration = 1;
2963 lastMoveTime = 0;
2964 step = _step;
2965 dir = 0;
2966 }
2967
2968 /**
2969 * Add trackball movement into the state. If the direction of movement
2970 * has been reversed, the state is reset before adding the
2971 * movement (so that you don't have to compensate for any previously
2972 * collected movement before see the result of the movement in the
2973 * new direction).
2974 *
2975 * @return Returns the absolute value of the amount of movement
2976 * collected so far.
2977 */
2978 float collect(float off, long time, String axis) {
2979 long normTime;
2980 if (off > 0) {
2981 normTime = (long)(off * FAST_MOVE_TIME);
2982 if (dir < 0) {
2983 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to positive!");
2984 position = 0;
2985 step = 0;
2986 acceleration = 1;
2987 lastMoveTime = 0;
2988 }
2989 dir = 1;
2990 } else if (off < 0) {
2991 normTime = (long)((-off) * FAST_MOVE_TIME);
2992 if (dir > 0) {
2993 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to negative!");
2994 position = 0;
2995 step = 0;
2996 acceleration = 1;
2997 lastMoveTime = 0;
2998 }
2999 dir = -1;
3000 } else {
3001 normTime = 0;
3002 }
Romain Guy8506ab42009-06-11 17:35:47 -07003003
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003004 // The number of milliseconds between each movement that is
3005 // considered "normal" and will not result in any acceleration
3006 // or deceleration, scaled by the offset we have here.
3007 if (normTime > 0) {
3008 long delta = time - lastMoveTime;
3009 lastMoveTime = time;
3010 float acc = acceleration;
3011 if (delta < normTime) {
3012 // The user is scrolling rapidly, so increase acceleration.
3013 float scale = (normTime-delta) * ACCEL_MOVE_SCALING_FACTOR;
3014 if (scale > 1) acc *= scale;
3015 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " accelerate: off="
3016 + off + " normTime=" + normTime + " delta=" + delta
3017 + " scale=" + scale + " acc=" + acc);
3018 acceleration = acc < MAX_ACCELERATION ? acc : MAX_ACCELERATION;
3019 } else {
3020 // The user is scrolling slowly, so decrease acceleration.
3021 float scale = (delta-normTime) * ACCEL_MOVE_SCALING_FACTOR;
3022 if (scale > 1) acc /= scale;
3023 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " deccelerate: off="
3024 + off + " normTime=" + normTime + " delta=" + delta
3025 + " scale=" + scale + " acc=" + acc);
3026 acceleration = acc > 1 ? acc : 1;
3027 }
3028 }
3029 position += off;
3030 return (absPosition = Math.abs(position));
3031 }
3032
3033 /**
3034 * Generate the number of discrete movement events appropriate for
3035 * the currently collected trackball movement.
3036 *
3037 * @param precision The minimum movement required to generate the
3038 * first discrete movement.
3039 *
3040 * @return Returns the number of discrete movements, either positive
3041 * or negative, or 0 if there is not enough trackball movement yet
3042 * for a discrete movement.
3043 */
3044 int generate(float precision) {
3045 int movement = 0;
3046 nonAccelMovement = 0;
3047 do {
3048 final int dir = position >= 0 ? 1 : -1;
3049 switch (step) {
3050 // If we are going to execute the first step, then we want
3051 // to do this as soon as possible instead of waiting for
3052 // a full movement, in order to make things look responsive.
3053 case 0:
3054 if (absPosition < precision) {
3055 return movement;
3056 }
3057 movement += dir;
3058 nonAccelMovement += dir;
3059 step = 1;
3060 break;
3061 // If we have generated the first movement, then we need
3062 // to wait for the second complete trackball motion before
3063 // generating the second discrete movement.
3064 case 1:
3065 if (absPosition < 2) {
3066 return movement;
3067 }
3068 movement += dir;
3069 nonAccelMovement += dir;
3070 position += dir > 0 ? -2 : 2;
3071 absPosition = Math.abs(position);
3072 step = 2;
3073 break;
3074 // After the first two, we generate discrete movements
3075 // consistently with the trackball, applying an acceleration
3076 // if the trackball is moving quickly. This is a simple
3077 // acceleration on top of what we already compute based
3078 // on how quickly the wheel is being turned, to apply
3079 // a longer increasing acceleration to continuous movement
3080 // in one direction.
3081 default:
3082 if (absPosition < 1) {
3083 return movement;
3084 }
3085 movement += dir;
3086 position += dir >= 0 ? -1 : 1;
3087 absPosition = Math.abs(position);
3088 float acc = acceleration;
3089 acc *= 1.1f;
3090 acceleration = acc < MAX_ACCELERATION ? acc : acceleration;
3091 break;
3092 }
3093 } while (true);
3094 }
3095 }
3096
3097 public static final class CalledFromWrongThreadException extends AndroidRuntimeException {
3098 public CalledFromWrongThreadException(String msg) {
3099 super(msg);
3100 }
3101 }
3102
3103 private SurfaceHolder mHolder = new SurfaceHolder() {
3104 // we only need a SurfaceHolder for opengl. it would be nice
3105 // to implement everything else though, especially the callback
3106 // support (opengl doesn't make use of it right now, but eventually
3107 // will).
3108 public Surface getSurface() {
3109 return mSurface;
3110 }
3111
3112 public boolean isCreating() {
3113 return false;
3114 }
3115
3116 public void addCallback(Callback callback) {
3117 }
3118
3119 public void removeCallback(Callback callback) {
3120 }
3121
3122 public void setFixedSize(int width, int height) {
3123 }
3124
3125 public void setSizeFromLayout() {
3126 }
3127
3128 public void setFormat(int format) {
3129 }
3130
3131 public void setType(int type) {
3132 }
3133
3134 public void setKeepScreenOn(boolean screenOn) {
3135 }
3136
3137 public Canvas lockCanvas() {
3138 return null;
3139 }
3140
3141 public Canvas lockCanvas(Rect dirty) {
3142 return null;
3143 }
3144
3145 public void unlockCanvasAndPost(Canvas canvas) {
3146 }
3147 public Rect getSurfaceFrame() {
3148 return null;
3149 }
3150 };
3151
3152 static RunQueue getRunQueue() {
3153 RunQueue rq = sRunQueues.get();
3154 if (rq != null) {
3155 return rq;
3156 }
3157 rq = new RunQueue();
3158 sRunQueues.set(rq);
3159 return rq;
3160 }
Romain Guy8506ab42009-06-11 17:35:47 -07003161
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003162 /**
3163 * @hide
3164 */
3165 static final class RunQueue {
3166 private final ArrayList<HandlerAction> mActions = new ArrayList<HandlerAction>();
3167
3168 void post(Runnable action) {
3169 postDelayed(action, 0);
3170 }
3171
3172 void postDelayed(Runnable action, long delayMillis) {
3173 HandlerAction handlerAction = new HandlerAction();
3174 handlerAction.action = action;
3175 handlerAction.delay = delayMillis;
3176
3177 synchronized (mActions) {
3178 mActions.add(handlerAction);
3179 }
3180 }
3181
3182 void removeCallbacks(Runnable action) {
3183 final HandlerAction handlerAction = new HandlerAction();
3184 handlerAction.action = action;
3185
3186 synchronized (mActions) {
3187 final ArrayList<HandlerAction> actions = mActions;
3188
3189 while (actions.remove(handlerAction)) {
3190 // Keep going
3191 }
3192 }
3193 }
3194
3195 void executeActions(Handler handler) {
3196 synchronized (mActions) {
3197 final ArrayList<HandlerAction> actions = mActions;
3198 final int count = actions.size();
3199
3200 for (int i = 0; i < count; i++) {
3201 final HandlerAction handlerAction = actions.get(i);
3202 handler.postDelayed(handlerAction.action, handlerAction.delay);
3203 }
3204
Romain Guy15df6702009-08-17 20:17:30 -07003205 actions.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003206 }
3207 }
3208
3209 private static class HandlerAction {
3210 Runnable action;
3211 long delay;
3212
3213 @Override
3214 public boolean equals(Object o) {
3215 if (this == o) return true;
3216 if (o == null || getClass() != o.getClass()) return false;
3217
3218 HandlerAction that = (HandlerAction) o;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003219 return !(action != null ? !action.equals(that.action) : that.action != null);
3220
3221 }
3222
3223 @Override
3224 public int hashCode() {
3225 int result = action != null ? action.hashCode() : 0;
3226 result = 31 * result + (int) (delay ^ (delay >>> 32));
3227 return result;
3228 }
3229 }
3230 }
3231
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003232 private static native void nativeShowFPS(Canvas canvas, int durationMillis);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003233}