blob: 877a30227d340d204d98b0f8de2bd814cf786eb9 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.view;
18
Romain Guy812ccbe2010-06-01 14:07:24 -070019import android.content.pm.ApplicationInfo;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -070020import com.android.internal.view.BaseSurfaceHolder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080021import com.android.internal.view.IInputMethodCallback;
22import com.android.internal.view.IInputMethodSession;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -070023import com.android.internal.view.RootViewSurfaceTaker;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080024
25import android.graphics.Canvas;
26import android.graphics.PixelFormat;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080027import android.graphics.PorterDuff;
28import android.graphics.Rect;
29import android.graphics.Region;
30import android.os.*;
31import android.os.Process;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080032import android.util.AndroidRuntimeException;
33import android.util.Config;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -070034import android.util.DisplayMetrics;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080035import android.util.Log;
36import android.util.EventLog;
37import 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
332 enableHardwareAcceleration(view, attrs);
333
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 Guye4d01122010-06-16 18:44:05 -0700463 private void enableHardwareAcceleration(View view, WindowManager.LayoutParams attrs) {
464 // 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
469 if ((view.getContext().getApplicationInfo().flags &
470 ApplicationInfo.FLAG_HARDWARE_ACCELERATED) != 0) {
471 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);
1723 deliverKeyEvent((KeyEvent)msg.obj, true);
1724 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 Brown00fa7bd2010-07-02 15:37:36 -07001864 if (mFinishedCallback != null) {
1865 mFinishedCallback.run();
1866 mFinishedCallback = null;
Jeff Brown46b9ac02010-04-22 18:58:52 -07001867 }
1868 }
1869
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001870 /**
1871 * Something in the current window tells us we need to change the touch mode. For
1872 * example, we are not in touch mode, and the user touches the screen.
1873 *
1874 * If the touch mode has changed, tell the window manager, and handle it locally.
1875 *
1876 * @param inTouchMode Whether we want to be in touch mode.
1877 * @return True if the touch mode changed and focus changed was changed as a result
1878 */
1879 boolean ensureTouchMode(boolean inTouchMode) {
1880 if (DBG) Log.d("touchmode", "ensureTouchMode(" + inTouchMode + "), current "
1881 + "touch mode is " + mAttachInfo.mInTouchMode);
1882 if (mAttachInfo.mInTouchMode == inTouchMode) return false;
1883
1884 // tell the window manager
1885 try {
1886 sWindowSession.setInTouchMode(inTouchMode);
1887 } catch (RemoteException e) {
1888 throw new RuntimeException(e);
1889 }
1890
1891 // handle the change
Romain Guy2d4cff62010-04-09 15:39:00 -07001892 return ensureTouchModeLocally(inTouchMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001893 }
1894
1895 /**
1896 * Ensure that the touch mode for this window is set, and if it is changing,
1897 * take the appropriate action.
1898 * @param inTouchMode Whether we want to be in touch mode.
1899 * @return True if the touch mode changed and focus changed was changed as a result
1900 */
Romain Guy2d4cff62010-04-09 15:39:00 -07001901 private boolean ensureTouchModeLocally(boolean inTouchMode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001902 if (DBG) Log.d("touchmode", "ensureTouchModeLocally(" + inTouchMode + "), current "
1903 + "touch mode is " + mAttachInfo.mInTouchMode);
1904
1905 if (mAttachInfo.mInTouchMode == inTouchMode) return false;
1906
1907 mAttachInfo.mInTouchMode = inTouchMode;
1908 mAttachInfo.mTreeObserver.dispatchOnTouchModeChanged(inTouchMode);
1909
Romain Guy2d4cff62010-04-09 15:39:00 -07001910 return (inTouchMode) ? enterTouchMode() : leaveTouchMode();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001911 }
1912
1913 private boolean enterTouchMode() {
1914 if (mView != null) {
1915 if (mView.hasFocus()) {
1916 // note: not relying on mFocusedView here because this could
1917 // be when the window is first being added, and mFocused isn't
1918 // set yet.
1919 final View focused = mView.findFocus();
1920 if (focused != null && !focused.isFocusableInTouchMode()) {
1921
1922 final ViewGroup ancestorToTakeFocus =
1923 findAncestorToTakeFocusInTouchMode(focused);
1924 if (ancestorToTakeFocus != null) {
1925 // there is an ancestor that wants focus after its descendants that
1926 // is focusable in touch mode.. give it focus
1927 return ancestorToTakeFocus.requestFocus();
1928 } else {
1929 // nothing appropriate to have focus in touch mode, clear it out
1930 mView.unFocus();
1931 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(focused, null);
1932 mFocusedView = null;
1933 return true;
1934 }
1935 }
1936 }
1937 }
1938 return false;
1939 }
1940
1941
1942 /**
1943 * Find an ancestor of focused that wants focus after its descendants and is
1944 * focusable in touch mode.
1945 * @param focused The currently focused view.
1946 * @return An appropriate view, or null if no such view exists.
1947 */
1948 private ViewGroup findAncestorToTakeFocusInTouchMode(View focused) {
1949 ViewParent parent = focused.getParent();
1950 while (parent instanceof ViewGroup) {
1951 final ViewGroup vgParent = (ViewGroup) parent;
1952 if (vgParent.getDescendantFocusability() == ViewGroup.FOCUS_AFTER_DESCENDANTS
1953 && vgParent.isFocusableInTouchMode()) {
1954 return vgParent;
1955 }
1956 if (vgParent.isRootNamespace()) {
1957 return null;
1958 } else {
1959 parent = vgParent.getParent();
1960 }
1961 }
1962 return null;
1963 }
1964
1965 private boolean leaveTouchMode() {
1966 if (mView != null) {
1967 if (mView.hasFocus()) {
1968 // i learned the hard way to not trust mFocusedView :)
1969 mFocusedView = mView.findFocus();
1970 if (!(mFocusedView instanceof ViewGroup)) {
1971 // some view has focus, let it keep it
1972 return false;
1973 } else if (((ViewGroup)mFocusedView).getDescendantFocusability() !=
1974 ViewGroup.FOCUS_AFTER_DESCENDANTS) {
1975 // some view group has focus, and doesn't prefer its children
1976 // over itself for focus, so let them keep it.
1977 return false;
1978 }
1979 }
1980
1981 // find the best view to give focus to in this brave new non-touch-mode
1982 // world
1983 final View focused = focusSearch(null, View.FOCUS_DOWN);
1984 if (focused != null) {
1985 return focused.requestFocus(View.FOCUS_DOWN);
1986 }
1987 }
1988 return false;
1989 }
1990
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001991 private void deliverPointerEvent(MotionEvent event) {
1992 if (mTranslator != null) {
1993 mTranslator.translateEventInScreenToAppWindow(event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001994 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001995
1996 boolean handled;
1997 if (mView != null && mAdded) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001998
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001999 // enter touch mode on the down
2000 boolean isDown = event.getAction() == MotionEvent.ACTION_DOWN;
2001 if (isDown) {
2002 ensureTouchMode(true);
2003 }
2004 if(Config.LOGV) {
2005 captureMotionLog("captureDispatchPointer", event);
2006 }
2007 if (mCurScrollY != 0) {
2008 event.offsetLocation(0, mCurScrollY);
2009 }
2010 if (MEASURE_LATENCY) {
2011 lt.sample("A Dispatching TouchEvents", System.nanoTime() - event.getEventTimeNano());
2012 }
2013 handled = mView.dispatchTouchEvent(event);
2014 if (MEASURE_LATENCY) {
2015 lt.sample("B Dispatched TouchEvents ", System.nanoTime() - event.getEventTimeNano());
2016 }
2017 if (!handled && isDown) {
2018 int edgeSlop = mViewConfiguration.getScaledEdgeSlop();
2019
2020 final int edgeFlags = event.getEdgeFlags();
2021 int direction = View.FOCUS_UP;
2022 int x = (int)event.getX();
2023 int y = (int)event.getY();
2024 final int[] deltas = new int[2];
2025
2026 if ((edgeFlags & MotionEvent.EDGE_TOP) != 0) {
2027 direction = View.FOCUS_DOWN;
2028 if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
2029 deltas[0] = edgeSlop;
2030 x += edgeSlop;
2031 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
2032 deltas[0] = -edgeSlop;
2033 x -= edgeSlop;
2034 }
2035 } else if ((edgeFlags & MotionEvent.EDGE_BOTTOM) != 0) {
2036 direction = View.FOCUS_UP;
2037 if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
2038 deltas[0] = edgeSlop;
2039 x += edgeSlop;
2040 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
2041 deltas[0] = -edgeSlop;
2042 x -= edgeSlop;
2043 }
2044 } else if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
2045 direction = View.FOCUS_RIGHT;
2046 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
2047 direction = View.FOCUS_LEFT;
2048 }
2049
2050 if (edgeFlags != 0 && mView instanceof ViewGroup) {
2051 View nearest = FocusFinder.getInstance().findNearestTouchable(
2052 ((ViewGroup) mView), x, y, direction, deltas);
2053 if (nearest != null) {
2054 event.offsetLocation(deltas[0], deltas[1]);
2055 event.setEdgeFlags(0);
2056 mView.dispatchTouchEvent(event);
2057 }
2058 }
2059 }
2060 }
2061 }
2062
2063 private void deliverTrackballEvent(MotionEvent event) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002064 if (DEBUG_TRACKBALL) Log.v(TAG, "Motion event:" + event);
2065
2066 boolean handled = false;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002067 if (mView != null && mAdded) {
2068 handled = mView.dispatchTrackballEvent(event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002069 if (handled) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002070 // If we reach this, we delivered a trackball event to mView and
2071 // mView consumed it. Because we will not translate the trackball
2072 // event into a key event, touch mode will not exit, so we exit
2073 // touch mode here.
2074 ensureTouchMode(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002075 return;
2076 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002077
2078 // Otherwise we could do something here, like changing the focus
2079 // or something?
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002080 }
2081
2082 final TrackballAxis x = mTrackballAxisX;
2083 final TrackballAxis y = mTrackballAxisY;
2084
2085 long curTime = SystemClock.uptimeMillis();
2086 if ((mLastTrackballTime+MAX_TRACKBALL_DELAY) < curTime) {
2087 // It has been too long since the last movement,
2088 // so restart at the beginning.
2089 x.reset(0);
2090 y.reset(0);
2091 mLastTrackballTime = curTime;
2092 }
2093
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002094 final int action = event.getAction();
2095 final int metastate = event.getMetaState();
2096 switch (action) {
2097 case MotionEvent.ACTION_DOWN:
2098 x.reset(2);
2099 y.reset(2);
2100 deliverKeyEvent(new KeyEvent(curTime, curTime,
2101 KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_CENTER,
2102 0, metastate), false);
2103 break;
2104 case MotionEvent.ACTION_UP:
2105 x.reset(2);
2106 y.reset(2);
2107 deliverKeyEvent(new KeyEvent(curTime, curTime,
2108 KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_CENTER,
2109 0, metastate), false);
2110 break;
2111 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002112
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002113 if (DEBUG_TRACKBALL) Log.v(TAG, "TB X=" + x.position + " step="
2114 + x.step + " dir=" + x.dir + " acc=" + x.acceleration
2115 + " move=" + event.getX()
2116 + " / Y=" + y.position + " step="
2117 + y.step + " dir=" + y.dir + " acc=" + y.acceleration
2118 + " move=" + event.getY());
2119 final float xOff = x.collect(event.getX(), event.getEventTime(), "X");
2120 final float yOff = y.collect(event.getY(), event.getEventTime(), "Y");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002121
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002122 // Generate DPAD events based on the trackball movement.
2123 // We pick the axis that has moved the most as the direction of
2124 // the DPAD. When we generate DPAD events for one axis, then the
2125 // other axis is reset -- we don't want to perform DPAD jumps due
2126 // to slight movements in the trackball when making major movements
2127 // along the other axis.
2128 int keycode = 0;
2129 int movement = 0;
2130 float accel = 1;
2131 if (xOff > yOff) {
2132 movement = x.generate((2/event.getXPrecision()));
2133 if (movement != 0) {
2134 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_RIGHT
2135 : KeyEvent.KEYCODE_DPAD_LEFT;
2136 accel = x.acceleration;
2137 y.reset(2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002138 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002139 } else if (yOff > 0) {
2140 movement = y.generate((2/event.getYPrecision()));
2141 if (movement != 0) {
2142 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_DOWN
2143 : KeyEvent.KEYCODE_DPAD_UP;
2144 accel = y.acceleration;
2145 x.reset(2);
2146 }
2147 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002148
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002149 if (keycode != 0) {
2150 if (movement < 0) movement = -movement;
2151 int accelMovement = (int)(movement * accel);
2152 if (DEBUG_TRACKBALL) Log.v(TAG, "Move: movement=" + movement
2153 + " accelMovement=" + accelMovement
2154 + " accel=" + accel);
2155 if (accelMovement > movement) {
2156 if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: "
2157 + keycode);
2158 movement--;
2159 deliverKeyEvent(new KeyEvent(curTime, curTime,
2160 KeyEvent.ACTION_MULTIPLE, keycode,
2161 accelMovement-movement, metastate), false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002162 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002163 while (movement > 0) {
2164 if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: "
2165 + keycode);
2166 movement--;
2167 curTime = SystemClock.uptimeMillis();
2168 deliverKeyEvent(new KeyEvent(curTime, curTime,
2169 KeyEvent.ACTION_DOWN, keycode, 0, event.getMetaState()), false);
2170 deliverKeyEvent(new KeyEvent(curTime, curTime,
2171 KeyEvent.ACTION_UP, keycode, 0, metastate), false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002172 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002173 mLastTrackballTime = curTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002174 }
2175 }
2176
2177 /**
2178 * @param keyCode The key code
2179 * @return True if the key is directional.
2180 */
2181 static boolean isDirectional(int keyCode) {
2182 switch (keyCode) {
2183 case KeyEvent.KEYCODE_DPAD_LEFT:
2184 case KeyEvent.KEYCODE_DPAD_RIGHT:
2185 case KeyEvent.KEYCODE_DPAD_UP:
2186 case KeyEvent.KEYCODE_DPAD_DOWN:
2187 return true;
2188 }
2189 return false;
2190 }
2191
2192 /**
2193 * Returns true if this key is a keyboard key.
2194 * @param keyEvent The key event.
2195 * @return whether this key is a keyboard key.
2196 */
2197 private static boolean isKeyboardKey(KeyEvent keyEvent) {
2198 final int convertedKey = keyEvent.getUnicodeChar();
2199 return convertedKey > 0;
2200 }
2201
2202
2203
2204 /**
2205 * See if the key event means we should leave touch mode (and leave touch
2206 * mode if so).
2207 * @param event The key event.
2208 * @return Whether this key event should be consumed (meaning the act of
2209 * leaving touch mode alone is considered the event).
2210 */
2211 private boolean checkForLeavingTouchModeAndConsume(KeyEvent event) {
Adam Powell51a6bee2010-03-15 14:07:28 -07002212 final int action = event.getAction();
2213 if (action != KeyEvent.ACTION_DOWN && action != KeyEvent.ACTION_MULTIPLE) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002214 return false;
2215 }
2216 if ((event.getFlags()&KeyEvent.FLAG_KEEP_TOUCH_MODE) != 0) {
2217 return false;
2218 }
2219
2220 // only relevant if we are in touch mode
2221 if (!mAttachInfo.mInTouchMode) {
2222 return false;
2223 }
2224
2225 // if something like an edit text has focus and the user is typing,
2226 // leave touch mode
2227 //
2228 // note: the condition of not being a keyboard key is kind of a hacky
2229 // approximation of whether we think the focused view will want the
2230 // key; if we knew for sure whether the focused view would consume
2231 // the event, that would be better.
2232 if (isKeyboardKey(event) && mView != null && mView.hasFocus()) {
2233 mFocusedView = mView.findFocus();
2234 if ((mFocusedView instanceof ViewGroup)
2235 && ((ViewGroup) mFocusedView).getDescendantFocusability() ==
2236 ViewGroup.FOCUS_AFTER_DESCENDANTS) {
2237 // something has focus, but is holding it weakly as a container
2238 return false;
2239 }
2240 if (ensureTouchMode(false)) {
2241 throw new IllegalStateException("should not have changed focus "
2242 + "when leaving touch mode while a view has focus.");
2243 }
2244 return false;
2245 }
2246
2247 if (isDirectional(event.getKeyCode())) {
2248 // no view has focus, so we leave touch mode (and find something
2249 // to give focus to). the event is consumed if we were able to
2250 // find something to give focus to.
2251 return ensureTouchMode(false);
2252 }
2253 return false;
2254 }
2255
2256 /**
Romain Guy8506ab42009-06-11 17:35:47 -07002257 * log motion events
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002258 */
2259 private static void captureMotionLog(String subTag, MotionEvent ev) {
Romain Guy8506ab42009-06-11 17:35:47 -07002260 //check dynamic switch
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002261 if (ev == null ||
2262 SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_EVENT, 0) == 0) {
2263 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002264 }
Romain Guy8506ab42009-06-11 17:35:47 -07002265
2266 StringBuilder sb = new StringBuilder(subTag + ": ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002267 sb.append(ev.getDownTime()).append(',');
2268 sb.append(ev.getEventTime()).append(',');
2269 sb.append(ev.getAction()).append(',');
Romain Guy8506ab42009-06-11 17:35:47 -07002270 sb.append(ev.getX()).append(',');
2271 sb.append(ev.getY()).append(',');
2272 sb.append(ev.getPressure()).append(',');
2273 sb.append(ev.getSize()).append(',');
2274 sb.append(ev.getMetaState()).append(',');
2275 sb.append(ev.getXPrecision()).append(',');
2276 sb.append(ev.getYPrecision()).append(',');
2277 sb.append(ev.getDeviceId()).append(',');
2278 sb.append(ev.getEdgeFlags());
2279 Log.d(TAG, sb.toString());
2280 }
2281 /**
2282 * log motion events
2283 */
2284 private static void captureKeyLog(String subTag, KeyEvent ev) {
2285 //check dynamic switch
2286 if (ev == null ||
2287 SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_EVENT, 0) == 0) {
2288 return;
2289 }
2290 StringBuilder sb = new StringBuilder(subTag + ": ");
2291 sb.append(ev.getDownTime()).append(',');
2292 sb.append(ev.getEventTime()).append(',');
2293 sb.append(ev.getAction()).append(',');
2294 sb.append(ev.getKeyCode()).append(',');
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002295 sb.append(ev.getRepeatCount()).append(',');
2296 sb.append(ev.getMetaState()).append(',');
2297 sb.append(ev.getDeviceId()).append(',');
2298 sb.append(ev.getScanCode());
Romain Guy8506ab42009-06-11 17:35:47 -07002299 Log.d(TAG, sb.toString());
2300 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002301
2302 int enqueuePendingEvent(Object event, boolean sendDone) {
2303 int seq = mPendingEventSeq+1;
2304 if (seq < 0) seq = 0;
2305 mPendingEventSeq = seq;
2306 mPendingEvents.put(seq, event);
2307 return sendDone ? seq : -seq;
2308 }
2309
2310 Object retrievePendingEvent(int seq) {
2311 if (seq < 0) seq = -seq;
2312 Object event = mPendingEvents.get(seq);
2313 if (event != null) {
2314 mPendingEvents.remove(seq);
2315 }
2316 return event;
2317 }
Romain Guy8506ab42009-06-11 17:35:47 -07002318
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002319 private void deliverKeyEvent(KeyEvent event, boolean sendDone) {
2320 // If mView is null, we just consume the key event because it doesn't
2321 // make sense to do anything else with it.
Romain Guy812ccbe2010-06-01 14:07:24 -07002322 boolean handled = mView == null || mView.dispatchKeyEventPreIme(event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002323 if (handled) {
2324 if (sendDone) {
2325 if (LOCAL_LOGV) Log.v(
Jeff Brownc5ed5912010-07-14 18:48:53 -07002326 TAG, "Telling window manager key is finished");
Jeff Brown46b9ac02010-04-22 18:58:52 -07002327 finishKeyEvent(event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002328 }
2329 return;
2330 }
2331 // If it is possible for this window to interact with the input
2332 // method window, then we want to first dispatch our key events
2333 // to the input method.
2334 if (mLastWasImTarget) {
2335 InputMethodManager imm = InputMethodManager.peekInstance();
2336 if (imm != null && mView != null) {
2337 int seq = enqueuePendingEvent(event, sendDone);
2338 if (DEBUG_IMF) Log.v(TAG, "Sending key event to IME: seq="
2339 + seq + " event=" + event);
2340 imm.dispatchKeyEvent(mView.getContext(), seq, event,
2341 mInputMethodCallback);
2342 return;
2343 }
2344 }
2345 deliverKeyEventToViewHierarchy(event, sendDone);
2346 }
2347
2348 void handleFinishedEvent(int seq, boolean handled) {
2349 final KeyEvent event = (KeyEvent)retrievePendingEvent(seq);
2350 if (DEBUG_IMF) Log.v(TAG, "IME finished event: seq=" + seq
2351 + " handled=" + handled + " event=" + event);
2352 if (event != null) {
2353 final boolean sendDone = seq >= 0;
2354 if (!handled) {
2355 deliverKeyEventToViewHierarchy(event, sendDone);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002356 } else if (sendDone) {
2357 if (LOCAL_LOGV) Log.v(
Jeff Brownc5ed5912010-07-14 18:48:53 -07002358 TAG, "Telling window manager key is finished");
Jeff Brown46b9ac02010-04-22 18:58:52 -07002359 finishKeyEvent(event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002360 } else {
Jeff Brownc5ed5912010-07-14 18:48:53 -07002361 Log.w(TAG, "handleFinishedEvent(seq=" + seq
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002362 + " handled=" + handled + " ev=" + event
2363 + ") neither delivering nor finishing key");
2364 }
2365 }
2366 }
Romain Guy8506ab42009-06-11 17:35:47 -07002367
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002368 private void deliverKeyEventToViewHierarchy(KeyEvent event, boolean sendDone) {
2369 try {
2370 if (mView != null && mAdded) {
2371 final int action = event.getAction();
2372 boolean isDown = (action == KeyEvent.ACTION_DOWN);
2373
2374 if (checkForLeavingTouchModeAndConsume(event)) {
2375 return;
Romain Guy8506ab42009-06-11 17:35:47 -07002376 }
2377
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002378 if (Config.LOGV) {
2379 captureKeyLog("captureDispatchKeyEvent", event);
2380 }
2381 boolean keyHandled = mView.dispatchKeyEvent(event);
2382
2383 if (!keyHandled && isDown) {
2384 int direction = 0;
2385 switch (event.getKeyCode()) {
2386 case KeyEvent.KEYCODE_DPAD_LEFT:
2387 direction = View.FOCUS_LEFT;
2388 break;
2389 case KeyEvent.KEYCODE_DPAD_RIGHT:
2390 direction = View.FOCUS_RIGHT;
2391 break;
2392 case KeyEvent.KEYCODE_DPAD_UP:
2393 direction = View.FOCUS_UP;
2394 break;
2395 case KeyEvent.KEYCODE_DPAD_DOWN:
2396 direction = View.FOCUS_DOWN;
2397 break;
2398 }
2399
2400 if (direction != 0) {
2401
2402 View focused = mView != null ? mView.findFocus() : null;
2403 if (focused != null) {
2404 View v = focused.focusSearch(direction);
2405 boolean focusPassed = false;
2406 if (v != null && v != focused) {
2407 // do the math the get the interesting rect
2408 // of previous focused into the coord system of
2409 // newly focused view
2410 focused.getFocusedRect(mTempRect);
Dianne Hackborn1c6a8942010-03-23 16:34:20 -07002411 if (mView instanceof ViewGroup) {
2412 ((ViewGroup) mView).offsetDescendantRectToMyCoords(
2413 focused, mTempRect);
2414 ((ViewGroup) mView).offsetRectIntoDescendantCoords(
2415 v, mTempRect);
2416 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002417 focusPassed = v.requestFocus(direction, mTempRect);
2418 }
2419
2420 if (!focusPassed) {
2421 mView.dispatchUnhandledMove(focused, direction);
2422 } else {
2423 playSoundEffect(SoundEffectConstants.getContantForFocusDirection(direction));
2424 }
2425 }
2426 }
2427 }
2428 }
2429
2430 } finally {
2431 if (sendDone) {
2432 if (LOCAL_LOGV) Log.v(
Jeff Brownc5ed5912010-07-14 18:48:53 -07002433 TAG, "Telling window manager key is finished");
Jeff Brown46b9ac02010-04-22 18:58:52 -07002434 finishKeyEvent(event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002435 }
2436 // Let the exception fall through -- the looper will catch
2437 // it and take care of the bad app for us.
2438 }
2439 }
2440
2441 private AudioManager getAudioManager() {
2442 if (mView == null) {
2443 throw new IllegalStateException("getAudioManager called when there is no mView");
2444 }
2445 if (mAudioManager == null) {
2446 mAudioManager = (AudioManager) mView.getContext().getSystemService(Context.AUDIO_SERVICE);
2447 }
2448 return mAudioManager;
2449 }
2450
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002451 private int relayoutWindow(WindowManager.LayoutParams params, int viewVisibility,
2452 boolean insetsPending) throws RemoteException {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002453
2454 float appScale = mAttachInfo.mApplicationScale;
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002455 boolean restore = false;
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002456 if (params != null && mTranslator != null) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07002457 restore = true;
2458 params.backup();
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002459 mTranslator.translateWindowLayout(params);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002460 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002461 if (params != null) {
2462 if (DBG) Log.d(TAG, "WindowLayout in layoutWindow:" + params);
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002463 }
Dianne Hackborn694f79b2010-03-17 19:44:59 -07002464 mPendingConfiguration.seq = 0;
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002465 int relayoutResult = sWindowSession.relayout(
2466 mWindow, params,
Mitsuru Oshima61324e52009-07-21 15:40:36 -07002467 (int) (mView.mMeasuredWidth * appScale + 0.5f),
2468 (int) (mView.mMeasuredHeight * appScale + 0.5f),
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002469 viewVisibility, insetsPending, mWinFrame,
Dianne Hackborn694f79b2010-03-17 19:44:59 -07002470 mPendingContentInsets, mPendingVisibleInsets,
2471 mPendingConfiguration, mSurface);
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002472 if (restore) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07002473 params.restore();
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002474 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002475
2476 if (mTranslator != null) {
2477 mTranslator.translateRectInScreenToAppWinFrame(mWinFrame);
2478 mTranslator.translateRectInScreenToAppWindow(mPendingContentInsets);
2479 mTranslator.translateRectInScreenToAppWindow(mPendingVisibleInsets);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002480 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002481 return relayoutResult;
2482 }
Romain Guy8506ab42009-06-11 17:35:47 -07002483
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002484 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002485 * {@inheritDoc}
2486 */
2487 public void playSoundEffect(int effectId) {
2488 checkThread();
2489
Jean-Michel Trivi13b18fd2010-05-05 09:18:15 -07002490 try {
2491 final AudioManager audioManager = getAudioManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002492
Jean-Michel Trivi13b18fd2010-05-05 09:18:15 -07002493 switch (effectId) {
2494 case SoundEffectConstants.CLICK:
2495 audioManager.playSoundEffect(AudioManager.FX_KEY_CLICK);
2496 return;
2497 case SoundEffectConstants.NAVIGATION_DOWN:
2498 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_DOWN);
2499 return;
2500 case SoundEffectConstants.NAVIGATION_LEFT:
2501 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_LEFT);
2502 return;
2503 case SoundEffectConstants.NAVIGATION_RIGHT:
2504 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_RIGHT);
2505 return;
2506 case SoundEffectConstants.NAVIGATION_UP:
2507 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_UP);
2508 return;
2509 default:
2510 throw new IllegalArgumentException("unknown effect id " + effectId +
2511 " not defined in " + SoundEffectConstants.class.getCanonicalName());
2512 }
2513 } catch (IllegalStateException e) {
2514 // Exception thrown by getAudioManager() when mView is null
2515 Log.e(TAG, "FATAL EXCEPTION when attempting to play sound effect: " + e);
2516 e.printStackTrace();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002517 }
2518 }
2519
2520 /**
2521 * {@inheritDoc}
2522 */
2523 public boolean performHapticFeedback(int effectId, boolean always) {
2524 try {
2525 return sWindowSession.performHapticFeedback(mWindow, effectId, always);
2526 } catch (RemoteException e) {
2527 return false;
2528 }
2529 }
2530
2531 /**
2532 * {@inheritDoc}
2533 */
2534 public View focusSearch(View focused, int direction) {
2535 checkThread();
2536 if (!(mView instanceof ViewGroup)) {
2537 return null;
2538 }
2539 return FocusFinder.getInstance().findNextFocus((ViewGroup) mView, focused, direction);
2540 }
2541
2542 public void debug() {
2543 mView.debug();
2544 }
2545
2546 public void die(boolean immediate) {
Dianne Hackborn94d69142009-09-28 22:14:42 -07002547 if (immediate) {
2548 doDie();
2549 } else {
2550 sendEmptyMessage(DIE);
2551 }
2552 }
2553
2554 void doDie() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002555 checkThread();
Jeff Brownb75fa302010-07-15 23:47:29 -07002556 if (LOCAL_LOGV) Log.v(TAG, "DIE in " + this + " of " + mSurface);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002557 synchronized (this) {
2558 if (mAdded && !mFirst) {
2559 int viewVisibility = mView.getVisibility();
2560 boolean viewVisibilityChanged = mViewVisibility != viewVisibility;
2561 if (mWindowAttributesChanged || viewVisibilityChanged) {
2562 // If layout params have been changed, first give them
2563 // to the window manager to make sure it has the correct
2564 // animation info.
2565 try {
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002566 if ((relayoutWindow(mWindowAttributes, viewVisibility, false)
2567 & WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002568 sWindowSession.finishDrawing(mWindow);
2569 }
2570 } catch (RemoteException e) {
2571 }
2572 }
2573
Dianne Hackborn0586a1b2009-09-06 21:08:27 -07002574 mSurface.release();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002575 }
2576 if (mAdded) {
2577 mAdded = false;
Dianne Hackborn94d69142009-09-28 22:14:42 -07002578 dispatchDetachedFromWindow();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002579 }
2580 }
2581 }
2582
2583 public void dispatchFinishedEvent(int seq, boolean handled) {
2584 Message msg = obtainMessage(FINISHED_EVENT);
2585 msg.arg1 = seq;
2586 msg.arg2 = handled ? 1 : 0;
2587 sendMessage(msg);
2588 }
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002589
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002590 public void dispatchResized(int w, int h, Rect coveredInsets,
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002591 Rect visibleInsets, boolean reportDraw, Configuration newConfig) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002592 if (DEBUG_LAYOUT) Log.v(TAG, "Resizing " + this + ": w=" + w
2593 + " h=" + h + " coveredInsets=" + coveredInsets.toShortString()
2594 + " visibleInsets=" + visibleInsets.toShortString()
2595 + " reportDraw=" + reportDraw);
2596 Message msg = obtainMessage(reportDraw ? RESIZED_REPORT :RESIZED);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002597 if (mTranslator != null) {
2598 mTranslator.translateRectInScreenToAppWindow(coveredInsets);
2599 mTranslator.translateRectInScreenToAppWindow(visibleInsets);
2600 w *= mTranslator.applicationInvertedScale;
2601 h *= mTranslator.applicationInvertedScale;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002602 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002603 msg.arg1 = w;
2604 msg.arg2 = h;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002605 ResizedInfo ri = new ResizedInfo();
2606 ri.coveredInsets = new Rect(coveredInsets);
2607 ri.visibleInsets = new Rect(visibleInsets);
2608 ri.newConfig = newConfig;
2609 msg.obj = ri;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002610 sendMessage(msg);
2611 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002612
2613 private Runnable mFinishedCallback;
2614
2615 private final InputHandler mInputHandler = new InputHandler() {
2616 public void handleKey(KeyEvent event, Runnable finishedCallback) {
2617 mFinishedCallback = finishedCallback;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002618
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002619 dispatchKey(event);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002620 }
2621
Jeff Brownc5ed5912010-07-14 18:48:53 -07002622 public void handleMotion(MotionEvent event, Runnable finishedCallback) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002623 finishedCallback.run();
2624
Jeff Brownc5ed5912010-07-14 18:48:53 -07002625 dispatchMotion(event);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002626 }
2627 };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002628
2629 public void dispatchKey(KeyEvent event) {
2630 if (event.getAction() == KeyEvent.ACTION_DOWN) {
2631 //noinspection ConstantConditions
2632 if (false && event.getKeyCode() == KeyEvent.KEYCODE_CAMERA) {
Romain Guy812ccbe2010-06-01 14:07:24 -07002633 if (DBG) Log.d("keydisp", "===================================================");
2634 if (DBG) Log.d("keydisp", "Focused view Hierarchy is:");
2635
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002636 debug();
2637
Romain Guy812ccbe2010-06-01 14:07:24 -07002638 if (DBG) Log.d("keydisp", "===================================================");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002639 }
2640 }
2641
2642 Message msg = obtainMessage(DISPATCH_KEY);
2643 msg.obj = event;
2644
2645 if (LOCAL_LOGV) Log.v(
Jeff Brownc5ed5912010-07-14 18:48:53 -07002646 TAG, "sending key " + event + " to " + mView);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002647
2648 sendMessageAtTime(msg, event.getEventTime());
2649 }
Jeff Brownc5ed5912010-07-14 18:48:53 -07002650
2651 public void dispatchMotion(MotionEvent event) {
2652 int source = event.getSource();
2653 if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
2654 dispatchPointer(event);
2655 } else if ((source & InputDevice.SOURCE_CLASS_TRACKBALL) != 0) {
2656 dispatchTrackball(event);
2657 } else {
2658 // TODO
2659 Log.v(TAG, "Dropping unsupported motion event (unimplemented): " + event);
2660 }
2661 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002662
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002663 public void dispatchPointer(MotionEvent event) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002664 Message msg = obtainMessage(DISPATCH_POINTER);
2665 msg.obj = event;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002666 sendMessageAtTime(msg, event.getEventTime());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002667 }
2668
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002669 public void dispatchTrackball(MotionEvent event) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002670 Message msg = obtainMessage(DISPATCH_TRACKBALL);
2671 msg.obj = event;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002672 sendMessageAtTime(msg, event.getEventTime());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002673 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002674
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002675 public void dispatchAppVisibility(boolean visible) {
2676 Message msg = obtainMessage(DISPATCH_APP_VISIBILITY);
2677 msg.arg1 = visible ? 1 : 0;
2678 sendMessage(msg);
2679 }
2680
2681 public void dispatchGetNewSurface() {
2682 Message msg = obtainMessage(DISPATCH_GET_NEW_SURFACE);
2683 sendMessage(msg);
2684 }
2685
2686 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
2687 Message msg = Message.obtain();
2688 msg.what = WINDOW_FOCUS_CHANGED;
2689 msg.arg1 = hasFocus ? 1 : 0;
2690 msg.arg2 = inTouchMode ? 1 : 0;
2691 sendMessage(msg);
2692 }
2693
Dianne Hackbornffa42482009-09-23 22:20:11 -07002694 public void dispatchCloseSystemDialogs(String reason) {
2695 Message msg = Message.obtain();
2696 msg.what = CLOSE_SYSTEM_DIALOGS;
2697 msg.obj = reason;
2698 sendMessage(msg);
2699 }
2700
svetoslavganov75986cf2009-05-14 22:28:01 -07002701 /**
2702 * The window is getting focus so if there is anything focused/selected
2703 * send an {@link AccessibilityEvent} to announce that.
2704 */
2705 private void sendAccessibilityEvents() {
2706 if (!AccessibilityManager.getInstance(mView.getContext()).isEnabled()) {
2707 return;
2708 }
2709 mView.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
2710 View focusedView = mView.findFocus();
2711 if (focusedView != null && focusedView != mView) {
2712 focusedView.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
2713 }
2714 }
2715
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002716 public boolean showContextMenuForChild(View originalView) {
2717 return false;
2718 }
2719
Adam Powell6e346362010-07-23 10:18:23 -07002720 public ActionMode startActionModeForChild(View originalView, ActionMode.Callback callback) {
2721 return null;
2722 }
2723
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002724 public void createContextMenu(ContextMenu menu) {
2725 }
2726
2727 public void childDrawableStateChanged(View child) {
2728 }
2729
2730 protected Rect getWindowFrame() {
2731 return mWinFrame;
2732 }
2733
2734 void checkThread() {
2735 if (mThread != Thread.currentThread()) {
2736 throw new CalledFromWrongThreadException(
2737 "Only the original thread that created a view hierarchy can touch its views.");
2738 }
2739 }
2740
2741 public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
2742 // ViewRoot never intercepts touch event, so this can be a no-op
2743 }
2744
2745 public boolean requestChildRectangleOnScreen(View child, Rect rectangle,
2746 boolean immediate) {
2747 return scrollToRectOrFocus(rectangle, immediate);
2748 }
Romain Guy8506ab42009-06-11 17:35:47 -07002749
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07002750 class TakenSurfaceHolder extends BaseSurfaceHolder {
2751 @Override
2752 public boolean onAllowLockCanvas() {
2753 return mDrawingAllowed;
2754 }
2755
2756 @Override
2757 public void onRelayoutContainer() {
2758 // Not currently interesting -- from changing between fixed and layout size.
2759 }
2760
2761 public void setFormat(int format) {
2762 ((RootViewSurfaceTaker)mView).setSurfaceFormat(format);
2763 }
2764
2765 public void setType(int type) {
2766 ((RootViewSurfaceTaker)mView).setSurfaceType(type);
2767 }
2768
2769 @Override
2770 public void onUpdateSurface() {
2771 // We take care of format and type changes on our own.
2772 throw new IllegalStateException("Shouldn't be here");
2773 }
2774
2775 public boolean isCreating() {
2776 return mIsCreating;
2777 }
2778
2779 @Override
2780 public void setFixedSize(int width, int height) {
2781 throw new UnsupportedOperationException(
2782 "Currently only support sizing from layout");
2783 }
2784
2785 public void setKeepScreenOn(boolean screenOn) {
2786 ((RootViewSurfaceTaker)mView).setSurfaceKeepScreenOn(screenOn);
2787 }
2788 }
2789
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002790 static class InputMethodCallback extends IInputMethodCallback.Stub {
2791 private WeakReference<ViewRoot> mViewRoot;
2792
2793 public InputMethodCallback(ViewRoot viewRoot) {
2794 mViewRoot = new WeakReference<ViewRoot>(viewRoot);
2795 }
Romain Guy8506ab42009-06-11 17:35:47 -07002796
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002797 public void finishedEvent(int seq, boolean handled) {
2798 final ViewRoot viewRoot = mViewRoot.get();
2799 if (viewRoot != null) {
2800 viewRoot.dispatchFinishedEvent(seq, handled);
2801 }
2802 }
2803
2804 public void sessionCreated(IInputMethodSession session) throws RemoteException {
2805 // Stub -- not for use in the client.
2806 }
2807 }
Romain Guy8506ab42009-06-11 17:35:47 -07002808
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002809 static class W extends IWindow.Stub {
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002810 private final WeakReference<ViewRoot> mViewRoot;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002811
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002812 public W(ViewRoot viewRoot, Context context) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002813 mViewRoot = new WeakReference<ViewRoot>(viewRoot);
2814 }
2815
2816 public void resized(int w, int h, Rect coveredInsets,
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002817 Rect visibleInsets, boolean reportDraw, Configuration newConfig) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002818 final ViewRoot viewRoot = mViewRoot.get();
2819 if (viewRoot != null) {
2820 viewRoot.dispatchResized(w, h, coveredInsets,
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002821 visibleInsets, reportDraw, newConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002822 }
2823 }
2824
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002825 public void dispatchAppVisibility(boolean visible) {
2826 final ViewRoot viewRoot = mViewRoot.get();
2827 if (viewRoot != null) {
2828 viewRoot.dispatchAppVisibility(visible);
2829 }
2830 }
2831
2832 public void dispatchGetNewSurface() {
2833 final ViewRoot viewRoot = mViewRoot.get();
2834 if (viewRoot != null) {
2835 viewRoot.dispatchGetNewSurface();
2836 }
2837 }
2838
2839 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
2840 final ViewRoot viewRoot = mViewRoot.get();
2841 if (viewRoot != null) {
2842 viewRoot.windowFocusChanged(hasFocus, inTouchMode);
2843 }
2844 }
2845
2846 private static int checkCallingPermission(String permission) {
2847 if (!Process.supportsProcesses()) {
2848 return PackageManager.PERMISSION_GRANTED;
2849 }
2850
2851 try {
2852 return ActivityManagerNative.getDefault().checkPermission(
2853 permission, Binder.getCallingPid(), Binder.getCallingUid());
2854 } catch (RemoteException e) {
2855 return PackageManager.PERMISSION_DENIED;
2856 }
2857 }
2858
2859 public void executeCommand(String command, String parameters, ParcelFileDescriptor out) {
2860 final ViewRoot viewRoot = mViewRoot.get();
2861 if (viewRoot != null) {
2862 final View view = viewRoot.mView;
2863 if (view != null) {
2864 if (checkCallingPermission(Manifest.permission.DUMP) !=
2865 PackageManager.PERMISSION_GRANTED) {
2866 throw new SecurityException("Insufficient permissions to invoke"
2867 + " executeCommand() from pid=" + Binder.getCallingPid()
2868 + ", uid=" + Binder.getCallingUid());
2869 }
2870
2871 OutputStream clientStream = null;
2872 try {
2873 clientStream = new ParcelFileDescriptor.AutoCloseOutputStream(out);
2874 ViewDebug.dispatchCommand(view, command, parameters, clientStream);
2875 } catch (IOException e) {
2876 e.printStackTrace();
2877 } finally {
2878 if (clientStream != null) {
2879 try {
2880 clientStream.close();
2881 } catch (IOException e) {
2882 e.printStackTrace();
2883 }
2884 }
2885 }
2886 }
2887 }
2888 }
Dianne Hackborn72c82ab2009-08-11 21:13:54 -07002889
Dianne Hackbornffa42482009-09-23 22:20:11 -07002890 public void closeSystemDialogs(String reason) {
2891 final ViewRoot viewRoot = mViewRoot.get();
2892 if (viewRoot != null) {
2893 viewRoot.dispatchCloseSystemDialogs(reason);
2894 }
2895 }
2896
Marco Nelissenbf6956b2009-11-09 15:21:13 -08002897 public void dispatchWallpaperOffsets(float x, float y, float xStep, float yStep,
2898 boolean sync) {
Dianne Hackborn19382ac2009-09-11 21:13:37 -07002899 if (sync) {
2900 try {
2901 sWindowSession.wallpaperOffsetsComplete(asBinder());
2902 } catch (RemoteException e) {
2903 }
2904 }
Dianne Hackborn72c82ab2009-08-11 21:13:54 -07002905 }
Dianne Hackborn75804932009-10-20 20:15:20 -07002906
2907 public void dispatchWallpaperCommand(String action, int x, int y,
2908 int z, Bundle extras, boolean sync) {
2909 if (sync) {
2910 try {
2911 sWindowSession.wallpaperCommandComplete(asBinder(), null);
2912 } catch (RemoteException e) {
2913 }
2914 }
2915 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002916 }
2917
2918 /**
2919 * Maintains state information for a single trackball axis, generating
2920 * discrete (DPAD) movements based on raw trackball motion.
2921 */
2922 static final class TrackballAxis {
2923 /**
2924 * The maximum amount of acceleration we will apply.
2925 */
2926 static final float MAX_ACCELERATION = 20;
Romain Guy8506ab42009-06-11 17:35:47 -07002927
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002928 /**
2929 * The maximum amount of time (in milliseconds) between events in order
2930 * for us to consider the user to be doing fast trackball movements,
2931 * and thus apply an acceleration.
2932 */
2933 static final long FAST_MOVE_TIME = 150;
Romain Guy8506ab42009-06-11 17:35:47 -07002934
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002935 /**
2936 * Scaling factor to the time (in milliseconds) between events to how
2937 * much to multiple/divide the current acceleration. When movement
2938 * is < FAST_MOVE_TIME this multiplies the acceleration; when >
2939 * FAST_MOVE_TIME it divides it.
2940 */
2941 static final float ACCEL_MOVE_SCALING_FACTOR = (1.0f/40);
Romain Guy8506ab42009-06-11 17:35:47 -07002942
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002943 float position;
2944 float absPosition;
2945 float acceleration = 1;
2946 long lastMoveTime = 0;
2947 int step;
2948 int dir;
2949 int nonAccelMovement;
2950
2951 void reset(int _step) {
2952 position = 0;
2953 acceleration = 1;
2954 lastMoveTime = 0;
2955 step = _step;
2956 dir = 0;
2957 }
2958
2959 /**
2960 * Add trackball movement into the state. If the direction of movement
2961 * has been reversed, the state is reset before adding the
2962 * movement (so that you don't have to compensate for any previously
2963 * collected movement before see the result of the movement in the
2964 * new direction).
2965 *
2966 * @return Returns the absolute value of the amount of movement
2967 * collected so far.
2968 */
2969 float collect(float off, long time, String axis) {
2970 long normTime;
2971 if (off > 0) {
2972 normTime = (long)(off * FAST_MOVE_TIME);
2973 if (dir < 0) {
2974 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to positive!");
2975 position = 0;
2976 step = 0;
2977 acceleration = 1;
2978 lastMoveTime = 0;
2979 }
2980 dir = 1;
2981 } else if (off < 0) {
2982 normTime = (long)((-off) * FAST_MOVE_TIME);
2983 if (dir > 0) {
2984 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to negative!");
2985 position = 0;
2986 step = 0;
2987 acceleration = 1;
2988 lastMoveTime = 0;
2989 }
2990 dir = -1;
2991 } else {
2992 normTime = 0;
2993 }
Romain Guy8506ab42009-06-11 17:35:47 -07002994
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002995 // The number of milliseconds between each movement that is
2996 // considered "normal" and will not result in any acceleration
2997 // or deceleration, scaled by the offset we have here.
2998 if (normTime > 0) {
2999 long delta = time - lastMoveTime;
3000 lastMoveTime = time;
3001 float acc = acceleration;
3002 if (delta < normTime) {
3003 // The user is scrolling rapidly, so increase acceleration.
3004 float scale = (normTime-delta) * ACCEL_MOVE_SCALING_FACTOR;
3005 if (scale > 1) acc *= scale;
3006 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " accelerate: off="
3007 + off + " normTime=" + normTime + " delta=" + delta
3008 + " scale=" + scale + " acc=" + acc);
3009 acceleration = acc < MAX_ACCELERATION ? acc : MAX_ACCELERATION;
3010 } else {
3011 // The user is scrolling slowly, so decrease acceleration.
3012 float scale = (delta-normTime) * ACCEL_MOVE_SCALING_FACTOR;
3013 if (scale > 1) acc /= scale;
3014 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " deccelerate: off="
3015 + off + " normTime=" + normTime + " delta=" + delta
3016 + " scale=" + scale + " acc=" + acc);
3017 acceleration = acc > 1 ? acc : 1;
3018 }
3019 }
3020 position += off;
3021 return (absPosition = Math.abs(position));
3022 }
3023
3024 /**
3025 * Generate the number of discrete movement events appropriate for
3026 * the currently collected trackball movement.
3027 *
3028 * @param precision The minimum movement required to generate the
3029 * first discrete movement.
3030 *
3031 * @return Returns the number of discrete movements, either positive
3032 * or negative, or 0 if there is not enough trackball movement yet
3033 * for a discrete movement.
3034 */
3035 int generate(float precision) {
3036 int movement = 0;
3037 nonAccelMovement = 0;
3038 do {
3039 final int dir = position >= 0 ? 1 : -1;
3040 switch (step) {
3041 // If we are going to execute the first step, then we want
3042 // to do this as soon as possible instead of waiting for
3043 // a full movement, in order to make things look responsive.
3044 case 0:
3045 if (absPosition < precision) {
3046 return movement;
3047 }
3048 movement += dir;
3049 nonAccelMovement += dir;
3050 step = 1;
3051 break;
3052 // If we have generated the first movement, then we need
3053 // to wait for the second complete trackball motion before
3054 // generating the second discrete movement.
3055 case 1:
3056 if (absPosition < 2) {
3057 return movement;
3058 }
3059 movement += dir;
3060 nonAccelMovement += dir;
3061 position += dir > 0 ? -2 : 2;
3062 absPosition = Math.abs(position);
3063 step = 2;
3064 break;
3065 // After the first two, we generate discrete movements
3066 // consistently with the trackball, applying an acceleration
3067 // if the trackball is moving quickly. This is a simple
3068 // acceleration on top of what we already compute based
3069 // on how quickly the wheel is being turned, to apply
3070 // a longer increasing acceleration to continuous movement
3071 // in one direction.
3072 default:
3073 if (absPosition < 1) {
3074 return movement;
3075 }
3076 movement += dir;
3077 position += dir >= 0 ? -1 : 1;
3078 absPosition = Math.abs(position);
3079 float acc = acceleration;
3080 acc *= 1.1f;
3081 acceleration = acc < MAX_ACCELERATION ? acc : acceleration;
3082 break;
3083 }
3084 } while (true);
3085 }
3086 }
3087
3088 public static final class CalledFromWrongThreadException extends AndroidRuntimeException {
3089 public CalledFromWrongThreadException(String msg) {
3090 super(msg);
3091 }
3092 }
3093
3094 private SurfaceHolder mHolder = new SurfaceHolder() {
3095 // we only need a SurfaceHolder for opengl. it would be nice
3096 // to implement everything else though, especially the callback
3097 // support (opengl doesn't make use of it right now, but eventually
3098 // will).
3099 public Surface getSurface() {
3100 return mSurface;
3101 }
3102
3103 public boolean isCreating() {
3104 return false;
3105 }
3106
3107 public void addCallback(Callback callback) {
3108 }
3109
3110 public void removeCallback(Callback callback) {
3111 }
3112
3113 public void setFixedSize(int width, int height) {
3114 }
3115
3116 public void setSizeFromLayout() {
3117 }
3118
3119 public void setFormat(int format) {
3120 }
3121
3122 public void setType(int type) {
3123 }
3124
3125 public void setKeepScreenOn(boolean screenOn) {
3126 }
3127
3128 public Canvas lockCanvas() {
3129 return null;
3130 }
3131
3132 public Canvas lockCanvas(Rect dirty) {
3133 return null;
3134 }
3135
3136 public void unlockCanvasAndPost(Canvas canvas) {
3137 }
3138 public Rect getSurfaceFrame() {
3139 return null;
3140 }
3141 };
3142
3143 static RunQueue getRunQueue() {
3144 RunQueue rq = sRunQueues.get();
3145 if (rq != null) {
3146 return rq;
3147 }
3148 rq = new RunQueue();
3149 sRunQueues.set(rq);
3150 return rq;
3151 }
Romain Guy8506ab42009-06-11 17:35:47 -07003152
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003153 /**
3154 * @hide
3155 */
3156 static final class RunQueue {
3157 private final ArrayList<HandlerAction> mActions = new ArrayList<HandlerAction>();
3158
3159 void post(Runnable action) {
3160 postDelayed(action, 0);
3161 }
3162
3163 void postDelayed(Runnable action, long delayMillis) {
3164 HandlerAction handlerAction = new HandlerAction();
3165 handlerAction.action = action;
3166 handlerAction.delay = delayMillis;
3167
3168 synchronized (mActions) {
3169 mActions.add(handlerAction);
3170 }
3171 }
3172
3173 void removeCallbacks(Runnable action) {
3174 final HandlerAction handlerAction = new HandlerAction();
3175 handlerAction.action = action;
3176
3177 synchronized (mActions) {
3178 final ArrayList<HandlerAction> actions = mActions;
3179
3180 while (actions.remove(handlerAction)) {
3181 // Keep going
3182 }
3183 }
3184 }
3185
3186 void executeActions(Handler handler) {
3187 synchronized (mActions) {
3188 final ArrayList<HandlerAction> actions = mActions;
3189 final int count = actions.size();
3190
3191 for (int i = 0; i < count; i++) {
3192 final HandlerAction handlerAction = actions.get(i);
3193 handler.postDelayed(handlerAction.action, handlerAction.delay);
3194 }
3195
Romain Guy15df6702009-08-17 20:17:30 -07003196 actions.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003197 }
3198 }
3199
3200 private static class HandlerAction {
3201 Runnable action;
3202 long delay;
3203
3204 @Override
3205 public boolean equals(Object o) {
3206 if (this == o) return true;
3207 if (o == null || getClass() != o.getClass()) return false;
3208
3209 HandlerAction that = (HandlerAction) o;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003210 return !(action != null ? !action.equals(that.action) : that.action != null);
3211
3212 }
3213
3214 @Override
3215 public int hashCode() {
3216 int result = action != null ? action.hashCode() : 0;
3217 result = 31 * result + (int) (delay ^ (delay >>> 32));
3218 return result;
3219 }
3220 }
3221 }
3222
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003223 private static native void nativeShowFPS(Canvas canvas, int durationMillis);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003224}