blob: 0321be0c90e79a63646737b17ebb752eedeae58c [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.view;
18
Dianne Hackborndc8a7f62010-05-10 11:29:34 -070019import com.android.internal.view.BaseSurfaceHolder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080020import com.android.internal.view.IInputMethodCallback;
21import com.android.internal.view.IInputMethodSession;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -070022import com.android.internal.view.RootViewSurfaceTaker;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080023
24import android.graphics.Canvas;
25import android.graphics.PixelFormat;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080026import android.graphics.PorterDuff;
27import android.graphics.Rect;
28import android.graphics.Region;
29import android.os.*;
30import android.os.Process;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080031import android.util.AndroidRuntimeException;
32import android.util.Config;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -070033import android.util.DisplayMetrics;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080034import android.util.Log;
35import android.util.EventLog;
Chet Haase949dbf72010-08-11 18:41:06 -070036import android.util.Slog;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080037import android.util.SparseArray;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080038import android.view.View.MeasureSpec;
svetoslavganov75986cf2009-05-14 22:28:01 -070039import android.view.accessibility.AccessibilityEvent;
40import android.view.accessibility.AccessibilityManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080041import android.view.inputmethod.InputConnection;
42import android.view.inputmethod.InputMethodManager;
43import android.widget.Scroller;
44import android.content.pm.PackageManager;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -070045import android.content.res.CompatibilityInfo;
Dianne Hackborne36d6e22010-02-17 19:46:25 -080046import android.content.res.Configuration;
Mitsuru Oshima38ed7d772009-07-21 14:39:34 -070047import android.content.res.Resources;
Dianne Hackborne36d6e22010-02-17 19:46:25 -080048import android.content.ComponentCallbacks;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080049import android.content.Context;
50import android.app.ActivityManagerNative;
51import android.Manifest;
52import android.media.AudioManager;
53
54import java.lang.ref.WeakReference;
55import java.io.IOException;
56import java.io.OutputStream;
57import java.util.ArrayList;
58
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080059/**
60 * The top of a view hierarchy, implementing the needed protocol between View
61 * and the WindowManager. This is for the most part an internal implementation
62 * detail of {@link WindowManagerImpl}.
63 *
64 * {@hide}
65 */
Romain Guy812ccbe2010-06-01 14:07:24 -070066@SuppressWarnings({"EmptyCatchBlock", "PointlessBooleanExpression"})
67public final class ViewRoot extends Handler implements ViewParent, View.AttachInfo.Callbacks {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080068 private static final String TAG = "ViewRoot";
69 private static final boolean DBG = false;
Mike Reedfd716532009-10-12 14:42:56 -040070 private static final boolean SHOW_FPS = false;
Romain Guy812ccbe2010-06-01 14:07:24 -070071 private static final boolean LOCAL_LOGV = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080072 /** @noinspection PointlessBooleanExpression*/
73 private static final boolean DEBUG_DRAW = false || LOCAL_LOGV;
74 private static final boolean DEBUG_LAYOUT = false || LOCAL_LOGV;
Christopher Tatefa9e7c02010-05-06 12:07:10 -070075 private static final boolean DEBUG_INPUT = true || LOCAL_LOGV;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080076 private static final boolean DEBUG_INPUT_RESIZE = false || LOCAL_LOGV;
77 private static final boolean DEBUG_ORIENTATION = false || LOCAL_LOGV;
78 private static final boolean DEBUG_TRACKBALL = false || LOCAL_LOGV;
79 private static final boolean DEBUG_IMF = false || LOCAL_LOGV;
Dianne Hackborn694f79b2010-03-17 19:44:59 -070080 private static final boolean DEBUG_CONFIGURATION = false || LOCAL_LOGV;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080081 private static final boolean WATCH_POINTER = false;
82
Michael Chan53071d62009-05-13 17:29:48 -070083 private static final boolean MEASURE_LATENCY = false;
84 private static LatencyTimer lt;
85
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080086 /**
87 * Maximum time we allow the user to roll the trackball enough to generate
88 * a key event, before resetting the counters.
89 */
90 static final int MAX_TRACKBALL_DELAY = 250;
91
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080092 static IWindowSession sWindowSession;
93
94 static final Object mStaticInit = new Object();
95 static boolean mInitialized = false;
96
97 static final ThreadLocal<RunQueue> sRunQueues = new ThreadLocal<RunQueue>();
98
Dianne Hackborn2a9094d2010-02-03 19:20:09 -080099 static final ArrayList<Runnable> sFirstDrawHandlers = new ArrayList<Runnable>();
100 static boolean sFirstDrawComplete = false;
101
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800102 static final ArrayList<ComponentCallbacks> sConfigCallbacks
103 = new ArrayList<ComponentCallbacks>();
104
Romain Guy8506ab42009-06-11 17:35:47 -0700105 private static int sDrawTime;
Romain Guy13922e02009-05-12 17:56:14 -0700106
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800107 long mLastTrackballTime = 0;
108 final TrackballAxis mTrackballAxisX = new TrackballAxis();
109 final TrackballAxis mTrackballAxisY = new TrackballAxis();
110
111 final int[] mTmpLocation = new int[2];
Romain Guy8506ab42009-06-11 17:35:47 -0700112
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800113 final InputMethodCallback mInputMethodCallback;
114 final SparseArray<Object> mPendingEvents = new SparseArray<Object>();
115 int mPendingEventSeq = 0;
Romain Guy8506ab42009-06-11 17:35:47 -0700116
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800117 final Thread mThread;
118
119 final WindowLeaked mLocation;
120
121 final WindowManager.LayoutParams mWindowAttributes = new WindowManager.LayoutParams();
122
123 final W mWindow;
124
125 View mView;
126 View mFocusedView;
127 View mRealFocusedView; // this is not set to null in touch mode
128 int mViewVisibility;
129 boolean mAppVisible = true;
130
Dianne Hackbornd76b67c2010-07-13 17:48:30 -0700131 SurfaceHolder.Callback2 mSurfaceHolderCallback;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700132 BaseSurfaceHolder mSurfaceHolder;
133 boolean mIsCreating;
134 boolean mDrawingAllowed;
135
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800136 final Region mTransparentRegion;
137 final Region mPreviousTransparentRegion;
138
139 int mWidth;
140 int mHeight;
141 Rect mDirty; // will be a graphics.Region soon
Romain Guybb93d552009-03-24 21:04:15 -0700142 boolean mIsAnimating;
Romain Guy8506ab42009-06-11 17:35:47 -0700143
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700144 CompatibilityInfo.Translator mTranslator;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800145
146 final View.AttachInfo mAttachInfo;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700147 InputChannel mInputChannel;
Dianne Hackborn1e4b9f32010-06-23 14:10:57 -0700148 InputQueue.Callback mInputQueueCallback;
149 InputQueue mInputQueue;
Dianne Hackborna95e4cb2010-06-18 18:09:33 -0700150
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800151 final Rect mTempRect; // used in the transaction to not thrash the heap.
152 final Rect mVisRect; // used to retrieve visible rect of focused view.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800153
154 boolean mTraversalScheduled;
155 boolean mWillDrawSoon;
156 boolean mLayoutRequested;
157 boolean mFirst;
158 boolean mReportNextDraw;
159 boolean mFullRedrawNeeded;
160 boolean mNewSurfaceNeeded;
161 boolean mHasHadWindowFocus;
162 boolean mLastWasImTarget;
163
164 boolean mWindowAttributesChanged = false;
165
166 // These can be accessed by any thread, must be protected with a lock.
Mathias Agopian5583dc62009-07-09 16:28:11 -0700167 // Surface can never be reassigned or cleared (use Surface.clear()).
168 private final Surface mSurface = new Surface();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800169
170 boolean mAdded;
171 boolean mAddedTouchMode;
172
173 /*package*/ int mAddNesting;
174
175 // These are accessed by multiple threads.
176 final Rect mWinFrame; // frame given by window manager.
177
178 final Rect mPendingVisibleInsets = new Rect();
179 final Rect mPendingContentInsets = new Rect();
180 final ViewTreeObserver.InternalInsetsInfo mLastGivenInsets
181 = new ViewTreeObserver.InternalInsetsInfo();
182
Dianne Hackborn694f79b2010-03-17 19:44:59 -0700183 final Configuration mLastConfiguration = new Configuration();
184 final Configuration mPendingConfiguration = new Configuration();
185
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800186 class ResizedInfo {
187 Rect coveredInsets;
188 Rect visibleInsets;
189 Configuration newConfig;
190 }
191
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800192 boolean mScrollMayChange;
193 int mSoftInputMode;
194 View mLastScrolledFocus;
195 int mScrollY;
196 int mCurScrollY;
197 Scroller mScroller;
Romain Guy8506ab42009-06-11 17:35:47 -0700198
Romain Guy812ccbe2010-06-01 14:07:24 -0700199 HardwareRenderer mHwRenderer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800200
Romain Guy8506ab42009-06-11 17:35:47 -0700201 final ViewConfiguration mViewConfiguration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800202
203 /**
204 * see {@link #playSoundEffect(int)}
205 */
206 AudioManager mAudioManager;
207
Dianne Hackborn11ea3342009-07-22 21:48:55 -0700208 private final int mDensity;
Adam Powellb08013c2010-09-16 16:28:11 -0700209
Dianne Hackborn4c62fc02009-08-08 20:40:27 -0700210 public static IWindowSession getWindowSession(Looper mainLooper) {
211 synchronized (mStaticInit) {
212 if (!mInitialized) {
213 try {
214 InputMethodManager imm = InputMethodManager.getInstance(mainLooper);
215 sWindowSession = IWindowManager.Stub.asInterface(
216 ServiceManager.getService("window"))
217 .openSession(imm.getClient(), imm.getInputContext());
218 mInitialized = true;
219 } catch (RemoteException e) {
220 }
221 }
222 return sWindowSession;
223 }
224 }
225
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800226 public ViewRoot(Context context) {
227 super();
228
Romain Guy812ccbe2010-06-01 14:07:24 -0700229 if (MEASURE_LATENCY) {
230 if (lt == null) {
231 lt = new LatencyTimer(100, 1000);
232 }
Michael Chan53071d62009-05-13 17:29:48 -0700233 }
234
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800235 // Initialize the statics when this class is first instantiated. This is
236 // done here instead of in the static block because Zygote does not
237 // allow the spawning of threads.
Dianne Hackborn4c62fc02009-08-08 20:40:27 -0700238 getWindowSession(context.getMainLooper());
239
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800240 mThread = Thread.currentThread();
241 mLocation = new WindowLeaked(null);
242 mLocation.fillInStackTrace();
243 mWidth = -1;
244 mHeight = -1;
245 mDirty = new Rect();
246 mTempRect = new Rect();
247 mVisRect = new Rect();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800248 mWinFrame = new Rect();
Romain Guyfb8b7632010-08-23 21:05:08 -0700249 mWindow = new W(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800250 mInputMethodCallback = new InputMethodCallback(this);
251 mViewVisibility = View.GONE;
252 mTransparentRegion = new Region();
253 mPreviousTransparentRegion = new Region();
254 mFirst = true; // true for the first time the view is added
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800255 mAdded = false;
256 mAttachInfo = new View.AttachInfo(sWindowSession, mWindow, this, this);
257 mViewConfiguration = ViewConfiguration.get(context);
Dianne Hackborn11ea3342009-07-22 21:48:55 -0700258 mDensity = context.getResources().getDisplayMetrics().densityDpi;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800259 }
260
Dianne Hackborn2a9094d2010-02-03 19:20:09 -0800261 public static void addFirstDrawHandler(Runnable callback) {
262 synchronized (sFirstDrawHandlers) {
263 if (!sFirstDrawComplete) {
264 sFirstDrawHandlers.add(callback);
265 }
266 }
267 }
268
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800269 public static void addConfigCallback(ComponentCallbacks callback) {
270 synchronized (sConfigCallbacks) {
271 sConfigCallbacks.add(callback);
272 }
273 }
274
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800275 // FIXME for perf testing only
276 private boolean mProfile = false;
277
278 /**
279 * Call this to profile the next traversal call.
280 * FIXME for perf testing only. Remove eventually
281 */
282 public void profile() {
283 mProfile = true;
284 }
285
286 /**
287 * Indicates whether we are in touch mode. Calling this method triggers an IPC
288 * call and should be avoided whenever possible.
289 *
290 * @return True, if the device is in touch mode, false otherwise.
291 *
292 * @hide
293 */
294 static boolean isInTouchMode() {
295 if (mInitialized) {
296 try {
297 return sWindowSession.getInTouchMode();
298 } catch (RemoteException e) {
299 }
300 }
301 return false;
302 }
303
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800304 /**
305 * We have one child
306 */
Romain Guye4d01122010-06-16 18:44:05 -0700307 public void setView(View view, WindowManager.LayoutParams attrs, View panelParentView) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800308 synchronized (this) {
309 if (mView == null) {
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700310 mView = view;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700311 mWindowAttributes.copyFrom(attrs);
Mitsuru Oshima1ecf5d22009-07-06 17:20:38 -0700312 attrs = mWindowAttributes;
Romain Guye4d01122010-06-16 18:44:05 -0700313
Romain Guy529b60a2010-08-03 18:05:47 -0700314 enableHardwareAcceleration(attrs);
Romain Guye4d01122010-06-16 18:44:05 -0700315
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700316 if (view instanceof RootViewSurfaceTaker) {
317 mSurfaceHolderCallback =
318 ((RootViewSurfaceTaker)view).willYouTakeTheSurface();
319 if (mSurfaceHolderCallback != null) {
320 mSurfaceHolder = new TakenSurfaceHolder();
Dianne Hackborn289b9b62010-07-09 11:44:11 -0700321 mSurfaceHolder.setFormat(PixelFormat.UNKNOWN);
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700322 }
323 }
Mitsuru Oshima38ed7d772009-07-21 14:39:34 -0700324 Resources resources = mView.getContext().getResources();
325 CompatibilityInfo compatibilityInfo = resources.getCompatibilityInfo();
Mitsuru Oshima589cebe2009-07-22 20:38:58 -0700326 mTranslator = compatibilityInfo.getTranslator();
Mitsuru Oshima38ed7d772009-07-21 14:39:34 -0700327
328 if (mTranslator != null || !compatibilityInfo.supportsScreen()) {
Mitsuru Oshima240f8a72009-07-22 20:39:14 -0700329 mSurface.setCompatibleDisplayMetrics(resources.getDisplayMetrics(),
330 mTranslator);
Mitsuru Oshima38ed7d772009-07-21 14:39:34 -0700331 }
332
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -0700333 boolean restore = false;
Romain Guy35b38ce2009-10-07 13:38:55 -0700334 if (mTranslator != null) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -0700335 restore = true;
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700336 attrs.backup();
337 mTranslator.translateWindowLayout(attrs);
Mitsuru Oshima3d914922009-05-13 22:29:15 -0700338 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700339 if (DEBUG_LAYOUT) Log.d(TAG, "WindowLayout in setView:" + attrs);
340
Mitsuru Oshima1ecf5d22009-07-06 17:20:38 -0700341 if (!compatibilityInfo.supportsScreen()) {
342 attrs.flags |= WindowManager.LayoutParams.FLAG_COMPATIBLE_WINDOW;
343 }
344
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800345 mSoftInputMode = attrs.softInputMode;
346 mWindowAttributesChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800347 mAttachInfo.mRootView = view;
Romain Guy35b38ce2009-10-07 13:38:55 -0700348 mAttachInfo.mScalingRequired = mTranslator != null;
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700349 mAttachInfo.mApplicationScale =
350 mTranslator == null ? 1.0f : mTranslator.applicationScale;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800351 if (panelParentView != null) {
352 mAttachInfo.mPanelParentWindowToken
353 = panelParentView.getApplicationWindowToken();
354 }
355 mAdded = true;
356 int res; /* = WindowManagerImpl.ADD_OKAY; */
Romain Guy8506ab42009-06-11 17:35:47 -0700357
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800358 // Schedule the first layout -before- adding to the window
359 // manager, to make sure we do the relayout before receiving
360 // any other events from the system.
361 requestLayout();
Jeff Brown46b9ac02010-04-22 18:58:52 -0700362 mInputChannel = new InputChannel();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800363 try {
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700364 res = sWindowSession.add(mWindow, mWindowAttributes,
Jeff Brown46b9ac02010-04-22 18:58:52 -0700365 getHostVisibility(), mAttachInfo.mContentInsets,
366 mInputChannel);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800367 } catch (RemoteException e) {
368 mAdded = false;
369 mView = null;
370 mAttachInfo.mRootView = null;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700371 mInputChannel = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800372 unscheduleTraversals();
373 throw new RuntimeException("Adding window failed", e);
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700374 } finally {
375 if (restore) {
376 attrs.restore();
377 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800378 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700379
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700380 if (mTranslator != null) {
381 mTranslator.translateRectInScreenToAppWindow(mAttachInfo.mContentInsets);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700382 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800383 mPendingContentInsets.set(mAttachInfo.mContentInsets);
384 mPendingVisibleInsets.set(0, 0, 0, 0);
Jeff Brownc5ed5912010-07-14 18:48:53 -0700385 if (Config.LOGV) Log.v(TAG, "Added window " + mWindow);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800386 if (res < WindowManagerImpl.ADD_OKAY) {
387 mView = null;
388 mAttachInfo.mRootView = null;
389 mAdded = false;
390 unscheduleTraversals();
391 switch (res) {
392 case WindowManagerImpl.ADD_BAD_APP_TOKEN:
393 case WindowManagerImpl.ADD_BAD_SUBWINDOW_TOKEN:
394 throw new WindowManagerImpl.BadTokenException(
395 "Unable to add window -- token " + attrs.token
396 + " is not valid; is your activity running?");
397 case WindowManagerImpl.ADD_NOT_APP_TOKEN:
398 throw new WindowManagerImpl.BadTokenException(
399 "Unable to add window -- token " + attrs.token
400 + " is not for an application");
401 case WindowManagerImpl.ADD_APP_EXITING:
402 throw new WindowManagerImpl.BadTokenException(
403 "Unable to add window -- app for token " + attrs.token
404 + " is exiting");
405 case WindowManagerImpl.ADD_DUPLICATE_ADD:
406 throw new WindowManagerImpl.BadTokenException(
407 "Unable to add window -- window " + mWindow
408 + " has already been added");
409 case WindowManagerImpl.ADD_STARTING_NOT_NEEDED:
410 // Silently ignore -- we would have just removed it
411 // right away, anyway.
412 return;
413 case WindowManagerImpl.ADD_MULTIPLE_SINGLETON:
414 throw new WindowManagerImpl.BadTokenException(
415 "Unable to add window " + mWindow +
416 " -- another window of this type already exists");
417 case WindowManagerImpl.ADD_PERMISSION_DENIED:
418 throw new WindowManagerImpl.BadTokenException(
419 "Unable to add window " + mWindow +
420 " -- permission denied for this window type");
421 }
422 throw new RuntimeException(
423 "Unable to add window -- unknown error code " + res);
424 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700425
Jeff Brown00fa7bd2010-07-02 15:37:36 -0700426 if (view instanceof RootViewSurfaceTaker) {
427 mInputQueueCallback =
428 ((RootViewSurfaceTaker)view).willYouTakeTheInputQueue();
429 }
430 if (mInputQueueCallback != null) {
431 mInputQueue = new InputQueue(mInputChannel);
432 mInputQueueCallback.onInputQueueCreated(mInputQueue);
433 } else {
434 InputQueue.registerInputChannel(mInputChannel, mInputHandler,
435 Looper.myQueue());
Jeff Brown46b9ac02010-04-22 18:58:52 -0700436 }
437
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800438 view.assignParent(this);
439 mAddedTouchMode = (res&WindowManagerImpl.ADD_FLAG_IN_TOUCH_MODE) != 0;
440 mAppVisible = (res&WindowManagerImpl.ADD_FLAG_APP_VISIBLE) != 0;
441 }
442 }
443 }
444
Romain Guy529b60a2010-08-03 18:05:47 -0700445 private void enableHardwareAcceleration(WindowManager.LayoutParams attrs) {
Romain Guye4d01122010-06-16 18:44:05 -0700446 // Only enable hardware acceleration if we are not in the system process
447 // The window manager creates ViewRoots to display animated preview windows
448 // of launching apps and we don't want those to be hardware accelerated
Romain Guy52339202010-09-03 16:04:46 -0700449 if (!HardwareRenderer.sRendererDisabled) {
Romain Guye4d01122010-06-16 18:44:05 -0700450 // Try to enable hardware acceleration if requested
Romain Guy529b60a2010-08-03 18:05:47 -0700451 if (attrs != null &&
452 (attrs.flags & WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED) != 0) {
Romain Guye4d01122010-06-16 18:44:05 -0700453 final boolean translucent = attrs.format != PixelFormat.OPAQUE;
Romain Guy4caa4ed2010-08-25 14:46:24 -0700454 if (mHwRenderer != null) {
455 mHwRenderer.destroy(true);
456 }
Romain Guye4d01122010-06-16 18:44:05 -0700457 mHwRenderer = HardwareRenderer.createGlRenderer(2, translucent);
Romain Guy2bffd262010-09-12 17:40:02 -0700458 mAttachInfo.mHardwareAccelerated = true;
Romain Guye4d01122010-06-16 18:44:05 -0700459 }
460 }
461 }
462
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800463 public View getView() {
464 return mView;
465 }
466
467 final WindowLeaked getLocation() {
468 return mLocation;
469 }
470
471 void setLayoutParams(WindowManager.LayoutParams attrs, boolean newView) {
472 synchronized (this) {
The Android Open Source Project10592532009-03-18 17:39:46 -0700473 int oldSoftInputMode = mWindowAttributes.softInputMode;
Mitsuru Oshima5a2b91d2009-07-16 16:30:02 -0700474 // preserve compatible window flag if exists.
475 int compatibleWindowFlag =
476 mWindowAttributes.flags & WindowManager.LayoutParams.FLAG_COMPATIBLE_WINDOW;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800477 mWindowAttributes.copyFrom(attrs);
Mitsuru Oshima5a2b91d2009-07-16 16:30:02 -0700478 mWindowAttributes.flags |= compatibleWindowFlag;
479
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800480 if (newView) {
481 mSoftInputMode = attrs.softInputMode;
482 requestLayout();
483 }
The Android Open Source Project10592532009-03-18 17:39:46 -0700484 // Don't lose the mode we last auto-computed.
485 if ((attrs.softInputMode&WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST)
486 == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED) {
487 mWindowAttributes.softInputMode = (mWindowAttributes.softInputMode
488 & ~WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST)
489 | (oldSoftInputMode
490 & WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST);
491 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800492 mWindowAttributesChanged = true;
493 scheduleTraversals();
494 }
495 }
496
497 void handleAppVisibility(boolean visible) {
498 if (mAppVisible != visible) {
499 mAppVisible = visible;
500 scheduleTraversals();
501 }
502 }
503
504 void handleGetNewSurface() {
505 mNewSurfaceNeeded = true;
506 mFullRedrawNeeded = true;
507 scheduleTraversals();
508 }
509
510 /**
511 * {@inheritDoc}
512 */
513 public void requestLayout() {
514 checkThread();
515 mLayoutRequested = true;
516 scheduleTraversals();
517 }
518
519 /**
520 * {@inheritDoc}
521 */
522 public boolean isLayoutRequested() {
523 return mLayoutRequested;
524 }
525
526 public void invalidateChild(View child, Rect dirty) {
527 checkThread();
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700528 if (DEBUG_DRAW) Log.v(TAG, "Invalidate child: " + dirty);
529 if (mCurScrollY != 0 || mTranslator != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800530 mTempRect.set(dirty);
Romain Guy1e095972009-07-07 11:22:45 -0700531 dirty = mTempRect;
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700532 if (mCurScrollY != 0) {
Romain Guy1e095972009-07-07 11:22:45 -0700533 dirty.offset(0, -mCurScrollY);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700534 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700535 if (mTranslator != null) {
Romain Guy1e095972009-07-07 11:22:45 -0700536 mTranslator.translateRectInAppWindowToScreen(dirty);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700537 }
Romain Guy1e095972009-07-07 11:22:45 -0700538 if (mAttachInfo.mScalingRequired) {
539 dirty.inset(-1, -1);
540 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800541 }
542 mDirty.union(dirty);
543 if (!mWillDrawSoon) {
544 scheduleTraversals();
545 }
546 }
547
548 public ViewParent getParent() {
549 return null;
550 }
551
552 public ViewParent invalidateChildInParent(final int[] location, final Rect dirty) {
553 invalidateChild(null, dirty);
554 return null;
555 }
556
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700557 public boolean getChildVisibleRect(View child, Rect r, android.graphics.Point offset) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800558 if (child != mView) {
559 throw new RuntimeException("child is not mine, honest!");
560 }
561 // Note: don't apply scroll offset, because we want to know its
562 // visibility in the virtual canvas being given to the view hierarchy.
563 return r.intersect(0, 0, mWidth, mHeight);
564 }
565
566 public void bringChildToFront(View child) {
567 }
568
569 public void scheduleTraversals() {
570 if (!mTraversalScheduled) {
571 mTraversalScheduled = true;
572 sendEmptyMessage(DO_TRAVERSAL);
573 }
574 }
575
576 public void unscheduleTraversals() {
577 if (mTraversalScheduled) {
578 mTraversalScheduled = false;
579 removeMessages(DO_TRAVERSAL);
580 }
581 }
582
583 int getHostVisibility() {
584 return mAppVisible ? mView.getVisibility() : View.GONE;
585 }
Romain Guy8506ab42009-06-11 17:35:47 -0700586
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800587 private void performTraversals() {
588 // cache mView since it is used so much below...
589 final View host = mView;
590
591 if (DBG) {
592 System.out.println("======================================");
593 System.out.println("performTraversals");
594 host.debug();
595 }
596
597 if (host == null || !mAdded)
598 return;
599
600 mTraversalScheduled = false;
601 mWillDrawSoon = true;
602 boolean windowResizesToFitContent = false;
603 boolean fullRedrawNeeded = mFullRedrawNeeded;
604 boolean newSurface = false;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700605 boolean surfaceChanged = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800606 WindowManager.LayoutParams lp = mWindowAttributes;
607
608 int desiredWindowWidth;
609 int desiredWindowHeight;
610 int childWidthMeasureSpec;
611 int childHeightMeasureSpec;
612
613 final View.AttachInfo attachInfo = mAttachInfo;
614
615 final int viewVisibility = getHostVisibility();
616 boolean viewVisibilityChanged = mViewVisibility != viewVisibility
617 || mNewSurfaceNeeded;
618
619 WindowManager.LayoutParams params = null;
620 if (mWindowAttributesChanged) {
621 mWindowAttributesChanged = false;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700622 surfaceChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800623 params = lp;
624 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700625 Rect frame = mWinFrame;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800626 if (mFirst) {
627 fullRedrawNeeded = true;
628 mLayoutRequested = true;
629
Romain Guy8506ab42009-06-11 17:35:47 -0700630 DisplayMetrics packageMetrics =
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700631 mView.getContext().getResources().getDisplayMetrics();
632 desiredWindowWidth = packageMetrics.widthPixels;
633 desiredWindowHeight = packageMetrics.heightPixels;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800634
635 // For the very first time, tell the view hierarchy that it
636 // is attached to the window. Note that at this point the surface
637 // object is not initialized to its backing store, but soon it
638 // will be (assuming the window is visible).
639 attachInfo.mSurface = mSurface;
Dianne Hackborn289b9b62010-07-09 11:44:11 -0700640 attachInfo.mTranslucentWindow = PixelFormat.formatHasAlpha(lp.format);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800641 attachInfo.mHasWindowFocus = false;
642 attachInfo.mWindowVisibility = viewVisibility;
643 attachInfo.mRecomputeGlobalAttributes = false;
644 attachInfo.mKeepScreenOn = false;
645 viewVisibilityChanged = false;
Dianne Hackborn694f79b2010-03-17 19:44:59 -0700646 mLastConfiguration.setTo(host.getResources().getConfiguration());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800647 host.dispatchAttachedToWindow(attachInfo, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800648 //Log.i(TAG, "Screen on initialized: " + attachInfo.mKeepScreenOn);
svetoslavganov75986cf2009-05-14 22:28:01 -0700649
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800650 } else {
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700651 desiredWindowWidth = frame.width();
652 desiredWindowHeight = frame.height();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800653 if (desiredWindowWidth != mWidth || desiredWindowHeight != mHeight) {
Jeff Brownc5ed5912010-07-14 18:48:53 -0700654 if (DEBUG_ORIENTATION) Log.v(TAG,
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700655 "View " + host + " resized to: " + frame);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800656 fullRedrawNeeded = true;
657 mLayoutRequested = true;
658 windowResizesToFitContent = true;
659 }
660 }
661
662 if (viewVisibilityChanged) {
663 attachInfo.mWindowVisibility = viewVisibility;
664 host.dispatchWindowVisibilityChanged(viewVisibility);
665 if (viewVisibility != View.VISIBLE || mNewSurfaceNeeded) {
Romain Guy4caa4ed2010-08-25 14:46:24 -0700666 if (mHwRenderer != null) {
667 mHwRenderer.destroy(false);
668 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800669 }
670 if (viewVisibility == View.GONE) {
671 // After making a window gone, we will count it as being
672 // shown for the first time the next time it gets focus.
673 mHasHadWindowFocus = false;
674 }
675 }
676
677 boolean insetsChanged = false;
Romain Guy8506ab42009-06-11 17:35:47 -0700678
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800679 if (mLayoutRequested) {
Romain Guy15df6702009-08-17 20:17:30 -0700680 // Execute enqueued actions on every layout in case a view that was detached
681 // enqueued an action after being detached
682 getRunQueue().executeActions(attachInfo.mHandler);
683
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800684 if (mFirst) {
685 host.fitSystemWindows(mAttachInfo.mContentInsets);
686 // make sure touch mode code executes by setting cached value
687 // to opposite of the added touch mode.
688 mAttachInfo.mInTouchMode = !mAddedTouchMode;
Romain Guy2d4cff62010-04-09 15:39:00 -0700689 ensureTouchModeLocally(mAddedTouchMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800690 } else {
691 if (!mAttachInfo.mContentInsets.equals(mPendingContentInsets)) {
692 mAttachInfo.mContentInsets.set(mPendingContentInsets);
693 host.fitSystemWindows(mAttachInfo.mContentInsets);
694 insetsChanged = true;
695 if (DEBUG_LAYOUT) Log.v(TAG, "Content insets changing to: "
696 + mAttachInfo.mContentInsets);
697 }
698 if (!mAttachInfo.mVisibleInsets.equals(mPendingVisibleInsets)) {
699 mAttachInfo.mVisibleInsets.set(mPendingVisibleInsets);
700 if (DEBUG_LAYOUT) Log.v(TAG, "Visible insets changing to: "
701 + mAttachInfo.mVisibleInsets);
702 }
703 if (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT
704 || lp.height == ViewGroup.LayoutParams.WRAP_CONTENT) {
705 windowResizesToFitContent = true;
706
Romain Guy8506ab42009-06-11 17:35:47 -0700707 DisplayMetrics packageMetrics =
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700708 mView.getContext().getResources().getDisplayMetrics();
709 desiredWindowWidth = packageMetrics.widthPixels;
710 desiredWindowHeight = packageMetrics.heightPixels;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800711 }
712 }
713
714 childWidthMeasureSpec = getRootMeasureSpec(desiredWindowWidth, lp.width);
715 childHeightMeasureSpec = getRootMeasureSpec(desiredWindowHeight, lp.height);
716
717 // Ask host how big it wants to be
Jeff Brownc5ed5912010-07-14 18:48:53 -0700718 if (DEBUG_ORIENTATION || DEBUG_LAYOUT) Log.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800719 "Measuring " + host + " in display " + desiredWindowWidth
720 + "x" + desiredWindowHeight + "...");
721 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
722
723 if (DBG) {
724 System.out.println("======================================");
725 System.out.println("performTraversals -- after measure");
726 host.debug();
727 }
728 }
729
730 if (attachInfo.mRecomputeGlobalAttributes) {
731 //Log.i(TAG, "Computing screen on!");
732 attachInfo.mRecomputeGlobalAttributes = false;
733 boolean oldVal = attachInfo.mKeepScreenOn;
734 attachInfo.mKeepScreenOn = false;
735 host.dispatchCollectViewAttributes(0);
736 if (attachInfo.mKeepScreenOn != oldVal) {
737 params = lp;
738 //Log.i(TAG, "Keep screen on changed: " + attachInfo.mKeepScreenOn);
739 }
740 }
741
742 if (mFirst || attachInfo.mViewVisibilityChanged) {
743 attachInfo.mViewVisibilityChanged = false;
744 int resizeMode = mSoftInputMode &
745 WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST;
746 // If we are in auto resize mode, then we need to determine
747 // what mode to use now.
748 if (resizeMode == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED) {
749 final int N = attachInfo.mScrollContainers.size();
750 for (int i=0; i<N; i++) {
751 if (attachInfo.mScrollContainers.get(i).isShown()) {
752 resizeMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE;
753 }
754 }
755 if (resizeMode == 0) {
756 resizeMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN;
757 }
758 if ((lp.softInputMode &
759 WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) != resizeMode) {
760 lp.softInputMode = (lp.softInputMode &
761 ~WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) |
762 resizeMode;
763 params = lp;
764 }
765 }
766 }
Romain Guy8506ab42009-06-11 17:35:47 -0700767
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800768 if (params != null && (host.mPrivateFlags & View.REQUEST_TRANSPARENT_REGIONS) != 0) {
769 if (!PixelFormat.formatHasAlpha(params.format)) {
770 params.format = PixelFormat.TRANSLUCENT;
771 }
772 }
773
774 boolean windowShouldResize = mLayoutRequested && windowResizesToFitContent
Romain Guy2e4f4262010-04-06 11:07:52 -0700775 && ((mWidth != host.mMeasuredWidth || mHeight != host.mMeasuredHeight)
776 || (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT &&
777 frame.width() < desiredWindowWidth && frame.width() != mWidth)
778 || (lp.height == ViewGroup.LayoutParams.WRAP_CONTENT &&
779 frame.height() < desiredWindowHeight && frame.height() != mHeight));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800780
781 final boolean computesInternalInsets =
782 attachInfo.mTreeObserver.hasComputeInternalInsetsListeners();
Romain Guy812ccbe2010-06-01 14:07:24 -0700783
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800784 boolean insetsPending = false;
785 int relayoutResult = 0;
Romain Guy812ccbe2010-06-01 14:07:24 -0700786
787 if (mFirst || windowShouldResize || insetsChanged ||
788 viewVisibilityChanged || params != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800789
790 if (viewVisibility == View.VISIBLE) {
791 // If this window is giving internal insets to the window
792 // manager, and it is being added or changing its visibility,
793 // then we want to first give the window manager "fake"
794 // insets to cause it to effectively ignore the content of
795 // the window during layout. This avoids it briefly causing
796 // other windows to resize/move based on the raw frame of the
797 // window, waiting until we can finish laying out this window
798 // and get back to the window manager with the ultimately
799 // computed insets.
Romain Guy812ccbe2010-06-01 14:07:24 -0700800 insetsPending = computesInternalInsets && (mFirst || viewVisibilityChanged);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800801 }
802
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700803 if (mSurfaceHolder != null) {
804 mSurfaceHolder.mSurfaceLock.lock();
805 mDrawingAllowed = true;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700806 }
Romain Guy812ccbe2010-06-01 14:07:24 -0700807
808 boolean hwIntialized = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800809 boolean contentInsetsChanged = false;
Romain Guy13922e02009-05-12 17:56:14 -0700810 boolean visibleInsetsChanged;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700811 boolean hadSurface = mSurface.isValid();
Romain Guy812ccbe2010-06-01 14:07:24 -0700812
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800813 try {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800814 int fl = 0;
815 if (params != null) {
816 fl = params.flags;
817 if (attachInfo.mKeepScreenOn) {
818 params.flags |= WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
819 }
820 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700821 if (DEBUG_LAYOUT) {
822 Log.i(TAG, "host=w:" + host.mMeasuredWidth + ", h:" +
823 host.mMeasuredHeight + ", params=" + params);
824 }
825 relayoutResult = relayoutWindow(params, viewVisibility, insetsPending);
826
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800827 if (params != null) {
828 params.flags = fl;
829 }
830
831 if (DEBUG_LAYOUT) Log.v(TAG, "relayout: frame=" + frame.toShortString()
832 + " content=" + mPendingContentInsets.toShortString()
833 + " visible=" + mPendingVisibleInsets.toShortString()
834 + " surface=" + mSurface);
Romain Guy8506ab42009-06-11 17:35:47 -0700835
Dianne Hackborn694f79b2010-03-17 19:44:59 -0700836 if (mPendingConfiguration.seq != 0) {
837 if (DEBUG_CONFIGURATION) Log.v(TAG, "Visible with new config: "
838 + mPendingConfiguration);
839 updateConfiguration(mPendingConfiguration, !mFirst);
840 mPendingConfiguration.seq = 0;
841 }
842
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800843 contentInsetsChanged = !mPendingContentInsets.equals(
844 mAttachInfo.mContentInsets);
845 visibleInsetsChanged = !mPendingVisibleInsets.equals(
846 mAttachInfo.mVisibleInsets);
847 if (contentInsetsChanged) {
848 mAttachInfo.mContentInsets.set(mPendingContentInsets);
849 host.fitSystemWindows(mAttachInfo.mContentInsets);
850 if (DEBUG_LAYOUT) Log.v(TAG, "Content insets changing to: "
851 + mAttachInfo.mContentInsets);
852 }
853 if (visibleInsetsChanged) {
854 mAttachInfo.mVisibleInsets.set(mPendingVisibleInsets);
855 if (DEBUG_LAYOUT) Log.v(TAG, "Visible insets changing to: "
856 + mAttachInfo.mVisibleInsets);
857 }
858
859 if (!hadSurface) {
860 if (mSurface.isValid()) {
861 // If we are creating a new surface, then we need to
862 // completely redraw it. Also, when we get to the
863 // point of drawing it we will hold off and schedule
864 // a new traversal instead. This is so we can tell the
865 // window manager about all of the windows being displayed
866 // before actually drawing them, so it can display then
867 // all at once.
868 newSurface = true;
869 fullRedrawNeeded = true;
Jack Palevich61a6e682009-10-09 17:37:50 -0700870 mPreviousTransparentRegion.setEmpty();
Romain Guy8506ab42009-06-11 17:35:47 -0700871
Romain Guy812ccbe2010-06-01 14:07:24 -0700872 if (mHwRenderer != null) {
Romain Guy2d614592010-06-09 18:21:37 -0700873 hwIntialized = mHwRenderer.initialize(mHolder);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800874 }
875 }
876 } else if (!mSurface.isValid()) {
877 // If the surface has been removed, then reset the scroll
878 // positions.
879 mLastScrolledFocus = null;
880 mScrollY = mCurScrollY = 0;
881 if (mScroller != null) {
882 mScroller.abortAnimation();
883 }
884 }
885 } catch (RemoteException e) {
886 }
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700887
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800888 if (DEBUG_ORIENTATION) Log.v(
Jeff Brownc5ed5912010-07-14 18:48:53 -0700889 TAG, "Relayout returned: frame=" + frame + ", surface=" + mSurface);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800890
891 attachInfo.mWindowLeft = frame.left;
892 attachInfo.mWindowTop = frame.top;
893
894 // !!FIXME!! This next section handles the case where we did not get the
895 // window size we asked for. We should avoid this by getting a maximum size from
896 // the window session beforehand.
897 mWidth = frame.width();
898 mHeight = frame.height();
899
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700900 if (mSurfaceHolder != null) {
901 // The app owns the surface; tell it about what is going on.
902 if (mSurface.isValid()) {
903 // XXX .copyFrom() doesn't work!
904 //mSurfaceHolder.mSurface.copyFrom(mSurface);
905 mSurfaceHolder.mSurface = mSurface;
906 }
907 mSurfaceHolder.mSurfaceLock.unlock();
908 if (mSurface.isValid()) {
909 if (!hadSurface) {
910 mSurfaceHolder.ungetCallbacks();
911
912 mIsCreating = true;
913 mSurfaceHolderCallback.surfaceCreated(mSurfaceHolder);
914 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
915 if (callbacks != null) {
916 for (SurfaceHolder.Callback c : callbacks) {
917 c.surfaceCreated(mSurfaceHolder);
918 }
919 }
920 surfaceChanged = true;
921 }
922 if (surfaceChanged) {
923 mSurfaceHolderCallback.surfaceChanged(mSurfaceHolder,
924 lp.format, mWidth, mHeight);
925 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
926 if (callbacks != null) {
927 for (SurfaceHolder.Callback c : callbacks) {
928 c.surfaceChanged(mSurfaceHolder, lp.format,
929 mWidth, mHeight);
930 }
931 }
932 }
933 mIsCreating = false;
934 } else if (hadSurface) {
935 mSurfaceHolder.ungetCallbacks();
936 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
937 mSurfaceHolderCallback.surfaceDestroyed(mSurfaceHolder);
938 if (callbacks != null) {
939 for (SurfaceHolder.Callback c : callbacks) {
940 c.surfaceDestroyed(mSurfaceHolder);
941 }
942 }
943 mSurfaceHolder.mSurfaceLock.lock();
944 // Make surface invalid.
945 //mSurfaceHolder.mSurface.copyFrom(mSurface);
946 mSurfaceHolder.mSurface = new Surface();
947 mSurfaceHolder.mSurfaceLock.unlock();
948 }
949 }
Romain Guy53389bd2010-09-07 17:16:32 -0700950
951 if (hwIntialized || (windowShouldResize && mHwRenderer != null)) {
Romain Guyfb8b7632010-08-23 21:05:08 -0700952 mHwRenderer.setup(mWidth, mHeight);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800953 }
954
955 boolean focusChangedDueToTouchMode = ensureTouchModeLocally(
Romain Guy2d4cff62010-04-09 15:39:00 -0700956 (relayoutResult&WindowManagerImpl.RELAYOUT_IN_TOUCH_MODE) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800957 if (focusChangedDueToTouchMode || mWidth != host.mMeasuredWidth
958 || mHeight != host.mMeasuredHeight || contentInsetsChanged) {
959 childWidthMeasureSpec = getRootMeasureSpec(mWidth, lp.width);
960 childHeightMeasureSpec = getRootMeasureSpec(mHeight, lp.height);
961
962 if (DEBUG_LAYOUT) Log.v(TAG, "Ooops, something changed! mWidth="
963 + mWidth + " measuredWidth=" + host.mMeasuredWidth
964 + " mHeight=" + mHeight
965 + " measuredHeight" + host.mMeasuredHeight
966 + " coveredInsetsChanged=" + contentInsetsChanged);
Romain Guy8506ab42009-06-11 17:35:47 -0700967
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800968 // Ask host how big it wants to be
969 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
970
971 // Implementation of weights from WindowManager.LayoutParams
972 // We just grow the dimensions as needed and re-measure if
973 // needs be
974 int width = host.mMeasuredWidth;
975 int height = host.mMeasuredHeight;
976 boolean measureAgain = false;
977
978 if (lp.horizontalWeight > 0.0f) {
979 width += (int) ((mWidth - width) * lp.horizontalWeight);
980 childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(width,
981 MeasureSpec.EXACTLY);
982 measureAgain = true;
983 }
984 if (lp.verticalWeight > 0.0f) {
985 height += (int) ((mHeight - height) * lp.verticalWeight);
986 childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(height,
987 MeasureSpec.EXACTLY);
988 measureAgain = true;
989 }
990
991 if (measureAgain) {
992 if (DEBUG_LAYOUT) Log.v(TAG,
993 "And hey let's measure once more: width=" + width
994 + " height=" + height);
995 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
996 }
997
998 mLayoutRequested = true;
999 }
1000 }
1001
1002 final boolean didLayout = mLayoutRequested;
1003 boolean triggerGlobalLayoutListener = didLayout
1004 || attachInfo.mRecomputeGlobalAttributes;
1005 if (didLayout) {
1006 mLayoutRequested = false;
1007 mScrollMayChange = true;
1008 if (DEBUG_ORIENTATION || DEBUG_LAYOUT) Log.v(
Jeff Brownc5ed5912010-07-14 18:48:53 -07001009 TAG, "Laying out " + host + " to (" +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001010 host.mMeasuredWidth + ", " + host.mMeasuredHeight + ")");
Romain Guy13922e02009-05-12 17:56:14 -07001011 long startTime = 0L;
Romain Guy5429e1d2010-09-07 12:38:00 -07001012 if (ViewDebug.DEBUG_PROFILE_LAYOUT) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001013 startTime = SystemClock.elapsedRealtime();
1014 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001015 host.layout(0, 0, host.mMeasuredWidth, host.mMeasuredHeight);
1016
Romain Guy13922e02009-05-12 17:56:14 -07001017 if (Config.DEBUG && ViewDebug.consistencyCheckEnabled) {
1018 if (!host.dispatchConsistencyCheck(ViewDebug.CONSISTENCY_LAYOUT)) {
1019 throw new IllegalStateException("The view hierarchy is an inconsistent state,"
1020 + "please refer to the logs with the tag "
1021 + ViewDebug.CONSISTENCY_LOG_TAG + " for more infomation.");
1022 }
1023 }
1024
Romain Guy5429e1d2010-09-07 12:38:00 -07001025 if (ViewDebug.DEBUG_PROFILE_LAYOUT) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001026 EventLog.writeEvent(60001, SystemClock.elapsedRealtime() - startTime);
1027 }
1028
1029 // By this point all views have been sized and positionned
1030 // We can compute the transparent area
1031
1032 if ((host.mPrivateFlags & View.REQUEST_TRANSPARENT_REGIONS) != 0) {
1033 // start out transparent
1034 // TODO: AVOID THAT CALL BY CACHING THE RESULT?
1035 host.getLocationInWindow(mTmpLocation);
1036 mTransparentRegion.set(mTmpLocation[0], mTmpLocation[1],
1037 mTmpLocation[0] + host.mRight - host.mLeft,
1038 mTmpLocation[1] + host.mBottom - host.mTop);
1039
1040 host.gatherTransparentRegion(mTransparentRegion);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001041 if (mTranslator != null) {
1042 mTranslator.translateRegionInWindowToScreen(mTransparentRegion);
1043 }
1044
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001045 if (!mTransparentRegion.equals(mPreviousTransparentRegion)) {
1046 mPreviousTransparentRegion.set(mTransparentRegion);
1047 // reconfigure window manager
1048 try {
1049 sWindowSession.setTransparentRegion(mWindow, mTransparentRegion);
1050 } catch (RemoteException e) {
1051 }
1052 }
1053 }
1054
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001055 if (DBG) {
1056 System.out.println("======================================");
1057 System.out.println("performTraversals -- after setFrame");
1058 host.debug();
1059 }
1060 }
1061
1062 if (triggerGlobalLayoutListener) {
1063 attachInfo.mRecomputeGlobalAttributes = false;
1064 attachInfo.mTreeObserver.dispatchOnGlobalLayout();
1065 }
1066
1067 if (computesInternalInsets) {
1068 ViewTreeObserver.InternalInsetsInfo insets = attachInfo.mGivenInternalInsets;
1069 final Rect givenContent = attachInfo.mGivenInternalInsets.contentInsets;
1070 final Rect givenVisible = attachInfo.mGivenInternalInsets.visibleInsets;
1071 givenContent.left = givenContent.top = givenContent.right
1072 = givenContent.bottom = givenVisible.left = givenVisible.top
1073 = givenVisible.right = givenVisible.bottom = 0;
1074 attachInfo.mTreeObserver.dispatchOnComputeInternalInsets(insets);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001075 Rect contentInsets = insets.contentInsets;
1076 Rect visibleInsets = insets.visibleInsets;
1077 if (mTranslator != null) {
1078 contentInsets = mTranslator.getTranslatedContentInsets(contentInsets);
1079 visibleInsets = mTranslator.getTranslatedVisbileInsets(visibleInsets);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001080 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001081 if (insetsPending || !mLastGivenInsets.equals(insets)) {
1082 mLastGivenInsets.set(insets);
1083 try {
1084 sWindowSession.setInsets(mWindow, insets.mTouchableInsets,
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001085 contentInsets, visibleInsets);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001086 } catch (RemoteException e) {
1087 }
1088 }
1089 }
Romain Guy8506ab42009-06-11 17:35:47 -07001090
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001091 if (mFirst) {
1092 // handle first focus request
1093 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: mView.hasFocus()="
1094 + mView.hasFocus());
1095 if (mView != null) {
1096 if (!mView.hasFocus()) {
1097 mView.requestFocus(View.FOCUS_FORWARD);
1098 mFocusedView = mRealFocusedView = mView.findFocus();
1099 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: requested focused view="
1100 + mFocusedView);
1101 } else {
1102 mRealFocusedView = mView.findFocus();
1103 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: existing focused view="
1104 + mRealFocusedView);
1105 }
1106 }
1107 }
1108
1109 mFirst = false;
1110 mWillDrawSoon = false;
1111 mNewSurfaceNeeded = false;
1112 mViewVisibility = viewVisibility;
1113
1114 if (mAttachInfo.mHasWindowFocus) {
1115 final boolean imTarget = WindowManager.LayoutParams
1116 .mayUseInputMethod(mWindowAttributes.flags);
1117 if (imTarget != mLastWasImTarget) {
1118 mLastWasImTarget = imTarget;
1119 InputMethodManager imm = InputMethodManager.peekInstance();
1120 if (imm != null && imTarget) {
1121 imm.startGettingWindowFocus(mView);
1122 imm.onWindowFocus(mView, mView.findFocus(),
1123 mWindowAttributes.softInputMode,
1124 !mHasHadWindowFocus, mWindowAttributes.flags);
1125 }
1126 }
1127 }
Romain Guy8506ab42009-06-11 17:35:47 -07001128
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001129 boolean cancelDraw = attachInfo.mTreeObserver.dispatchOnPreDraw();
1130
1131 if (!cancelDraw && !newSurface) {
1132 mFullRedrawNeeded = false;
1133 draw(fullRedrawNeeded);
1134
1135 if ((relayoutResult&WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0
1136 || mReportNextDraw) {
1137 if (LOCAL_LOGV) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001138 Log.v(TAG, "FINISHED DRAWING: " + mWindowAttributes.getTitle());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001139 }
1140 mReportNextDraw = false;
Dianne Hackbornd76b67c2010-07-13 17:48:30 -07001141 if (mSurfaceHolder != null && mSurface.isValid()) {
1142 mSurfaceHolderCallback.surfaceRedrawNeeded(mSurfaceHolder);
1143 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
1144 if (callbacks != null) {
1145 for (SurfaceHolder.Callback c : callbacks) {
1146 if (c instanceof SurfaceHolder.Callback2) {
1147 ((SurfaceHolder.Callback2)c).surfaceRedrawNeeded(
1148 mSurfaceHolder);
1149 }
1150 }
1151 }
1152 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001153 try {
1154 sWindowSession.finishDrawing(mWindow);
1155 } catch (RemoteException e) {
1156 }
1157 }
1158 } else {
1159 // We were supposed to report when we are done drawing. Since we canceled the
1160 // draw, remember it here.
1161 if ((relayoutResult&WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0) {
1162 mReportNextDraw = true;
1163 }
1164 if (fullRedrawNeeded) {
1165 mFullRedrawNeeded = true;
1166 }
1167 // Try again
1168 scheduleTraversals();
1169 }
1170 }
1171
1172 public void requestTransparentRegion(View child) {
1173 // the test below should not fail unless someone is messing with us
1174 checkThread();
1175 if (mView == child) {
1176 mView.mPrivateFlags |= View.REQUEST_TRANSPARENT_REGIONS;
1177 // Need to make sure we re-evaluate the window attributes next
1178 // time around, to ensure the window has the correct format.
1179 mWindowAttributesChanged = true;
1180 }
1181 }
1182
1183 /**
1184 * Figures out the measure spec for the root view in a window based on it's
1185 * layout params.
1186 *
1187 * @param windowSize
1188 * The available width or height of the window
1189 *
1190 * @param rootDimension
1191 * The layout params for one dimension (width or height) of the
1192 * window.
1193 *
1194 * @return The measure spec to use to measure the root view.
1195 */
1196 private int getRootMeasureSpec(int windowSize, int rootDimension) {
1197 int measureSpec;
1198 switch (rootDimension) {
1199
Romain Guy980a9382010-01-08 15:06:28 -08001200 case ViewGroup.LayoutParams.MATCH_PARENT:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001201 // Window can't resize. Force root view to be windowSize.
1202 measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.EXACTLY);
1203 break;
1204 case ViewGroup.LayoutParams.WRAP_CONTENT:
1205 // Window can resize. Set max size for root view.
1206 measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.AT_MOST);
1207 break;
1208 default:
1209 // Window wants to be an exact size. Force root view to be that size.
1210 measureSpec = MeasureSpec.makeMeasureSpec(rootDimension, MeasureSpec.EXACTLY);
1211 break;
1212 }
1213 return measureSpec;
1214 }
1215
1216 private void draw(boolean fullRedrawNeeded) {
1217 Surface surface = mSurface;
1218 if (surface == null || !surface.isValid()) {
1219 return;
1220 }
1221
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001222 if (!sFirstDrawComplete) {
1223 synchronized (sFirstDrawHandlers) {
1224 sFirstDrawComplete = true;
Romain Guy812ccbe2010-06-01 14:07:24 -07001225 final int count = sFirstDrawHandlers.size();
1226 for (int i = 0; i< count; i++) {
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001227 post(sFirstDrawHandlers.get(i));
1228 }
1229 }
1230 }
1231
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001232 scrollToRectOrFocus(null, false);
1233
1234 if (mAttachInfo.mViewScrollChanged) {
1235 mAttachInfo.mViewScrollChanged = false;
1236 mAttachInfo.mTreeObserver.dispatchOnScrollChanged();
1237 }
Romain Guy8506ab42009-06-11 17:35:47 -07001238
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001239 int yoff;
Romain Guy5bcdff42009-05-14 21:27:18 -07001240 final boolean scrolling = mScroller != null && mScroller.computeScrollOffset();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001241 if (scrolling) {
1242 yoff = mScroller.getCurrY();
1243 } else {
1244 yoff = mScrollY;
1245 }
1246 if (mCurScrollY != yoff) {
1247 mCurScrollY = yoff;
1248 fullRedrawNeeded = true;
1249 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001250 float appScale = mAttachInfo.mApplicationScale;
1251 boolean scalingRequired = mAttachInfo.mScalingRequired;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001252
1253 Rect dirty = mDirty;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001254 if (mSurfaceHolder != null) {
1255 // The app owns the surface, we won't draw.
1256 dirty.setEmpty();
1257 return;
1258 }
Romain Guy58ef7fb2010-09-13 12:52:37 -07001259
1260 if (fullRedrawNeeded) {
1261 mAttachInfo.mIgnoreDirtyState = true;
1262 dirty.union(0, 0, (int) (mWidth * appScale + 0.5f), (int) (mHeight * appScale + 0.5f));
1263 }
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001264
Romain Guy2d614592010-06-09 18:21:37 -07001265 if (mHwRenderer != null && mHwRenderer.isEnabled()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001266 if (!dirty.isEmpty()) {
Romain Guydbd77cd2010-07-09 10:36:05 -07001267 mHwRenderer.draw(mView, mAttachInfo, yoff);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001268 }
Romain Guy812ccbe2010-06-01 14:07:24 -07001269
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001270 if (scrolling) {
1271 mFullRedrawNeeded = true;
1272 scheduleTraversals();
1273 }
Romain Guy812ccbe2010-06-01 14:07:24 -07001274
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001275 return;
1276 }
1277
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001278 if (DEBUG_ORIENTATION || DEBUG_DRAW) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001279 Log.v(TAG, "Draw " + mView + "/"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001280 + mWindowAttributes.getTitle()
1281 + ": dirty={" + dirty.left + "," + dirty.top
1282 + "," + dirty.right + "," + dirty.bottom + "} surface="
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001283 + surface + " surface.isValid()=" + surface.isValid() + ", appScale:" +
1284 appScale + ", width=" + mWidth + ", height=" + mHeight);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001285 }
1286
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001287 if (!dirty.isEmpty() || mIsAnimating) {
1288 Canvas canvas;
1289 try {
1290 int left = dirty.left;
1291 int top = dirty.top;
1292 int right = dirty.right;
1293 int bottom = dirty.bottom;
1294 canvas = surface.lockCanvas(dirty);
Romain Guy5bcdff42009-05-14 21:27:18 -07001295
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001296 if (left != dirty.left || top != dirty.top || right != dirty.right ||
1297 bottom != dirty.bottom) {
1298 mAttachInfo.mIgnoreDirtyState = true;
1299 }
1300
1301 // TODO: Do this in native
1302 canvas.setDensity(mDensity);
1303 } catch (Surface.OutOfResourcesException e) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001304 Log.e(TAG, "OutOfResourcesException locking surface", e);
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001305 // TODO: we should ask the window manager to do something!
1306 // for now we just do nothing
1307 return;
1308 } catch (IllegalArgumentException e) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001309 Log.e(TAG, "IllegalArgumentException locking surface", e);
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001310 // TODO: we should ask the window manager to do something!
1311 // for now we just do nothing
1312 return;
Romain Guy5bcdff42009-05-14 21:27:18 -07001313 }
1314
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001315 try {
1316 if (!dirty.isEmpty() || mIsAnimating) {
1317 long startTime = 0L;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001318
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001319 if (DEBUG_ORIENTATION || DEBUG_DRAW) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001320 Log.v(TAG, "Surface " + surface + " drawing to bitmap w="
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001321 + canvas.getWidth() + ", h=" + canvas.getHeight());
1322 //canvas.drawARGB(255, 255, 0, 0);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001323 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001324
Romain Guy5429e1d2010-09-07 12:38:00 -07001325 if (ViewDebug.DEBUG_PROFILE_DRAWING) {
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001326 startTime = SystemClock.elapsedRealtime();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001327 }
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001328
1329 // If this bitmap's format includes an alpha channel, we
1330 // need to clear it before drawing so that the child will
1331 // properly re-composite its drawing on a transparent
1332 // background. This automatically respects the clip/dirty region
1333 // or
1334 // If we are applying an offset, we need to clear the area
1335 // where the offset doesn't appear to avoid having garbage
1336 // left in the blank areas.
1337 if (!canvas.isOpaque() || yoff != 0) {
1338 canvas.drawColor(0, PorterDuff.Mode.CLEAR);
1339 }
1340
1341 dirty.setEmpty();
1342 mIsAnimating = false;
1343 mAttachInfo.mDrawingTime = SystemClock.uptimeMillis();
1344 mView.mPrivateFlags |= View.DRAWN;
1345
1346 if (DEBUG_DRAW) {
1347 Context cxt = mView.getContext();
1348 Log.i(TAG, "Drawing: package:" + cxt.getPackageName() +
1349 ", metrics=" + cxt.getResources().getDisplayMetrics() +
1350 ", compatibilityInfo=" + cxt.getResources().getCompatibilityInfo());
1351 }
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001352 try {
1353 canvas.translate(0, -yoff);
1354 if (mTranslator != null) {
1355 mTranslator.translateCanvas(canvas);
1356 }
1357 canvas.setScreenDensity(scalingRequired
1358 ? DisplayMetrics.DENSITY_DEVICE : 0);
1359 mView.draw(canvas);
1360 } finally {
1361 mAttachInfo.mIgnoreDirtyState = false;
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001362 }
1363
1364 if (Config.DEBUG && ViewDebug.consistencyCheckEnabled) {
1365 mView.dispatchConsistencyCheck(ViewDebug.CONSISTENCY_DRAWING);
1366 }
1367
Romain Guy5429e1d2010-09-07 12:38:00 -07001368 if (SHOW_FPS || ViewDebug.DEBUG_SHOW_FPS) {
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001369 int now = (int)SystemClock.elapsedRealtime();
1370 if (sDrawTime != 0) {
1371 nativeShowFPS(canvas, now - sDrawTime);
1372 }
1373 sDrawTime = now;
1374 }
1375
Romain Guy5429e1d2010-09-07 12:38:00 -07001376 if (ViewDebug.DEBUG_PROFILE_DRAWING) {
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001377 EventLog.writeEvent(60000, SystemClock.elapsedRealtime() - startTime);
1378 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001379 }
1380
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001381 } finally {
1382 surface.unlockCanvasAndPost(canvas);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001383 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001384 }
1385
1386 if (LOCAL_LOGV) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001387 Log.v(TAG, "Surface " + surface + " unlockCanvasAndPost");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001388 }
Romain Guy8506ab42009-06-11 17:35:47 -07001389
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001390 if (scrolling) {
1391 mFullRedrawNeeded = true;
1392 scheduleTraversals();
1393 }
1394 }
1395
1396 boolean scrollToRectOrFocus(Rect rectangle, boolean immediate) {
1397 final View.AttachInfo attachInfo = mAttachInfo;
1398 final Rect ci = attachInfo.mContentInsets;
1399 final Rect vi = attachInfo.mVisibleInsets;
1400 int scrollY = 0;
1401 boolean handled = false;
Romain Guy8506ab42009-06-11 17:35:47 -07001402
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001403 if (vi.left > ci.left || vi.top > ci.top
1404 || vi.right > ci.right || vi.bottom > ci.bottom) {
1405 // We'll assume that we aren't going to change the scroll
1406 // offset, since we want to avoid that unless it is actually
1407 // going to make the focus visible... otherwise we scroll
1408 // all over the place.
1409 scrollY = mScrollY;
1410 // We can be called for two different situations: during a draw,
1411 // to update the scroll position if the focus has changed (in which
1412 // case 'rectangle' is null), or in response to a
1413 // requestChildRectangleOnScreen() call (in which case 'rectangle'
1414 // is non-null and we just want to scroll to whatever that
1415 // rectangle is).
1416 View focus = mRealFocusedView;
Romain Guye8b16522009-07-14 13:06:42 -07001417
1418 // When in touch mode, focus points to the previously focused view,
1419 // which may have been removed from the view hierarchy. The following
Joe Onoratob71193b2009-11-24 18:34:42 -05001420 // line checks whether the view is still in our hierarchy.
1421 if (focus == null || focus.mAttachInfo != mAttachInfo) {
Romain Guye8b16522009-07-14 13:06:42 -07001422 mRealFocusedView = null;
1423 return false;
1424 }
1425
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001426 if (focus != mLastScrolledFocus) {
1427 // If the focus has changed, then ignore any requests to scroll
1428 // to a rectangle; first we want to make sure the entire focus
1429 // view is visible.
1430 rectangle = null;
1431 }
1432 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Eval scroll: focus=" + focus
1433 + " rectangle=" + rectangle + " ci=" + ci
1434 + " vi=" + vi);
1435 if (focus == mLastScrolledFocus && !mScrollMayChange
1436 && rectangle == null) {
1437 // Optimization: if the focus hasn't changed since last
1438 // time, and no layout has happened, then just leave things
1439 // as they are.
1440 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Keeping scroll y="
1441 + mScrollY + " vi=" + vi.toShortString());
1442 } else if (focus != null) {
1443 // We need to determine if the currently focused view is
1444 // within the visible part of the window and, if not, apply
1445 // a pan so it can be seen.
1446 mLastScrolledFocus = focus;
1447 mScrollMayChange = false;
1448 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Need to scroll?");
1449 // Try to find the rectangle from the focus view.
1450 if (focus.getGlobalVisibleRect(mVisRect, null)) {
1451 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Root w="
1452 + mView.getWidth() + " h=" + mView.getHeight()
1453 + " ci=" + ci.toShortString()
1454 + " vi=" + vi.toShortString());
1455 if (rectangle == null) {
1456 focus.getFocusedRect(mTempRect);
1457 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Focus " + focus
1458 + ": focusRect=" + mTempRect.toShortString());
Dianne Hackborn1c6a8942010-03-23 16:34:20 -07001459 if (mView instanceof ViewGroup) {
1460 ((ViewGroup) mView).offsetDescendantRectToMyCoords(
1461 focus, mTempRect);
1462 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001463 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1464 "Focus in window: focusRect="
1465 + mTempRect.toShortString()
1466 + " visRect=" + mVisRect.toShortString());
1467 } else {
1468 mTempRect.set(rectangle);
1469 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1470 "Request scroll to rect: "
1471 + mTempRect.toShortString()
1472 + " visRect=" + mVisRect.toShortString());
1473 }
1474 if (mTempRect.intersect(mVisRect)) {
1475 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1476 "Focus window visible rect: "
1477 + mTempRect.toShortString());
1478 if (mTempRect.height() >
1479 (mView.getHeight()-vi.top-vi.bottom)) {
1480 // If the focus simply is not going to fit, then
1481 // best is probably just to leave things as-is.
1482 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1483 "Too tall; leaving scrollY=" + scrollY);
1484 } else if ((mTempRect.top-scrollY) < vi.top) {
1485 scrollY -= vi.top - (mTempRect.top-scrollY);
1486 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1487 "Top covered; scrollY=" + scrollY);
1488 } else if ((mTempRect.bottom-scrollY)
1489 > (mView.getHeight()-vi.bottom)) {
1490 scrollY += (mTempRect.bottom-scrollY)
1491 - (mView.getHeight()-vi.bottom);
1492 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1493 "Bottom covered; scrollY=" + scrollY);
1494 }
1495 handled = true;
1496 }
1497 }
1498 }
1499 }
Romain Guy8506ab42009-06-11 17:35:47 -07001500
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001501 if (scrollY != mScrollY) {
1502 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Pan scroll changed: old="
1503 + mScrollY + " , new=" + scrollY);
1504 if (!immediate) {
1505 if (mScroller == null) {
1506 mScroller = new Scroller(mView.getContext());
1507 }
1508 mScroller.startScroll(0, mScrollY, 0, scrollY-mScrollY);
1509 } else if (mScroller != null) {
1510 mScroller.abortAnimation();
1511 }
1512 mScrollY = scrollY;
1513 }
Romain Guy8506ab42009-06-11 17:35:47 -07001514
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001515 return handled;
1516 }
Romain Guy8506ab42009-06-11 17:35:47 -07001517
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001518 public void requestChildFocus(View child, View focused) {
1519 checkThread();
1520 if (mFocusedView != focused) {
1521 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(mFocusedView, focused);
1522 scheduleTraversals();
1523 }
1524 mFocusedView = mRealFocusedView = focused;
1525 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Request child focus: focus now "
1526 + mFocusedView);
1527 }
1528
1529 public void clearChildFocus(View child) {
1530 checkThread();
1531
1532 View oldFocus = mFocusedView;
1533
1534 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Clearing child focus");
1535 mFocusedView = mRealFocusedView = null;
1536 if (mView != null && !mView.hasFocus()) {
1537 // If a view gets the focus, the listener will be invoked from requestChildFocus()
1538 if (!mView.requestFocus(View.FOCUS_FORWARD)) {
1539 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
1540 }
1541 } else if (oldFocus != null) {
1542 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
1543 }
1544 }
1545
1546
1547 public void focusableViewAvailable(View v) {
1548 checkThread();
1549
1550 if (mView != null && !mView.hasFocus()) {
1551 v.requestFocus();
1552 } else {
1553 // the one case where will transfer focus away from the current one
1554 // is if the current view is a view group that prefers to give focus
1555 // to its children first AND the view is a descendant of it.
1556 mFocusedView = mView.findFocus();
1557 boolean descendantsHaveDibsOnFocus =
1558 (mFocusedView instanceof ViewGroup) &&
1559 (((ViewGroup) mFocusedView).getDescendantFocusability() ==
1560 ViewGroup.FOCUS_AFTER_DESCENDANTS);
1561 if (descendantsHaveDibsOnFocus && isViewDescendantOf(v, mFocusedView)) {
1562 // If a view gets the focus, the listener will be invoked from requestChildFocus()
1563 v.requestFocus();
1564 }
1565 }
1566 }
1567
1568 public void recomputeViewAttributes(View child) {
1569 checkThread();
1570 if (mView == child) {
1571 mAttachInfo.mRecomputeGlobalAttributes = true;
1572 if (!mWillDrawSoon) {
1573 scheduleTraversals();
1574 }
1575 }
1576 }
1577
1578 void dispatchDetachedFromWindow() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001579 if (mView != null) {
1580 mView.dispatchDetachedFromWindow();
1581 }
1582
1583 mView = null;
1584 mAttachInfo.mRootView = null;
Mathias Agopian5583dc62009-07-09 16:28:11 -07001585 mAttachInfo.mSurface = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001586
Romain Guy29d89972010-09-22 16:10:57 -07001587 destroyHardwareRenderer();
Romain Guy4caa4ed2010-08-25 14:46:24 -07001588
Dianne Hackborn0586a1b2009-09-06 21:08:27 -07001589 mSurface.release();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001590
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001591 if (mInputChannel != null) {
1592 if (mInputQueueCallback != null) {
1593 mInputQueueCallback.onInputQueueDestroyed(mInputQueue);
1594 mInputQueueCallback = null;
1595 } else {
1596 InputQueue.unregisterInputChannel(mInputChannel);
Jeff Brown46b9ac02010-04-22 18:58:52 -07001597 }
1598 }
1599
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001600 try {
1601 sWindowSession.remove(mWindow);
1602 } catch (RemoteException e) {
1603 }
Jeff Brown349703e2010-06-22 01:27:15 -07001604
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001605 // Dispose the input channel after removing the window so the Window Manager
1606 // doesn't interpret the input channel being closed as an abnormal termination.
1607 if (mInputChannel != null) {
1608 mInputChannel.dispose();
1609 mInputChannel = null;
Jeff Brown349703e2010-06-22 01:27:15 -07001610 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001611 }
Romain Guy8506ab42009-06-11 17:35:47 -07001612
Dianne Hackborn694f79b2010-03-17 19:44:59 -07001613 void updateConfiguration(Configuration config, boolean force) {
1614 if (DEBUG_CONFIGURATION) Log.v(TAG,
1615 "Applying new config to window "
1616 + mWindowAttributes.getTitle()
1617 + ": " + config);
1618 synchronized (sConfigCallbacks) {
1619 for (int i=sConfigCallbacks.size()-1; i>=0; i--) {
1620 sConfigCallbacks.get(i).onConfigurationChanged(config);
1621 }
1622 }
1623 if (mView != null) {
1624 // At this point the resources have been updated to
1625 // have the most recent config, whatever that is. Use
1626 // the on in them which may be newer.
1627 if (mView != null) {
1628 config = mView.getResources().getConfiguration();
1629 }
1630 if (force || mLastConfiguration.diff(config) != 0) {
1631 mLastConfiguration.setTo(config);
1632 mView.dispatchConfigurationChanged(config);
1633 }
1634 }
1635 }
1636
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001637 /**
1638 * Return true if child is an ancestor of parent, (or equal to the parent).
1639 */
1640 private static boolean isViewDescendantOf(View child, View parent) {
1641 if (child == parent) {
1642 return true;
1643 }
1644
1645 final ViewParent theParent = child.getParent();
1646 return (theParent instanceof ViewGroup) && isViewDescendantOf((View) theParent, parent);
1647 }
1648
Romain Guycdb86672010-03-18 18:54:50 -07001649 private static void forceLayout(View view) {
1650 view.forceLayout();
1651 if (view instanceof ViewGroup) {
1652 ViewGroup group = (ViewGroup) view;
1653 final int count = group.getChildCount();
1654 for (int i = 0; i < count; i++) {
1655 forceLayout(group.getChildAt(i));
1656 }
1657 }
1658 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001659
1660 public final static int DO_TRAVERSAL = 1000;
1661 public final static int DIE = 1001;
1662 public final static int RESIZED = 1002;
1663 public final static int RESIZED_REPORT = 1003;
1664 public final static int WINDOW_FOCUS_CHANGED = 1004;
1665 public final static int DISPATCH_KEY = 1005;
1666 public final static int DISPATCH_POINTER = 1006;
1667 public final static int DISPATCH_TRACKBALL = 1007;
1668 public final static int DISPATCH_APP_VISIBILITY = 1008;
1669 public final static int DISPATCH_GET_NEW_SURFACE = 1009;
1670 public final static int FINISHED_EVENT = 1010;
1671 public final static int DISPATCH_KEY_FROM_IME = 1011;
1672 public final static int FINISH_INPUT_CONNECTION = 1012;
1673 public final static int CHECK_FOCUS = 1013;
Dianne Hackbornffa42482009-09-23 22:20:11 -07001674 public final static int CLOSE_SYSTEM_DIALOGS = 1014;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001675
1676 @Override
1677 public void handleMessage(Message msg) {
1678 switch (msg.what) {
1679 case View.AttachInfo.INVALIDATE_MSG:
1680 ((View) msg.obj).invalidate();
1681 break;
1682 case View.AttachInfo.INVALIDATE_RECT_MSG:
1683 final View.AttachInfo.InvalidateInfo info = (View.AttachInfo.InvalidateInfo) msg.obj;
1684 info.target.invalidate(info.left, info.top, info.right, info.bottom);
1685 info.release();
1686 break;
1687 case DO_TRAVERSAL:
1688 if (mProfile) {
1689 Debug.startMethodTracing("ViewRoot");
1690 }
1691
1692 performTraversals();
1693
1694 if (mProfile) {
1695 Debug.stopMethodTracing();
1696 mProfile = false;
1697 }
1698 break;
1699 case FINISHED_EVENT:
1700 handleFinishedEvent(msg.arg1, msg.arg2 != 0);
1701 break;
1702 case DISPATCH_KEY:
1703 if (LOCAL_LOGV) Log.v(
Jeff Brownc5ed5912010-07-14 18:48:53 -07001704 TAG, "Dispatching key "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001705 + msg.obj + " to " + mView);
Jeff Brown92ff1dd2010-08-11 16:16:06 -07001706 deliverKeyEvent((KeyEvent)msg.obj, msg.arg1 != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001707 break;
The Android Open Source Project10592532009-03-18 17:39:46 -07001708 case DISPATCH_POINTER: {
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001709 MotionEvent event = (MotionEvent) msg.obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001710 try {
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001711 deliverPointerEvent(event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001712 } finally {
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001713 event.recycle();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001714 if (LOCAL_LOGV || WATCH_POINTER) Log.i(TAG, "Done dispatching!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001715 }
The Android Open Source Project10592532009-03-18 17:39:46 -07001716 } break;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001717 case DISPATCH_TRACKBALL: {
1718 MotionEvent event = (MotionEvent) msg.obj;
1719 try {
1720 deliverTrackballEvent(event);
1721 } finally {
1722 event.recycle();
1723 }
1724 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001725 case DISPATCH_APP_VISIBILITY:
1726 handleAppVisibility(msg.arg1 != 0);
1727 break;
1728 case DISPATCH_GET_NEW_SURFACE:
1729 handleGetNewSurface();
1730 break;
1731 case RESIZED:
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001732 ResizedInfo ri = (ResizedInfo)msg.obj;
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001733
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001734 if (mWinFrame.width() == msg.arg1 && mWinFrame.height() == msg.arg2
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001735 && mPendingContentInsets.equals(ri.coveredInsets)
Dianne Hackbornd49258f2010-03-26 00:44:29 -07001736 && mPendingVisibleInsets.equals(ri.visibleInsets)
1737 && ((ResizedInfo)msg.obj).newConfig == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001738 break;
1739 }
1740 // fall through...
1741 case RESIZED_REPORT:
1742 if (mAdded) {
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001743 Configuration config = ((ResizedInfo)msg.obj).newConfig;
1744 if (config != null) {
Dianne Hackborn694f79b2010-03-17 19:44:59 -07001745 updateConfiguration(config, false);
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001746 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001747 mWinFrame.left = 0;
1748 mWinFrame.right = msg.arg1;
1749 mWinFrame.top = 0;
1750 mWinFrame.bottom = msg.arg2;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001751 mPendingContentInsets.set(((ResizedInfo)msg.obj).coveredInsets);
1752 mPendingVisibleInsets.set(((ResizedInfo)msg.obj).visibleInsets);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001753 if (msg.what == RESIZED_REPORT) {
1754 mReportNextDraw = true;
1755 }
Romain Guycdb86672010-03-18 18:54:50 -07001756
1757 if (mView != null) {
1758 forceLayout(mView);
1759 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001760 requestLayout();
1761 }
1762 break;
1763 case WINDOW_FOCUS_CHANGED: {
1764 if (mAdded) {
1765 boolean hasWindowFocus = msg.arg1 != 0;
1766 mAttachInfo.mHasWindowFocus = hasWindowFocus;
1767 if (hasWindowFocus) {
1768 boolean inTouchMode = msg.arg2 != 0;
Romain Guy2d4cff62010-04-09 15:39:00 -07001769 ensureTouchModeLocally(inTouchMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001770
Romain Guy812ccbe2010-06-01 14:07:24 -07001771 if (mHwRenderer != null) {
Romain Guy2d614592010-06-09 18:21:37 -07001772 mHwRenderer.initializeIfNeeded(mWidth, mHeight, mAttachInfo, mHolder);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001773 }
1774 }
Romain Guy8506ab42009-06-11 17:35:47 -07001775
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001776 mLastWasImTarget = WindowManager.LayoutParams
1777 .mayUseInputMethod(mWindowAttributes.flags);
Romain Guy8506ab42009-06-11 17:35:47 -07001778
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001779 InputMethodManager imm = InputMethodManager.peekInstance();
1780 if (mView != null) {
1781 if (hasWindowFocus && imm != null && mLastWasImTarget) {
1782 imm.startGettingWindowFocus(mView);
1783 }
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07001784 mAttachInfo.mKeyDispatchState.reset();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001785 mView.dispatchWindowFocusChanged(hasWindowFocus);
1786 }
svetoslavganov75986cf2009-05-14 22:28:01 -07001787
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001788 // Note: must be done after the focus change callbacks,
1789 // so all of the view state is set up correctly.
1790 if (hasWindowFocus) {
1791 if (imm != null && mLastWasImTarget) {
1792 imm.onWindowFocus(mView, mView.findFocus(),
1793 mWindowAttributes.softInputMode,
1794 !mHasHadWindowFocus, mWindowAttributes.flags);
1795 }
1796 // Clear the forward bit. We can just do this directly, since
1797 // the window manager doesn't care about it.
1798 mWindowAttributes.softInputMode &=
1799 ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
1800 ((WindowManager.LayoutParams)mView.getLayoutParams())
1801 .softInputMode &=
1802 ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
1803 mHasHadWindowFocus = true;
1804 }
svetoslavganov75986cf2009-05-14 22:28:01 -07001805
1806 if (hasWindowFocus && mView != null) {
1807 sendAccessibilityEvents();
1808 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001809 }
1810 } break;
1811 case DIE:
Dianne Hackborn94d69142009-09-28 22:14:42 -07001812 doDie();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001813 break;
The Android Open Source Project10592532009-03-18 17:39:46 -07001814 case DISPATCH_KEY_FROM_IME: {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001815 if (LOCAL_LOGV) Log.v(
Jeff Brownc5ed5912010-07-14 18:48:53 -07001816 TAG, "Dispatching key "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001817 + msg.obj + " from IME to " + mView);
The Android Open Source Project10592532009-03-18 17:39:46 -07001818 KeyEvent event = (KeyEvent)msg.obj;
1819 if ((event.getFlags()&KeyEvent.FLAG_FROM_SYSTEM) != 0) {
1820 // The IME is trying to say this event is from the
1821 // system! Bad bad bad!
Romain Guy812ccbe2010-06-01 14:07:24 -07001822 event = KeyEvent.changeFlags(event, event.getFlags() & ~KeyEvent.FLAG_FROM_SYSTEM);
The Android Open Source Project10592532009-03-18 17:39:46 -07001823 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001824 deliverKeyEventToViewHierarchy((KeyEvent)msg.obj, false);
The Android Open Source Project10592532009-03-18 17:39:46 -07001825 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001826 case FINISH_INPUT_CONNECTION: {
1827 InputMethodManager imm = InputMethodManager.peekInstance();
1828 if (imm != null) {
1829 imm.reportFinishInputConnection((InputConnection)msg.obj);
1830 }
1831 } break;
1832 case CHECK_FOCUS: {
1833 InputMethodManager imm = InputMethodManager.peekInstance();
1834 if (imm != null) {
1835 imm.checkFocus();
1836 }
1837 } break;
Dianne Hackbornffa42482009-09-23 22:20:11 -07001838 case CLOSE_SYSTEM_DIALOGS: {
1839 if (mView != null) {
1840 mView.onCloseSystemDialogs((String)msg.obj);
1841 }
1842 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001843 }
1844 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07001845
1846 private void finishKeyEvent(KeyEvent event) {
Jeff Brown92ff1dd2010-08-11 16:16:06 -07001847 if (LOCAL_LOGV) Log.v(TAG, "Telling window manager key is finished");
1848
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001849 if (mFinishedCallback != null) {
1850 mFinishedCallback.run();
1851 mFinishedCallback = null;
Jeff Brown92ff1dd2010-08-11 16:16:06 -07001852 } else {
1853 Slog.w(TAG, "Attempted to tell the input queue that the current key event "
1854 + "is finished but there is no key event actually in progress.");
Jeff Brown46b9ac02010-04-22 18:58:52 -07001855 }
1856 }
1857
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001858 /**
1859 * Something in the current window tells us we need to change the touch mode. For
1860 * example, we are not in touch mode, and the user touches the screen.
1861 *
1862 * If the touch mode has changed, tell the window manager, and handle it locally.
1863 *
1864 * @param inTouchMode Whether we want to be in touch mode.
1865 * @return True if the touch mode changed and focus changed was changed as a result
1866 */
1867 boolean ensureTouchMode(boolean inTouchMode) {
1868 if (DBG) Log.d("touchmode", "ensureTouchMode(" + inTouchMode + "), current "
1869 + "touch mode is " + mAttachInfo.mInTouchMode);
1870 if (mAttachInfo.mInTouchMode == inTouchMode) return false;
1871
1872 // tell the window manager
1873 try {
1874 sWindowSession.setInTouchMode(inTouchMode);
1875 } catch (RemoteException e) {
1876 throw new RuntimeException(e);
1877 }
1878
1879 // handle the change
Romain Guy2d4cff62010-04-09 15:39:00 -07001880 return ensureTouchModeLocally(inTouchMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001881 }
1882
1883 /**
1884 * Ensure that the touch mode for this window is set, and if it is changing,
1885 * take the appropriate action.
1886 * @param inTouchMode Whether we want to be in touch mode.
1887 * @return True if the touch mode changed and focus changed was changed as a result
1888 */
Romain Guy2d4cff62010-04-09 15:39:00 -07001889 private boolean ensureTouchModeLocally(boolean inTouchMode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001890 if (DBG) Log.d("touchmode", "ensureTouchModeLocally(" + inTouchMode + "), current "
1891 + "touch mode is " + mAttachInfo.mInTouchMode);
1892
1893 if (mAttachInfo.mInTouchMode == inTouchMode) return false;
1894
1895 mAttachInfo.mInTouchMode = inTouchMode;
1896 mAttachInfo.mTreeObserver.dispatchOnTouchModeChanged(inTouchMode);
1897
Romain Guy2d4cff62010-04-09 15:39:00 -07001898 return (inTouchMode) ? enterTouchMode() : leaveTouchMode();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001899 }
1900
1901 private boolean enterTouchMode() {
1902 if (mView != null) {
1903 if (mView.hasFocus()) {
1904 // note: not relying on mFocusedView here because this could
1905 // be when the window is first being added, and mFocused isn't
1906 // set yet.
1907 final View focused = mView.findFocus();
1908 if (focused != null && !focused.isFocusableInTouchMode()) {
1909
1910 final ViewGroup ancestorToTakeFocus =
1911 findAncestorToTakeFocusInTouchMode(focused);
1912 if (ancestorToTakeFocus != null) {
1913 // there is an ancestor that wants focus after its descendants that
1914 // is focusable in touch mode.. give it focus
1915 return ancestorToTakeFocus.requestFocus();
1916 } else {
1917 // nothing appropriate to have focus in touch mode, clear it out
1918 mView.unFocus();
1919 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(focused, null);
1920 mFocusedView = null;
1921 return true;
1922 }
1923 }
1924 }
1925 }
1926 return false;
1927 }
1928
1929
1930 /**
1931 * Find an ancestor of focused that wants focus after its descendants and is
1932 * focusable in touch mode.
1933 * @param focused The currently focused view.
1934 * @return An appropriate view, or null if no such view exists.
1935 */
1936 private ViewGroup findAncestorToTakeFocusInTouchMode(View focused) {
1937 ViewParent parent = focused.getParent();
1938 while (parent instanceof ViewGroup) {
1939 final ViewGroup vgParent = (ViewGroup) parent;
1940 if (vgParent.getDescendantFocusability() == ViewGroup.FOCUS_AFTER_DESCENDANTS
1941 && vgParent.isFocusableInTouchMode()) {
1942 return vgParent;
1943 }
1944 if (vgParent.isRootNamespace()) {
1945 return null;
1946 } else {
1947 parent = vgParent.getParent();
1948 }
1949 }
1950 return null;
1951 }
1952
1953 private boolean leaveTouchMode() {
1954 if (mView != null) {
1955 if (mView.hasFocus()) {
1956 // i learned the hard way to not trust mFocusedView :)
1957 mFocusedView = mView.findFocus();
1958 if (!(mFocusedView instanceof ViewGroup)) {
1959 // some view has focus, let it keep it
1960 return false;
1961 } else if (((ViewGroup)mFocusedView).getDescendantFocusability() !=
1962 ViewGroup.FOCUS_AFTER_DESCENDANTS) {
1963 // some view group has focus, and doesn't prefer its children
1964 // over itself for focus, so let them keep it.
1965 return false;
1966 }
1967 }
1968
1969 // find the best view to give focus to in this brave new non-touch-mode
1970 // world
1971 final View focused = focusSearch(null, View.FOCUS_DOWN);
1972 if (focused != null) {
1973 return focused.requestFocus(View.FOCUS_DOWN);
1974 }
1975 }
1976 return false;
1977 }
1978
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001979 private void deliverPointerEvent(MotionEvent event) {
1980 if (mTranslator != null) {
1981 mTranslator.translateEventInScreenToAppWindow(event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001982 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001983
1984 boolean handled;
1985 if (mView != null && mAdded) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001986
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001987 // enter touch mode on the down
1988 boolean isDown = event.getAction() == MotionEvent.ACTION_DOWN;
1989 if (isDown) {
1990 ensureTouchMode(true);
1991 }
1992 if(Config.LOGV) {
1993 captureMotionLog("captureDispatchPointer", event);
1994 }
1995 if (mCurScrollY != 0) {
1996 event.offsetLocation(0, mCurScrollY);
1997 }
1998 if (MEASURE_LATENCY) {
1999 lt.sample("A Dispatching TouchEvents", System.nanoTime() - event.getEventTimeNano());
2000 }
2001 handled = mView.dispatchTouchEvent(event);
2002 if (MEASURE_LATENCY) {
2003 lt.sample("B Dispatched TouchEvents ", System.nanoTime() - event.getEventTimeNano());
2004 }
2005 if (!handled && isDown) {
2006 int edgeSlop = mViewConfiguration.getScaledEdgeSlop();
2007
2008 final int edgeFlags = event.getEdgeFlags();
2009 int direction = View.FOCUS_UP;
2010 int x = (int)event.getX();
2011 int y = (int)event.getY();
2012 final int[] deltas = new int[2];
2013
2014 if ((edgeFlags & MotionEvent.EDGE_TOP) != 0) {
2015 direction = View.FOCUS_DOWN;
2016 if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
2017 deltas[0] = edgeSlop;
2018 x += edgeSlop;
2019 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
2020 deltas[0] = -edgeSlop;
2021 x -= edgeSlop;
2022 }
2023 } else if ((edgeFlags & MotionEvent.EDGE_BOTTOM) != 0) {
2024 direction = View.FOCUS_UP;
2025 if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
2026 deltas[0] = edgeSlop;
2027 x += edgeSlop;
2028 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
2029 deltas[0] = -edgeSlop;
2030 x -= edgeSlop;
2031 }
2032 } else if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
2033 direction = View.FOCUS_RIGHT;
2034 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
2035 direction = View.FOCUS_LEFT;
2036 }
2037
2038 if (edgeFlags != 0 && mView instanceof ViewGroup) {
2039 View nearest = FocusFinder.getInstance().findNearestTouchable(
2040 ((ViewGroup) mView), x, y, direction, deltas);
2041 if (nearest != null) {
2042 event.offsetLocation(deltas[0], deltas[1]);
2043 event.setEdgeFlags(0);
2044 mView.dispatchTouchEvent(event);
2045 }
2046 }
2047 }
2048 }
2049 }
2050
2051 private void deliverTrackballEvent(MotionEvent event) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002052 if (DEBUG_TRACKBALL) Log.v(TAG, "Motion event:" + event);
2053
2054 boolean handled = false;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002055 if (mView != null && mAdded) {
2056 handled = mView.dispatchTrackballEvent(event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002057 if (handled) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002058 // If we reach this, we delivered a trackball event to mView and
2059 // mView consumed it. Because we will not translate the trackball
2060 // event into a key event, touch mode will not exit, so we exit
2061 // touch mode here.
2062 ensureTouchMode(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002063 return;
2064 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002065
2066 // Otherwise we could do something here, like changing the focus
2067 // or something?
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002068 }
2069
2070 final TrackballAxis x = mTrackballAxisX;
2071 final TrackballAxis y = mTrackballAxisY;
2072
2073 long curTime = SystemClock.uptimeMillis();
2074 if ((mLastTrackballTime+MAX_TRACKBALL_DELAY) < curTime) {
2075 // It has been too long since the last movement,
2076 // so restart at the beginning.
2077 x.reset(0);
2078 y.reset(0);
2079 mLastTrackballTime = curTime;
2080 }
2081
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002082 final int action = event.getAction();
2083 final int metastate = event.getMetaState();
2084 switch (action) {
2085 case MotionEvent.ACTION_DOWN:
2086 x.reset(2);
2087 y.reset(2);
2088 deliverKeyEvent(new KeyEvent(curTime, curTime,
2089 KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_CENTER,
2090 0, metastate), false);
2091 break;
2092 case MotionEvent.ACTION_UP:
2093 x.reset(2);
2094 y.reset(2);
2095 deliverKeyEvent(new KeyEvent(curTime, curTime,
2096 KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_CENTER,
2097 0, metastate), false);
2098 break;
2099 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002100
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002101 if (DEBUG_TRACKBALL) Log.v(TAG, "TB X=" + x.position + " step="
2102 + x.step + " dir=" + x.dir + " acc=" + x.acceleration
2103 + " move=" + event.getX()
2104 + " / Y=" + y.position + " step="
2105 + y.step + " dir=" + y.dir + " acc=" + y.acceleration
2106 + " move=" + event.getY());
2107 final float xOff = x.collect(event.getX(), event.getEventTime(), "X");
2108 final float yOff = y.collect(event.getY(), event.getEventTime(), "Y");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002109
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002110 // Generate DPAD events based on the trackball movement.
2111 // We pick the axis that has moved the most as the direction of
2112 // the DPAD. When we generate DPAD events for one axis, then the
2113 // other axis is reset -- we don't want to perform DPAD jumps due
2114 // to slight movements in the trackball when making major movements
2115 // along the other axis.
2116 int keycode = 0;
2117 int movement = 0;
2118 float accel = 1;
2119 if (xOff > yOff) {
2120 movement = x.generate((2/event.getXPrecision()));
2121 if (movement != 0) {
2122 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_RIGHT
2123 : KeyEvent.KEYCODE_DPAD_LEFT;
2124 accel = x.acceleration;
2125 y.reset(2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002126 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002127 } else if (yOff > 0) {
2128 movement = y.generate((2/event.getYPrecision()));
2129 if (movement != 0) {
2130 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_DOWN
2131 : KeyEvent.KEYCODE_DPAD_UP;
2132 accel = y.acceleration;
2133 x.reset(2);
2134 }
2135 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002136
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002137 if (keycode != 0) {
2138 if (movement < 0) movement = -movement;
2139 int accelMovement = (int)(movement * accel);
2140 if (DEBUG_TRACKBALL) Log.v(TAG, "Move: movement=" + movement
2141 + " accelMovement=" + accelMovement
2142 + " accel=" + accel);
2143 if (accelMovement > movement) {
2144 if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: "
2145 + keycode);
2146 movement--;
2147 deliverKeyEvent(new KeyEvent(curTime, curTime,
2148 KeyEvent.ACTION_MULTIPLE, keycode,
2149 accelMovement-movement, metastate), false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002150 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002151 while (movement > 0) {
2152 if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: "
2153 + keycode);
2154 movement--;
2155 curTime = SystemClock.uptimeMillis();
2156 deliverKeyEvent(new KeyEvent(curTime, curTime,
2157 KeyEvent.ACTION_DOWN, keycode, 0, event.getMetaState()), false);
2158 deliverKeyEvent(new KeyEvent(curTime, curTime,
2159 KeyEvent.ACTION_UP, keycode, 0, metastate), false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002160 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002161 mLastTrackballTime = curTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002162 }
2163 }
2164
2165 /**
2166 * @param keyCode The key code
2167 * @return True if the key is directional.
2168 */
2169 static boolean isDirectional(int keyCode) {
2170 switch (keyCode) {
2171 case KeyEvent.KEYCODE_DPAD_LEFT:
2172 case KeyEvent.KEYCODE_DPAD_RIGHT:
2173 case KeyEvent.KEYCODE_DPAD_UP:
2174 case KeyEvent.KEYCODE_DPAD_DOWN:
2175 return true;
2176 }
2177 return false;
2178 }
2179
2180 /**
2181 * Returns true if this key is a keyboard key.
2182 * @param keyEvent The key event.
2183 * @return whether this key is a keyboard key.
2184 */
2185 private static boolean isKeyboardKey(KeyEvent keyEvent) {
2186 final int convertedKey = keyEvent.getUnicodeChar();
2187 return convertedKey > 0;
2188 }
2189
2190
2191
2192 /**
2193 * See if the key event means we should leave touch mode (and leave touch
2194 * mode if so).
2195 * @param event The key event.
2196 * @return Whether this key event should be consumed (meaning the act of
2197 * leaving touch mode alone is considered the event).
2198 */
2199 private boolean checkForLeavingTouchModeAndConsume(KeyEvent event) {
Adam Powell51a6bee2010-03-15 14:07:28 -07002200 final int action = event.getAction();
2201 if (action != KeyEvent.ACTION_DOWN && action != KeyEvent.ACTION_MULTIPLE) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002202 return false;
2203 }
2204 if ((event.getFlags()&KeyEvent.FLAG_KEEP_TOUCH_MODE) != 0) {
2205 return false;
2206 }
2207
2208 // only relevant if we are in touch mode
2209 if (!mAttachInfo.mInTouchMode) {
2210 return false;
2211 }
2212
2213 // if something like an edit text has focus and the user is typing,
2214 // leave touch mode
2215 //
2216 // note: the condition of not being a keyboard key is kind of a hacky
2217 // approximation of whether we think the focused view will want the
2218 // key; if we knew for sure whether the focused view would consume
2219 // the event, that would be better.
2220 if (isKeyboardKey(event) && mView != null && mView.hasFocus()) {
2221 mFocusedView = mView.findFocus();
2222 if ((mFocusedView instanceof ViewGroup)
2223 && ((ViewGroup) mFocusedView).getDescendantFocusability() ==
2224 ViewGroup.FOCUS_AFTER_DESCENDANTS) {
2225 // something has focus, but is holding it weakly as a container
2226 return false;
2227 }
2228 if (ensureTouchMode(false)) {
2229 throw new IllegalStateException("should not have changed focus "
2230 + "when leaving touch mode while a view has focus.");
2231 }
2232 return false;
2233 }
2234
2235 if (isDirectional(event.getKeyCode())) {
2236 // no view has focus, so we leave touch mode (and find something
2237 // to give focus to). the event is consumed if we were able to
2238 // find something to give focus to.
2239 return ensureTouchMode(false);
2240 }
2241 return false;
2242 }
2243
2244 /**
Romain Guy8506ab42009-06-11 17:35:47 -07002245 * log motion events
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002246 */
2247 private static void captureMotionLog(String subTag, MotionEvent ev) {
Romain Guy8506ab42009-06-11 17:35:47 -07002248 //check dynamic switch
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002249 if (ev == null ||
2250 SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_EVENT, 0) == 0) {
2251 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002252 }
Romain Guy8506ab42009-06-11 17:35:47 -07002253
2254 StringBuilder sb = new StringBuilder(subTag + ": ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002255 sb.append(ev.getDownTime()).append(',');
2256 sb.append(ev.getEventTime()).append(',');
2257 sb.append(ev.getAction()).append(',');
Romain Guy8506ab42009-06-11 17:35:47 -07002258 sb.append(ev.getX()).append(',');
2259 sb.append(ev.getY()).append(',');
2260 sb.append(ev.getPressure()).append(',');
2261 sb.append(ev.getSize()).append(',');
2262 sb.append(ev.getMetaState()).append(',');
2263 sb.append(ev.getXPrecision()).append(',');
2264 sb.append(ev.getYPrecision()).append(',');
2265 sb.append(ev.getDeviceId()).append(',');
2266 sb.append(ev.getEdgeFlags());
2267 Log.d(TAG, sb.toString());
2268 }
2269 /**
2270 * log motion events
2271 */
2272 private static void captureKeyLog(String subTag, KeyEvent ev) {
2273 //check dynamic switch
2274 if (ev == null ||
2275 SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_EVENT, 0) == 0) {
2276 return;
2277 }
2278 StringBuilder sb = new StringBuilder(subTag + ": ");
2279 sb.append(ev.getDownTime()).append(',');
2280 sb.append(ev.getEventTime()).append(',');
2281 sb.append(ev.getAction()).append(',');
2282 sb.append(ev.getKeyCode()).append(',');
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002283 sb.append(ev.getRepeatCount()).append(',');
2284 sb.append(ev.getMetaState()).append(',');
2285 sb.append(ev.getDeviceId()).append(',');
2286 sb.append(ev.getScanCode());
Romain Guy8506ab42009-06-11 17:35:47 -07002287 Log.d(TAG, sb.toString());
2288 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002289
2290 int enqueuePendingEvent(Object event, boolean sendDone) {
2291 int seq = mPendingEventSeq+1;
2292 if (seq < 0) seq = 0;
2293 mPendingEventSeq = seq;
2294 mPendingEvents.put(seq, event);
2295 return sendDone ? seq : -seq;
2296 }
2297
2298 Object retrievePendingEvent(int seq) {
2299 if (seq < 0) seq = -seq;
2300 Object event = mPendingEvents.get(seq);
2301 if (event != null) {
2302 mPendingEvents.remove(seq);
2303 }
2304 return event;
2305 }
Romain Guy8506ab42009-06-11 17:35:47 -07002306
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002307 private void deliverKeyEvent(KeyEvent event, boolean sendDone) {
2308 // If mView is null, we just consume the key event because it doesn't
2309 // make sense to do anything else with it.
Romain Guy812ccbe2010-06-01 14:07:24 -07002310 boolean handled = mView == null || mView.dispatchKeyEventPreIme(event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002311 if (handled) {
2312 if (sendDone) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002313 finishKeyEvent(event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002314 }
2315 return;
2316 }
2317 // If it is possible for this window to interact with the input
2318 // method window, then we want to first dispatch our key events
2319 // to the input method.
2320 if (mLastWasImTarget) {
2321 InputMethodManager imm = InputMethodManager.peekInstance();
2322 if (imm != null && mView != null) {
2323 int seq = enqueuePendingEvent(event, sendDone);
2324 if (DEBUG_IMF) Log.v(TAG, "Sending key event to IME: seq="
2325 + seq + " event=" + event);
2326 imm.dispatchKeyEvent(mView.getContext(), seq, event,
2327 mInputMethodCallback);
2328 return;
2329 }
2330 }
2331 deliverKeyEventToViewHierarchy(event, sendDone);
2332 }
2333
2334 void handleFinishedEvent(int seq, boolean handled) {
2335 final KeyEvent event = (KeyEvent)retrievePendingEvent(seq);
2336 if (DEBUG_IMF) Log.v(TAG, "IME finished event: seq=" + seq
2337 + " handled=" + handled + " event=" + event);
2338 if (event != null) {
2339 final boolean sendDone = seq >= 0;
2340 if (!handled) {
2341 deliverKeyEventToViewHierarchy(event, sendDone);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002342 } else if (sendDone) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002343 finishKeyEvent(event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002344 } else {
Jeff Brownc5ed5912010-07-14 18:48:53 -07002345 Log.w(TAG, "handleFinishedEvent(seq=" + seq
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002346 + " handled=" + handled + " ev=" + event
2347 + ") neither delivering nor finishing key");
2348 }
2349 }
2350 }
Romain Guy8506ab42009-06-11 17:35:47 -07002351
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002352 private void deliverKeyEventToViewHierarchy(KeyEvent event, boolean sendDone) {
2353 try {
2354 if (mView != null && mAdded) {
2355 final int action = event.getAction();
2356 boolean isDown = (action == KeyEvent.ACTION_DOWN);
2357
2358 if (checkForLeavingTouchModeAndConsume(event)) {
2359 return;
Romain Guy8506ab42009-06-11 17:35:47 -07002360 }
2361
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002362 if (Config.LOGV) {
2363 captureKeyLog("captureDispatchKeyEvent", event);
2364 }
2365 boolean keyHandled = mView.dispatchKeyEvent(event);
2366
2367 if (!keyHandled && isDown) {
2368 int direction = 0;
2369 switch (event.getKeyCode()) {
2370 case KeyEvent.KEYCODE_DPAD_LEFT:
2371 direction = View.FOCUS_LEFT;
2372 break;
2373 case KeyEvent.KEYCODE_DPAD_RIGHT:
2374 direction = View.FOCUS_RIGHT;
2375 break;
2376 case KeyEvent.KEYCODE_DPAD_UP:
2377 direction = View.FOCUS_UP;
2378 break;
2379 case KeyEvent.KEYCODE_DPAD_DOWN:
2380 direction = View.FOCUS_DOWN;
2381 break;
2382 }
2383
2384 if (direction != 0) {
2385
2386 View focused = mView != null ? mView.findFocus() : null;
2387 if (focused != null) {
2388 View v = focused.focusSearch(direction);
2389 boolean focusPassed = false;
2390 if (v != null && v != focused) {
2391 // do the math the get the interesting rect
2392 // of previous focused into the coord system of
2393 // newly focused view
2394 focused.getFocusedRect(mTempRect);
Dianne Hackborn1c6a8942010-03-23 16:34:20 -07002395 if (mView instanceof ViewGroup) {
2396 ((ViewGroup) mView).offsetDescendantRectToMyCoords(
2397 focused, mTempRect);
2398 ((ViewGroup) mView).offsetRectIntoDescendantCoords(
2399 v, mTempRect);
2400 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002401 focusPassed = v.requestFocus(direction, mTempRect);
2402 }
2403
2404 if (!focusPassed) {
2405 mView.dispatchUnhandledMove(focused, direction);
2406 } else {
2407 playSoundEffect(SoundEffectConstants.getContantForFocusDirection(direction));
2408 }
2409 }
2410 }
2411 }
2412 }
2413
2414 } finally {
2415 if (sendDone) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002416 finishKeyEvent(event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002417 }
2418 // Let the exception fall through -- the looper will catch
2419 // it and take care of the bad app for us.
2420 }
2421 }
2422
2423 private AudioManager getAudioManager() {
2424 if (mView == null) {
2425 throw new IllegalStateException("getAudioManager called when there is no mView");
2426 }
2427 if (mAudioManager == null) {
2428 mAudioManager = (AudioManager) mView.getContext().getSystemService(Context.AUDIO_SERVICE);
2429 }
2430 return mAudioManager;
2431 }
2432
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002433 private int relayoutWindow(WindowManager.LayoutParams params, int viewVisibility,
2434 boolean insetsPending) throws RemoteException {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002435
2436 float appScale = mAttachInfo.mApplicationScale;
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002437 boolean restore = false;
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002438 if (params != null && mTranslator != null) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07002439 restore = true;
2440 params.backup();
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002441 mTranslator.translateWindowLayout(params);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002442 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002443 if (params != null) {
2444 if (DBG) Log.d(TAG, "WindowLayout in layoutWindow:" + params);
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002445 }
Dianne Hackborn694f79b2010-03-17 19:44:59 -07002446 mPendingConfiguration.seq = 0;
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002447 int relayoutResult = sWindowSession.relayout(
2448 mWindow, params,
Mitsuru Oshima61324e52009-07-21 15:40:36 -07002449 (int) (mView.mMeasuredWidth * appScale + 0.5f),
2450 (int) (mView.mMeasuredHeight * appScale + 0.5f),
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002451 viewVisibility, insetsPending, mWinFrame,
Dianne Hackborn694f79b2010-03-17 19:44:59 -07002452 mPendingContentInsets, mPendingVisibleInsets,
2453 mPendingConfiguration, mSurface);
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002454 if (restore) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07002455 params.restore();
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002456 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002457
2458 if (mTranslator != null) {
2459 mTranslator.translateRectInScreenToAppWinFrame(mWinFrame);
2460 mTranslator.translateRectInScreenToAppWindow(mPendingContentInsets);
2461 mTranslator.translateRectInScreenToAppWindow(mPendingVisibleInsets);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002462 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002463 return relayoutResult;
2464 }
Romain Guy8506ab42009-06-11 17:35:47 -07002465
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002466 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002467 * {@inheritDoc}
2468 */
2469 public void playSoundEffect(int effectId) {
2470 checkThread();
2471
Jean-Michel Trivi13b18fd2010-05-05 09:18:15 -07002472 try {
2473 final AudioManager audioManager = getAudioManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002474
Jean-Michel Trivi13b18fd2010-05-05 09:18:15 -07002475 switch (effectId) {
2476 case SoundEffectConstants.CLICK:
2477 audioManager.playSoundEffect(AudioManager.FX_KEY_CLICK);
2478 return;
2479 case SoundEffectConstants.NAVIGATION_DOWN:
2480 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_DOWN);
2481 return;
2482 case SoundEffectConstants.NAVIGATION_LEFT:
2483 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_LEFT);
2484 return;
2485 case SoundEffectConstants.NAVIGATION_RIGHT:
2486 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_RIGHT);
2487 return;
2488 case SoundEffectConstants.NAVIGATION_UP:
2489 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_UP);
2490 return;
2491 default:
2492 throw new IllegalArgumentException("unknown effect id " + effectId +
2493 " not defined in " + SoundEffectConstants.class.getCanonicalName());
2494 }
2495 } catch (IllegalStateException e) {
2496 // Exception thrown by getAudioManager() when mView is null
2497 Log.e(TAG, "FATAL EXCEPTION when attempting to play sound effect: " + e);
2498 e.printStackTrace();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002499 }
2500 }
2501
2502 /**
2503 * {@inheritDoc}
2504 */
2505 public boolean performHapticFeedback(int effectId, boolean always) {
2506 try {
2507 return sWindowSession.performHapticFeedback(mWindow, effectId, always);
2508 } catch (RemoteException e) {
2509 return false;
2510 }
2511 }
2512
2513 /**
2514 * {@inheritDoc}
2515 */
2516 public View focusSearch(View focused, int direction) {
2517 checkThread();
2518 if (!(mView instanceof ViewGroup)) {
2519 return null;
2520 }
2521 return FocusFinder.getInstance().findNextFocus((ViewGroup) mView, focused, direction);
2522 }
2523
2524 public void debug() {
2525 mView.debug();
2526 }
2527
2528 public void die(boolean immediate) {
Dianne Hackborn94d69142009-09-28 22:14:42 -07002529 if (immediate) {
2530 doDie();
2531 } else {
2532 sendEmptyMessage(DIE);
2533 }
2534 }
2535
2536 void doDie() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002537 checkThread();
Jeff Brownb75fa302010-07-15 23:47:29 -07002538 if (LOCAL_LOGV) Log.v(TAG, "DIE in " + this + " of " + mSurface);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002539 synchronized (this) {
2540 if (mAdded && !mFirst) {
Romain Guy29d89972010-09-22 16:10:57 -07002541 destroyHardwareRenderer();
2542
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002543 int viewVisibility = mView.getVisibility();
2544 boolean viewVisibilityChanged = mViewVisibility != viewVisibility;
2545 if (mWindowAttributesChanged || viewVisibilityChanged) {
2546 // If layout params have been changed, first give them
2547 // to the window manager to make sure it has the correct
2548 // animation info.
2549 try {
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002550 if ((relayoutWindow(mWindowAttributes, viewVisibility, false)
2551 & WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002552 sWindowSession.finishDrawing(mWindow);
2553 }
2554 } catch (RemoteException e) {
2555 }
2556 }
2557
Dianne Hackborn0586a1b2009-09-06 21:08:27 -07002558 mSurface.release();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002559 }
2560 if (mAdded) {
2561 mAdded = false;
Dianne Hackborn94d69142009-09-28 22:14:42 -07002562 dispatchDetachedFromWindow();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002563 }
2564 }
2565 }
2566
Romain Guy29d89972010-09-22 16:10:57 -07002567 private void destroyHardwareRenderer() {
2568 if (mHwRenderer != null) {
2569 mHwRenderer.destroy(true);
2570 mHwRenderer = null;
2571 mAttachInfo.mHardwareAccelerated = false;
2572 }
2573 }
2574
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002575 public void dispatchFinishedEvent(int seq, boolean handled) {
2576 Message msg = obtainMessage(FINISHED_EVENT);
2577 msg.arg1 = seq;
2578 msg.arg2 = handled ? 1 : 0;
2579 sendMessage(msg);
2580 }
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002581
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002582 public void dispatchResized(int w, int h, Rect coveredInsets,
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002583 Rect visibleInsets, boolean reportDraw, Configuration newConfig) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002584 if (DEBUG_LAYOUT) Log.v(TAG, "Resizing " + this + ": w=" + w
2585 + " h=" + h + " coveredInsets=" + coveredInsets.toShortString()
2586 + " visibleInsets=" + visibleInsets.toShortString()
2587 + " reportDraw=" + reportDraw);
2588 Message msg = obtainMessage(reportDraw ? RESIZED_REPORT :RESIZED);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002589 if (mTranslator != null) {
2590 mTranslator.translateRectInScreenToAppWindow(coveredInsets);
2591 mTranslator.translateRectInScreenToAppWindow(visibleInsets);
2592 w *= mTranslator.applicationInvertedScale;
2593 h *= mTranslator.applicationInvertedScale;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002594 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002595 msg.arg1 = w;
2596 msg.arg2 = h;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002597 ResizedInfo ri = new ResizedInfo();
2598 ri.coveredInsets = new Rect(coveredInsets);
2599 ri.visibleInsets = new Rect(visibleInsets);
2600 ri.newConfig = newConfig;
2601 msg.obj = ri;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002602 sendMessage(msg);
2603 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002604
2605 private Runnable mFinishedCallback;
2606
2607 private final InputHandler mInputHandler = new InputHandler() {
2608 public void handleKey(KeyEvent event, Runnable finishedCallback) {
Jeff Brown92ff1dd2010-08-11 16:16:06 -07002609 if (mFinishedCallback != null) {
2610 Slog.w(TAG, "Received a new key event from the input queue but there is "
2611 + "already an unfinished key event in progress.");
2612 }
2613
Jeff Brown46b9ac02010-04-22 18:58:52 -07002614 mFinishedCallback = finishedCallback;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002615
Jeff Brown92ff1dd2010-08-11 16:16:06 -07002616 dispatchKey(event, true);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002617 }
2618
Jeff Brownc5ed5912010-07-14 18:48:53 -07002619 public void handleMotion(MotionEvent event, Runnable finishedCallback) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002620 finishedCallback.run();
2621
Jeff Brownc5ed5912010-07-14 18:48:53 -07002622 dispatchMotion(event);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002623 }
2624 };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002625
2626 public void dispatchKey(KeyEvent event) {
Jeff Brown92ff1dd2010-08-11 16:16:06 -07002627 dispatchKey(event, false);
2628 }
2629
2630 private void dispatchKey(KeyEvent event, boolean sendDone) {
2631 //noinspection ConstantConditions
2632 if (false && event.getAction() == KeyEvent.ACTION_DOWN) {
2633 if (event.getKeyCode() == KeyEvent.KEYCODE_CAMERA) {
Romain Guy812ccbe2010-06-01 14:07:24 -07002634 if (DBG) Log.d("keydisp", "===================================================");
2635 if (DBG) Log.d("keydisp", "Focused view Hierarchy is:");
2636
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002637 debug();
2638
Romain Guy812ccbe2010-06-01 14:07:24 -07002639 if (DBG) Log.d("keydisp", "===================================================");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002640 }
2641 }
2642
2643 Message msg = obtainMessage(DISPATCH_KEY);
2644 msg.obj = event;
Jeff Brown92ff1dd2010-08-11 16:16:06 -07002645 msg.arg1 = sendDone ? 1 : 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002646
2647 if (LOCAL_LOGV) Log.v(
Jeff Brownc5ed5912010-07-14 18:48:53 -07002648 TAG, "sending key " + event + " to " + mView);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002649
2650 sendMessageAtTime(msg, event.getEventTime());
2651 }
Jeff Brownc5ed5912010-07-14 18:48:53 -07002652
2653 public void dispatchMotion(MotionEvent event) {
2654 int source = event.getSource();
2655 if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
2656 dispatchPointer(event);
2657 } else if ((source & InputDevice.SOURCE_CLASS_TRACKBALL) != 0) {
2658 dispatchTrackball(event);
2659 } else {
2660 // TODO
2661 Log.v(TAG, "Dropping unsupported motion event (unimplemented): " + event);
2662 }
2663 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002664
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002665 public void dispatchPointer(MotionEvent event) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002666 Message msg = obtainMessage(DISPATCH_POINTER);
2667 msg.obj = event;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002668 sendMessageAtTime(msg, event.getEventTime());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002669 }
2670
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002671 public void dispatchTrackball(MotionEvent event) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002672 Message msg = obtainMessage(DISPATCH_TRACKBALL);
2673 msg.obj = event;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002674 sendMessageAtTime(msg, event.getEventTime());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002675 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002676
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002677 public void dispatchAppVisibility(boolean visible) {
2678 Message msg = obtainMessage(DISPATCH_APP_VISIBILITY);
2679 msg.arg1 = visible ? 1 : 0;
2680 sendMessage(msg);
2681 }
2682
2683 public void dispatchGetNewSurface() {
2684 Message msg = obtainMessage(DISPATCH_GET_NEW_SURFACE);
2685 sendMessage(msg);
2686 }
2687
2688 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
2689 Message msg = Message.obtain();
2690 msg.what = WINDOW_FOCUS_CHANGED;
2691 msg.arg1 = hasFocus ? 1 : 0;
2692 msg.arg2 = inTouchMode ? 1 : 0;
2693 sendMessage(msg);
2694 }
2695
Dianne Hackbornffa42482009-09-23 22:20:11 -07002696 public void dispatchCloseSystemDialogs(String reason) {
2697 Message msg = Message.obtain();
2698 msg.what = CLOSE_SYSTEM_DIALOGS;
2699 msg.obj = reason;
2700 sendMessage(msg);
2701 }
2702
svetoslavganov75986cf2009-05-14 22:28:01 -07002703 /**
2704 * The window is getting focus so if there is anything focused/selected
2705 * send an {@link AccessibilityEvent} to announce that.
2706 */
2707 private void sendAccessibilityEvents() {
2708 if (!AccessibilityManager.getInstance(mView.getContext()).isEnabled()) {
2709 return;
2710 }
2711 mView.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
2712 View focusedView = mView.findFocus();
2713 if (focusedView != null && focusedView != mView) {
2714 focusedView.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
2715 }
2716 }
2717
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002718 public boolean showContextMenuForChild(View originalView) {
2719 return false;
2720 }
2721
Adam Powell6e346362010-07-23 10:18:23 -07002722 public ActionMode startActionModeForChild(View originalView, ActionMode.Callback callback) {
2723 return null;
2724 }
2725
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002726 public void createContextMenu(ContextMenu menu) {
2727 }
2728
2729 public void childDrawableStateChanged(View child) {
2730 }
2731
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002732 void checkThread() {
2733 if (mThread != Thread.currentThread()) {
2734 throw new CalledFromWrongThreadException(
2735 "Only the original thread that created a view hierarchy can touch its views.");
2736 }
2737 }
2738
2739 public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
2740 // ViewRoot never intercepts touch event, so this can be a no-op
2741 }
2742
2743 public boolean requestChildRectangleOnScreen(View child, Rect rectangle,
2744 boolean immediate) {
2745 return scrollToRectOrFocus(rectangle, immediate);
2746 }
Romain Guy8506ab42009-06-11 17:35:47 -07002747
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07002748 class TakenSurfaceHolder extends BaseSurfaceHolder {
2749 @Override
2750 public boolean onAllowLockCanvas() {
2751 return mDrawingAllowed;
2752 }
2753
2754 @Override
2755 public void onRelayoutContainer() {
2756 // Not currently interesting -- from changing between fixed and layout size.
2757 }
2758
2759 public void setFormat(int format) {
2760 ((RootViewSurfaceTaker)mView).setSurfaceFormat(format);
2761 }
2762
2763 public void setType(int type) {
2764 ((RootViewSurfaceTaker)mView).setSurfaceType(type);
2765 }
2766
2767 @Override
2768 public void onUpdateSurface() {
2769 // We take care of format and type changes on our own.
2770 throw new IllegalStateException("Shouldn't be here");
2771 }
2772
2773 public boolean isCreating() {
2774 return mIsCreating;
2775 }
2776
2777 @Override
2778 public void setFixedSize(int width, int height) {
2779 throw new UnsupportedOperationException(
2780 "Currently only support sizing from layout");
2781 }
2782
2783 public void setKeepScreenOn(boolean screenOn) {
2784 ((RootViewSurfaceTaker)mView).setSurfaceKeepScreenOn(screenOn);
2785 }
2786 }
2787
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002788 static class InputMethodCallback extends IInputMethodCallback.Stub {
2789 private WeakReference<ViewRoot> mViewRoot;
2790
2791 public InputMethodCallback(ViewRoot viewRoot) {
2792 mViewRoot = new WeakReference<ViewRoot>(viewRoot);
2793 }
Romain Guy8506ab42009-06-11 17:35:47 -07002794
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002795 public void finishedEvent(int seq, boolean handled) {
2796 final ViewRoot viewRoot = mViewRoot.get();
2797 if (viewRoot != null) {
2798 viewRoot.dispatchFinishedEvent(seq, handled);
2799 }
2800 }
2801
2802 public void sessionCreated(IInputMethodSession session) throws RemoteException {
2803 // Stub -- not for use in the client.
2804 }
2805 }
Romain Guy8506ab42009-06-11 17:35:47 -07002806
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002807 static class W extends IWindow.Stub {
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002808 private final WeakReference<ViewRoot> mViewRoot;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002809
Romain Guyfb8b7632010-08-23 21:05:08 -07002810 W(ViewRoot viewRoot) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002811 mViewRoot = new WeakReference<ViewRoot>(viewRoot);
2812 }
2813
Romain Guyfb8b7632010-08-23 21:05:08 -07002814 public void resized(int w, int h, Rect coveredInsets, Rect visibleInsets,
2815 boolean reportDraw, Configuration newConfig) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002816 final ViewRoot viewRoot = mViewRoot.get();
2817 if (viewRoot != null) {
Romain Guyfb8b7632010-08-23 21:05:08 -07002818 viewRoot.dispatchResized(w, h, coveredInsets, visibleInsets, reportDraw, newConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002819 }
2820 }
2821
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002822 public void dispatchAppVisibility(boolean visible) {
2823 final ViewRoot viewRoot = mViewRoot.get();
2824 if (viewRoot != null) {
2825 viewRoot.dispatchAppVisibility(visible);
2826 }
2827 }
2828
2829 public void dispatchGetNewSurface() {
2830 final ViewRoot viewRoot = mViewRoot.get();
2831 if (viewRoot != null) {
2832 viewRoot.dispatchGetNewSurface();
2833 }
2834 }
2835
2836 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
2837 final ViewRoot viewRoot = mViewRoot.get();
2838 if (viewRoot != null) {
2839 viewRoot.windowFocusChanged(hasFocus, inTouchMode);
2840 }
2841 }
2842
2843 private static int checkCallingPermission(String permission) {
2844 if (!Process.supportsProcesses()) {
2845 return PackageManager.PERMISSION_GRANTED;
2846 }
2847
2848 try {
2849 return ActivityManagerNative.getDefault().checkPermission(
2850 permission, Binder.getCallingPid(), Binder.getCallingUid());
2851 } catch (RemoteException e) {
2852 return PackageManager.PERMISSION_DENIED;
2853 }
2854 }
2855
2856 public void executeCommand(String command, String parameters, ParcelFileDescriptor out) {
2857 final ViewRoot viewRoot = mViewRoot.get();
2858 if (viewRoot != null) {
2859 final View view = viewRoot.mView;
2860 if (view != null) {
2861 if (checkCallingPermission(Manifest.permission.DUMP) !=
2862 PackageManager.PERMISSION_GRANTED) {
2863 throw new SecurityException("Insufficient permissions to invoke"
2864 + " executeCommand() from pid=" + Binder.getCallingPid()
2865 + ", uid=" + Binder.getCallingUid());
2866 }
2867
2868 OutputStream clientStream = null;
2869 try {
2870 clientStream = new ParcelFileDescriptor.AutoCloseOutputStream(out);
2871 ViewDebug.dispatchCommand(view, command, parameters, clientStream);
2872 } catch (IOException e) {
2873 e.printStackTrace();
2874 } finally {
2875 if (clientStream != null) {
2876 try {
2877 clientStream.close();
2878 } catch (IOException e) {
2879 e.printStackTrace();
2880 }
2881 }
2882 }
2883 }
2884 }
2885 }
Dianne Hackborn72c82ab2009-08-11 21:13:54 -07002886
Dianne Hackbornffa42482009-09-23 22:20:11 -07002887 public void closeSystemDialogs(String reason) {
2888 final ViewRoot viewRoot = mViewRoot.get();
2889 if (viewRoot != null) {
2890 viewRoot.dispatchCloseSystemDialogs(reason);
2891 }
2892 }
2893
Marco Nelissenbf6956b2009-11-09 15:21:13 -08002894 public void dispatchWallpaperOffsets(float x, float y, float xStep, float yStep,
2895 boolean sync) {
Dianne Hackborn19382ac2009-09-11 21:13:37 -07002896 if (sync) {
2897 try {
2898 sWindowSession.wallpaperOffsetsComplete(asBinder());
2899 } catch (RemoteException e) {
2900 }
2901 }
Dianne Hackborn72c82ab2009-08-11 21:13:54 -07002902 }
Dianne Hackborn75804932009-10-20 20:15:20 -07002903
2904 public void dispatchWallpaperCommand(String action, int x, int y,
2905 int z, Bundle extras, boolean sync) {
2906 if (sync) {
2907 try {
2908 sWindowSession.wallpaperCommandComplete(asBinder(), null);
2909 } catch (RemoteException e) {
2910 }
2911 }
2912 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002913 }
2914
2915 /**
2916 * Maintains state information for a single trackball axis, generating
2917 * discrete (DPAD) movements based on raw trackball motion.
2918 */
2919 static final class TrackballAxis {
2920 /**
2921 * The maximum amount of acceleration we will apply.
2922 */
2923 static final float MAX_ACCELERATION = 20;
Romain Guy8506ab42009-06-11 17:35:47 -07002924
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002925 /**
2926 * The maximum amount of time (in milliseconds) between events in order
2927 * for us to consider the user to be doing fast trackball movements,
2928 * and thus apply an acceleration.
2929 */
2930 static final long FAST_MOVE_TIME = 150;
Romain Guy8506ab42009-06-11 17:35:47 -07002931
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002932 /**
2933 * Scaling factor to the time (in milliseconds) between events to how
2934 * much to multiple/divide the current acceleration. When movement
2935 * is < FAST_MOVE_TIME this multiplies the acceleration; when >
2936 * FAST_MOVE_TIME it divides it.
2937 */
2938 static final float ACCEL_MOVE_SCALING_FACTOR = (1.0f/40);
Romain Guy8506ab42009-06-11 17:35:47 -07002939
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002940 float position;
2941 float absPosition;
2942 float acceleration = 1;
2943 long lastMoveTime = 0;
2944 int step;
2945 int dir;
2946 int nonAccelMovement;
2947
2948 void reset(int _step) {
2949 position = 0;
2950 acceleration = 1;
2951 lastMoveTime = 0;
2952 step = _step;
2953 dir = 0;
2954 }
2955
2956 /**
2957 * Add trackball movement into the state. If the direction of movement
2958 * has been reversed, the state is reset before adding the
2959 * movement (so that you don't have to compensate for any previously
2960 * collected movement before see the result of the movement in the
2961 * new direction).
2962 *
2963 * @return Returns the absolute value of the amount of movement
2964 * collected so far.
2965 */
2966 float collect(float off, long time, String axis) {
2967 long normTime;
2968 if (off > 0) {
2969 normTime = (long)(off * FAST_MOVE_TIME);
2970 if (dir < 0) {
2971 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to positive!");
2972 position = 0;
2973 step = 0;
2974 acceleration = 1;
2975 lastMoveTime = 0;
2976 }
2977 dir = 1;
2978 } else if (off < 0) {
2979 normTime = (long)((-off) * FAST_MOVE_TIME);
2980 if (dir > 0) {
2981 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to negative!");
2982 position = 0;
2983 step = 0;
2984 acceleration = 1;
2985 lastMoveTime = 0;
2986 }
2987 dir = -1;
2988 } else {
2989 normTime = 0;
2990 }
Romain Guy8506ab42009-06-11 17:35:47 -07002991
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002992 // The number of milliseconds between each movement that is
2993 // considered "normal" and will not result in any acceleration
2994 // or deceleration, scaled by the offset we have here.
2995 if (normTime > 0) {
2996 long delta = time - lastMoveTime;
2997 lastMoveTime = time;
2998 float acc = acceleration;
2999 if (delta < normTime) {
3000 // The user is scrolling rapidly, so increase acceleration.
3001 float scale = (normTime-delta) * ACCEL_MOVE_SCALING_FACTOR;
3002 if (scale > 1) acc *= scale;
3003 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " accelerate: off="
3004 + off + " normTime=" + normTime + " delta=" + delta
3005 + " scale=" + scale + " acc=" + acc);
3006 acceleration = acc < MAX_ACCELERATION ? acc : MAX_ACCELERATION;
3007 } else {
3008 // The user is scrolling slowly, so decrease acceleration.
3009 float scale = (delta-normTime) * ACCEL_MOVE_SCALING_FACTOR;
3010 if (scale > 1) acc /= scale;
3011 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " deccelerate: off="
3012 + off + " normTime=" + normTime + " delta=" + delta
3013 + " scale=" + scale + " acc=" + acc);
3014 acceleration = acc > 1 ? acc : 1;
3015 }
3016 }
3017 position += off;
3018 return (absPosition = Math.abs(position));
3019 }
3020
3021 /**
3022 * Generate the number of discrete movement events appropriate for
3023 * the currently collected trackball movement.
3024 *
3025 * @param precision The minimum movement required to generate the
3026 * first discrete movement.
3027 *
3028 * @return Returns the number of discrete movements, either positive
3029 * or negative, or 0 if there is not enough trackball movement yet
3030 * for a discrete movement.
3031 */
3032 int generate(float precision) {
3033 int movement = 0;
3034 nonAccelMovement = 0;
3035 do {
3036 final int dir = position >= 0 ? 1 : -1;
3037 switch (step) {
3038 // If we are going to execute the first step, then we want
3039 // to do this as soon as possible instead of waiting for
3040 // a full movement, in order to make things look responsive.
3041 case 0:
3042 if (absPosition < precision) {
3043 return movement;
3044 }
3045 movement += dir;
3046 nonAccelMovement += dir;
3047 step = 1;
3048 break;
3049 // If we have generated the first movement, then we need
3050 // to wait for the second complete trackball motion before
3051 // generating the second discrete movement.
3052 case 1:
3053 if (absPosition < 2) {
3054 return movement;
3055 }
3056 movement += dir;
3057 nonAccelMovement += dir;
3058 position += dir > 0 ? -2 : 2;
3059 absPosition = Math.abs(position);
3060 step = 2;
3061 break;
3062 // After the first two, we generate discrete movements
3063 // consistently with the trackball, applying an acceleration
3064 // if the trackball is moving quickly. This is a simple
3065 // acceleration on top of what we already compute based
3066 // on how quickly the wheel is being turned, to apply
3067 // a longer increasing acceleration to continuous movement
3068 // in one direction.
3069 default:
3070 if (absPosition < 1) {
3071 return movement;
3072 }
3073 movement += dir;
3074 position += dir >= 0 ? -1 : 1;
3075 absPosition = Math.abs(position);
3076 float acc = acceleration;
3077 acc *= 1.1f;
3078 acceleration = acc < MAX_ACCELERATION ? acc : acceleration;
3079 break;
3080 }
3081 } while (true);
3082 }
3083 }
3084
3085 public static final class CalledFromWrongThreadException extends AndroidRuntimeException {
3086 public CalledFromWrongThreadException(String msg) {
3087 super(msg);
3088 }
3089 }
3090
3091 private SurfaceHolder mHolder = new SurfaceHolder() {
3092 // we only need a SurfaceHolder for opengl. it would be nice
3093 // to implement everything else though, especially the callback
3094 // support (opengl doesn't make use of it right now, but eventually
3095 // will).
3096 public Surface getSurface() {
3097 return mSurface;
3098 }
3099
3100 public boolean isCreating() {
3101 return false;
3102 }
3103
3104 public void addCallback(Callback callback) {
3105 }
3106
3107 public void removeCallback(Callback callback) {
3108 }
3109
3110 public void setFixedSize(int width, int height) {
3111 }
3112
3113 public void setSizeFromLayout() {
3114 }
3115
3116 public void setFormat(int format) {
3117 }
3118
3119 public void setType(int type) {
3120 }
3121
3122 public void setKeepScreenOn(boolean screenOn) {
3123 }
3124
3125 public Canvas lockCanvas() {
3126 return null;
3127 }
3128
3129 public Canvas lockCanvas(Rect dirty) {
3130 return null;
3131 }
3132
3133 public void unlockCanvasAndPost(Canvas canvas) {
3134 }
3135 public Rect getSurfaceFrame() {
3136 return null;
3137 }
3138 };
3139
3140 static RunQueue getRunQueue() {
3141 RunQueue rq = sRunQueues.get();
3142 if (rq != null) {
3143 return rq;
3144 }
3145 rq = new RunQueue();
3146 sRunQueues.set(rq);
3147 return rq;
3148 }
Romain Guy8506ab42009-06-11 17:35:47 -07003149
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003150 /**
3151 * @hide
3152 */
3153 static final class RunQueue {
3154 private final ArrayList<HandlerAction> mActions = new ArrayList<HandlerAction>();
3155
3156 void post(Runnable action) {
3157 postDelayed(action, 0);
3158 }
3159
3160 void postDelayed(Runnable action, long delayMillis) {
3161 HandlerAction handlerAction = new HandlerAction();
3162 handlerAction.action = action;
3163 handlerAction.delay = delayMillis;
3164
3165 synchronized (mActions) {
3166 mActions.add(handlerAction);
3167 }
3168 }
3169
3170 void removeCallbacks(Runnable action) {
3171 final HandlerAction handlerAction = new HandlerAction();
3172 handlerAction.action = action;
3173
3174 synchronized (mActions) {
3175 final ArrayList<HandlerAction> actions = mActions;
3176
3177 while (actions.remove(handlerAction)) {
3178 // Keep going
3179 }
3180 }
3181 }
3182
3183 void executeActions(Handler handler) {
3184 synchronized (mActions) {
3185 final ArrayList<HandlerAction> actions = mActions;
3186 final int count = actions.size();
3187
3188 for (int i = 0; i < count; i++) {
3189 final HandlerAction handlerAction = actions.get(i);
3190 handler.postDelayed(handlerAction.action, handlerAction.delay);
3191 }
3192
Romain Guy15df6702009-08-17 20:17:30 -07003193 actions.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003194 }
3195 }
3196
3197 private static class HandlerAction {
3198 Runnable action;
3199 long delay;
3200
3201 @Override
3202 public boolean equals(Object o) {
3203 if (this == o) return true;
3204 if (o == null || getClass() != o.getClass()) return false;
3205
3206 HandlerAction that = (HandlerAction) o;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003207 return !(action != null ? !action.equals(that.action) : that.action != null);
3208
3209 }
3210
3211 @Override
3212 public int hashCode() {
3213 int result = action != null ? action.hashCode() : 0;
3214 result = 31 * result + (int) (delay ^ (delay >>> 32));
3215 return result;
3216 }
3217 }
3218 }
3219
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003220 private static native void nativeShowFPS(Canvas canvas, int durationMillis);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003221}