blob: e61eaed9fb159a21550abb39d1cd43be00001fed [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;
Jeff Brown46b9ac02010-04-22 18:58:52 -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);
458 }
459 }
460 }
461
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800462 public View getView() {
463 return mView;
464 }
465
466 final WindowLeaked getLocation() {
467 return mLocation;
468 }
469
470 void setLayoutParams(WindowManager.LayoutParams attrs, boolean newView) {
471 synchronized (this) {
The Android Open Source Project10592532009-03-18 17:39:46 -0700472 int oldSoftInputMode = mWindowAttributes.softInputMode;
Mitsuru Oshima5a2b91d2009-07-16 16:30:02 -0700473 // preserve compatible window flag if exists.
474 int compatibleWindowFlag =
475 mWindowAttributes.flags & WindowManager.LayoutParams.FLAG_COMPATIBLE_WINDOW;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800476 mWindowAttributes.copyFrom(attrs);
Mitsuru Oshima5a2b91d2009-07-16 16:30:02 -0700477 mWindowAttributes.flags |= compatibleWindowFlag;
478
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800479 if (newView) {
480 mSoftInputMode = attrs.softInputMode;
481 requestLayout();
482 }
The Android Open Source Project10592532009-03-18 17:39:46 -0700483 // Don't lose the mode we last auto-computed.
484 if ((attrs.softInputMode&WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST)
485 == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED) {
486 mWindowAttributes.softInputMode = (mWindowAttributes.softInputMode
487 & ~WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST)
488 | (oldSoftInputMode
489 & WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST);
490 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800491 mWindowAttributesChanged = true;
492 scheduleTraversals();
493 }
494 }
495
496 void handleAppVisibility(boolean visible) {
497 if (mAppVisible != visible) {
498 mAppVisible = visible;
499 scheduleTraversals();
500 }
501 }
502
503 void handleGetNewSurface() {
504 mNewSurfaceNeeded = true;
505 mFullRedrawNeeded = true;
506 scheduleTraversals();
507 }
508
509 /**
510 * {@inheritDoc}
511 */
512 public void requestLayout() {
513 checkThread();
514 mLayoutRequested = true;
515 scheduleTraversals();
516 }
517
518 /**
519 * {@inheritDoc}
520 */
521 public boolean isLayoutRequested() {
522 return mLayoutRequested;
523 }
524
525 public void invalidateChild(View child, Rect dirty) {
526 checkThread();
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700527 if (DEBUG_DRAW) Log.v(TAG, "Invalidate child: " + dirty);
528 if (mCurScrollY != 0 || mTranslator != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800529 mTempRect.set(dirty);
Romain Guy1e095972009-07-07 11:22:45 -0700530 dirty = mTempRect;
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700531 if (mCurScrollY != 0) {
Romain Guy1e095972009-07-07 11:22:45 -0700532 dirty.offset(0, -mCurScrollY);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700533 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700534 if (mTranslator != null) {
Romain Guy1e095972009-07-07 11:22:45 -0700535 mTranslator.translateRectInAppWindowToScreen(dirty);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700536 }
Romain Guy1e095972009-07-07 11:22:45 -0700537 if (mAttachInfo.mScalingRequired) {
538 dirty.inset(-1, -1);
539 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800540 }
541 mDirty.union(dirty);
542 if (!mWillDrawSoon) {
543 scheduleTraversals();
544 }
545 }
546
547 public ViewParent getParent() {
548 return null;
549 }
550
551 public ViewParent invalidateChildInParent(final int[] location, final Rect dirty) {
552 invalidateChild(null, dirty);
553 return null;
554 }
555
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700556 public boolean getChildVisibleRect(View child, Rect r, android.graphics.Point offset) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800557 if (child != mView) {
558 throw new RuntimeException("child is not mine, honest!");
559 }
560 // Note: don't apply scroll offset, because we want to know its
561 // visibility in the virtual canvas being given to the view hierarchy.
562 return r.intersect(0, 0, mWidth, mHeight);
563 }
564
565 public void bringChildToFront(View child) {
566 }
567
568 public void scheduleTraversals() {
569 if (!mTraversalScheduled) {
570 mTraversalScheduled = true;
571 sendEmptyMessage(DO_TRAVERSAL);
572 }
573 }
574
575 public void unscheduleTraversals() {
576 if (mTraversalScheduled) {
577 mTraversalScheduled = false;
578 removeMessages(DO_TRAVERSAL);
579 }
580 }
581
582 int getHostVisibility() {
583 return mAppVisible ? mView.getVisibility() : View.GONE;
584 }
Romain Guy8506ab42009-06-11 17:35:47 -0700585
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800586 private void performTraversals() {
587 // cache mView since it is used so much below...
588 final View host = mView;
589
590 if (DBG) {
591 System.out.println("======================================");
592 System.out.println("performTraversals");
593 host.debug();
594 }
595
596 if (host == null || !mAdded)
597 return;
598
599 mTraversalScheduled = false;
600 mWillDrawSoon = true;
601 boolean windowResizesToFitContent = false;
602 boolean fullRedrawNeeded = mFullRedrawNeeded;
603 boolean newSurface = false;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700604 boolean surfaceChanged = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800605 WindowManager.LayoutParams lp = mWindowAttributes;
606
607 int desiredWindowWidth;
608 int desiredWindowHeight;
609 int childWidthMeasureSpec;
610 int childHeightMeasureSpec;
611
612 final View.AttachInfo attachInfo = mAttachInfo;
613
614 final int viewVisibility = getHostVisibility();
615 boolean viewVisibilityChanged = mViewVisibility != viewVisibility
616 || mNewSurfaceNeeded;
617
618 WindowManager.LayoutParams params = null;
619 if (mWindowAttributesChanged) {
620 mWindowAttributesChanged = false;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700621 surfaceChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800622 params = lp;
623 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700624 Rect frame = mWinFrame;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800625 if (mFirst) {
626 fullRedrawNeeded = true;
627 mLayoutRequested = true;
628
Romain Guy8506ab42009-06-11 17:35:47 -0700629 DisplayMetrics packageMetrics =
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700630 mView.getContext().getResources().getDisplayMetrics();
631 desiredWindowWidth = packageMetrics.widthPixels;
632 desiredWindowHeight = packageMetrics.heightPixels;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800633
634 // For the very first time, tell the view hierarchy that it
635 // is attached to the window. Note that at this point the surface
636 // object is not initialized to its backing store, but soon it
637 // will be (assuming the window is visible).
638 attachInfo.mSurface = mSurface;
Dianne Hackborn289b9b62010-07-09 11:44:11 -0700639 attachInfo.mTranslucentWindow = PixelFormat.formatHasAlpha(lp.format);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800640 attachInfo.mHasWindowFocus = false;
641 attachInfo.mWindowVisibility = viewVisibility;
642 attachInfo.mRecomputeGlobalAttributes = false;
643 attachInfo.mKeepScreenOn = false;
644 viewVisibilityChanged = false;
Dianne Hackborn694f79b2010-03-17 19:44:59 -0700645 mLastConfiguration.setTo(host.getResources().getConfiguration());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800646 host.dispatchAttachedToWindow(attachInfo, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800647 //Log.i(TAG, "Screen on initialized: " + attachInfo.mKeepScreenOn);
svetoslavganov75986cf2009-05-14 22:28:01 -0700648
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800649 } else {
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700650 desiredWindowWidth = frame.width();
651 desiredWindowHeight = frame.height();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800652 if (desiredWindowWidth != mWidth || desiredWindowHeight != mHeight) {
Jeff Brownc5ed5912010-07-14 18:48:53 -0700653 if (DEBUG_ORIENTATION) Log.v(TAG,
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700654 "View " + host + " resized to: " + frame);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800655 fullRedrawNeeded = true;
656 mLayoutRequested = true;
657 windowResizesToFitContent = true;
658 }
659 }
660
661 if (viewVisibilityChanged) {
662 attachInfo.mWindowVisibility = viewVisibility;
663 host.dispatchWindowVisibilityChanged(viewVisibility);
664 if (viewVisibility != View.VISIBLE || mNewSurfaceNeeded) {
Romain Guy4caa4ed2010-08-25 14:46:24 -0700665 if (mHwRenderer != null) {
666 mHwRenderer.destroy(false);
667 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800668 }
669 if (viewVisibility == View.GONE) {
670 // After making a window gone, we will count it as being
671 // shown for the first time the next time it gets focus.
672 mHasHadWindowFocus = false;
673 }
674 }
675
676 boolean insetsChanged = false;
Romain Guy8506ab42009-06-11 17:35:47 -0700677
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800678 if (mLayoutRequested) {
Romain Guy15df6702009-08-17 20:17:30 -0700679 // Execute enqueued actions on every layout in case a view that was detached
680 // enqueued an action after being detached
681 getRunQueue().executeActions(attachInfo.mHandler);
682
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800683 if (mFirst) {
684 host.fitSystemWindows(mAttachInfo.mContentInsets);
685 // make sure touch mode code executes by setting cached value
686 // to opposite of the added touch mode.
687 mAttachInfo.mInTouchMode = !mAddedTouchMode;
Romain Guy2d4cff62010-04-09 15:39:00 -0700688 ensureTouchModeLocally(mAddedTouchMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800689 } else {
690 if (!mAttachInfo.mContentInsets.equals(mPendingContentInsets)) {
691 mAttachInfo.mContentInsets.set(mPendingContentInsets);
692 host.fitSystemWindows(mAttachInfo.mContentInsets);
693 insetsChanged = true;
694 if (DEBUG_LAYOUT) Log.v(TAG, "Content insets changing to: "
695 + mAttachInfo.mContentInsets);
696 }
697 if (!mAttachInfo.mVisibleInsets.equals(mPendingVisibleInsets)) {
698 mAttachInfo.mVisibleInsets.set(mPendingVisibleInsets);
699 if (DEBUG_LAYOUT) Log.v(TAG, "Visible insets changing to: "
700 + mAttachInfo.mVisibleInsets);
701 }
702 if (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT
703 || lp.height == ViewGroup.LayoutParams.WRAP_CONTENT) {
704 windowResizesToFitContent = true;
705
Romain Guy8506ab42009-06-11 17:35:47 -0700706 DisplayMetrics packageMetrics =
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700707 mView.getContext().getResources().getDisplayMetrics();
708 desiredWindowWidth = packageMetrics.widthPixels;
709 desiredWindowHeight = packageMetrics.heightPixels;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800710 }
711 }
712
713 childWidthMeasureSpec = getRootMeasureSpec(desiredWindowWidth, lp.width);
714 childHeightMeasureSpec = getRootMeasureSpec(desiredWindowHeight, lp.height);
715
716 // Ask host how big it wants to be
Jeff Brownc5ed5912010-07-14 18:48:53 -0700717 if (DEBUG_ORIENTATION || DEBUG_LAYOUT) Log.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800718 "Measuring " + host + " in display " + desiredWindowWidth
719 + "x" + desiredWindowHeight + "...");
720 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
721
722 if (DBG) {
723 System.out.println("======================================");
724 System.out.println("performTraversals -- after measure");
725 host.debug();
726 }
727 }
728
729 if (attachInfo.mRecomputeGlobalAttributes) {
730 //Log.i(TAG, "Computing screen on!");
731 attachInfo.mRecomputeGlobalAttributes = false;
732 boolean oldVal = attachInfo.mKeepScreenOn;
733 attachInfo.mKeepScreenOn = false;
734 host.dispatchCollectViewAttributes(0);
735 if (attachInfo.mKeepScreenOn != oldVal) {
736 params = lp;
737 //Log.i(TAG, "Keep screen on changed: " + attachInfo.mKeepScreenOn);
738 }
739 }
740
741 if (mFirst || attachInfo.mViewVisibilityChanged) {
742 attachInfo.mViewVisibilityChanged = false;
743 int resizeMode = mSoftInputMode &
744 WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST;
745 // If we are in auto resize mode, then we need to determine
746 // what mode to use now.
747 if (resizeMode == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED) {
748 final int N = attachInfo.mScrollContainers.size();
749 for (int i=0; i<N; i++) {
750 if (attachInfo.mScrollContainers.get(i).isShown()) {
751 resizeMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE;
752 }
753 }
754 if (resizeMode == 0) {
755 resizeMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN;
756 }
757 if ((lp.softInputMode &
758 WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) != resizeMode) {
759 lp.softInputMode = (lp.softInputMode &
760 ~WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) |
761 resizeMode;
762 params = lp;
763 }
764 }
765 }
Romain Guy8506ab42009-06-11 17:35:47 -0700766
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800767 if (params != null && (host.mPrivateFlags & View.REQUEST_TRANSPARENT_REGIONS) != 0) {
768 if (!PixelFormat.formatHasAlpha(params.format)) {
769 params.format = PixelFormat.TRANSLUCENT;
770 }
771 }
772
773 boolean windowShouldResize = mLayoutRequested && windowResizesToFitContent
Romain Guy2e4f4262010-04-06 11:07:52 -0700774 && ((mWidth != host.mMeasuredWidth || mHeight != host.mMeasuredHeight)
775 || (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT &&
776 frame.width() < desiredWindowWidth && frame.width() != mWidth)
777 || (lp.height == ViewGroup.LayoutParams.WRAP_CONTENT &&
778 frame.height() < desiredWindowHeight && frame.height() != mHeight));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800779
780 final boolean computesInternalInsets =
781 attachInfo.mTreeObserver.hasComputeInternalInsetsListeners();
Romain Guy812ccbe2010-06-01 14:07:24 -0700782
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800783 boolean insetsPending = false;
784 int relayoutResult = 0;
Romain Guy812ccbe2010-06-01 14:07:24 -0700785
786 if (mFirst || windowShouldResize || insetsChanged ||
787 viewVisibilityChanged || params != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800788
789 if (viewVisibility == View.VISIBLE) {
790 // If this window is giving internal insets to the window
791 // manager, and it is being added or changing its visibility,
792 // then we want to first give the window manager "fake"
793 // insets to cause it to effectively ignore the content of
794 // the window during layout. This avoids it briefly causing
795 // other windows to resize/move based on the raw frame of the
796 // window, waiting until we can finish laying out this window
797 // and get back to the window manager with the ultimately
798 // computed insets.
Romain Guy812ccbe2010-06-01 14:07:24 -0700799 insetsPending = computesInternalInsets && (mFirst || viewVisibilityChanged);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800800 }
801
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700802 if (mSurfaceHolder != null) {
803 mSurfaceHolder.mSurfaceLock.lock();
804 mDrawingAllowed = true;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700805 }
Romain Guy812ccbe2010-06-01 14:07:24 -0700806
807 boolean hwIntialized = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800808 boolean contentInsetsChanged = false;
Romain Guy13922e02009-05-12 17:56:14 -0700809 boolean visibleInsetsChanged;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700810 boolean hadSurface = mSurface.isValid();
Romain Guy812ccbe2010-06-01 14:07:24 -0700811
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800812 try {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800813 int fl = 0;
814 if (params != null) {
815 fl = params.flags;
816 if (attachInfo.mKeepScreenOn) {
817 params.flags |= WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
818 }
819 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700820 if (DEBUG_LAYOUT) {
821 Log.i(TAG, "host=w:" + host.mMeasuredWidth + ", h:" +
822 host.mMeasuredHeight + ", params=" + params);
823 }
824 relayoutResult = relayoutWindow(params, viewVisibility, insetsPending);
825
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800826 if (params != null) {
827 params.flags = fl;
828 }
829
830 if (DEBUG_LAYOUT) Log.v(TAG, "relayout: frame=" + frame.toShortString()
831 + " content=" + mPendingContentInsets.toShortString()
832 + " visible=" + mPendingVisibleInsets.toShortString()
833 + " surface=" + mSurface);
Romain Guy8506ab42009-06-11 17:35:47 -0700834
Dianne Hackborn694f79b2010-03-17 19:44:59 -0700835 if (mPendingConfiguration.seq != 0) {
836 if (DEBUG_CONFIGURATION) Log.v(TAG, "Visible with new config: "
837 + mPendingConfiguration);
838 updateConfiguration(mPendingConfiguration, !mFirst);
839 mPendingConfiguration.seq = 0;
840 }
841
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800842 contentInsetsChanged = !mPendingContentInsets.equals(
843 mAttachInfo.mContentInsets);
844 visibleInsetsChanged = !mPendingVisibleInsets.equals(
845 mAttachInfo.mVisibleInsets);
846 if (contentInsetsChanged) {
847 mAttachInfo.mContentInsets.set(mPendingContentInsets);
848 host.fitSystemWindows(mAttachInfo.mContentInsets);
849 if (DEBUG_LAYOUT) Log.v(TAG, "Content insets changing to: "
850 + mAttachInfo.mContentInsets);
851 }
852 if (visibleInsetsChanged) {
853 mAttachInfo.mVisibleInsets.set(mPendingVisibleInsets);
854 if (DEBUG_LAYOUT) Log.v(TAG, "Visible insets changing to: "
855 + mAttachInfo.mVisibleInsets);
856 }
857
858 if (!hadSurface) {
859 if (mSurface.isValid()) {
860 // If we are creating a new surface, then we need to
861 // completely redraw it. Also, when we get to the
862 // point of drawing it we will hold off and schedule
863 // a new traversal instead. This is so we can tell the
864 // window manager about all of the windows being displayed
865 // before actually drawing them, so it can display then
866 // all at once.
867 newSurface = true;
868 fullRedrawNeeded = true;
Jack Palevich61a6e682009-10-09 17:37:50 -0700869 mPreviousTransparentRegion.setEmpty();
Romain Guy8506ab42009-06-11 17:35:47 -0700870
Romain Guy812ccbe2010-06-01 14:07:24 -0700871 if (mHwRenderer != null) {
Romain Guy2d614592010-06-09 18:21:37 -0700872 hwIntialized = mHwRenderer.initialize(mHolder);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800873 }
874 }
875 } else if (!mSurface.isValid()) {
876 // If the surface has been removed, then reset the scroll
877 // positions.
878 mLastScrolledFocus = null;
879 mScrollY = mCurScrollY = 0;
880 if (mScroller != null) {
881 mScroller.abortAnimation();
882 }
883 }
884 } catch (RemoteException e) {
885 }
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700886
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800887 if (DEBUG_ORIENTATION) Log.v(
Jeff Brownc5ed5912010-07-14 18:48:53 -0700888 TAG, "Relayout returned: frame=" + frame + ", surface=" + mSurface);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800889
890 attachInfo.mWindowLeft = frame.left;
891 attachInfo.mWindowTop = frame.top;
892
893 // !!FIXME!! This next section handles the case where we did not get the
894 // window size we asked for. We should avoid this by getting a maximum size from
895 // the window session beforehand.
896 mWidth = frame.width();
897 mHeight = frame.height();
898
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700899 if (mSurfaceHolder != null) {
900 // The app owns the surface; tell it about what is going on.
901 if (mSurface.isValid()) {
902 // XXX .copyFrom() doesn't work!
903 //mSurfaceHolder.mSurface.copyFrom(mSurface);
904 mSurfaceHolder.mSurface = mSurface;
905 }
906 mSurfaceHolder.mSurfaceLock.unlock();
907 if (mSurface.isValid()) {
908 if (!hadSurface) {
909 mSurfaceHolder.ungetCallbacks();
910
911 mIsCreating = true;
912 mSurfaceHolderCallback.surfaceCreated(mSurfaceHolder);
913 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
914 if (callbacks != null) {
915 for (SurfaceHolder.Callback c : callbacks) {
916 c.surfaceCreated(mSurfaceHolder);
917 }
918 }
919 surfaceChanged = true;
920 }
921 if (surfaceChanged) {
922 mSurfaceHolderCallback.surfaceChanged(mSurfaceHolder,
923 lp.format, mWidth, mHeight);
924 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
925 if (callbacks != null) {
926 for (SurfaceHolder.Callback c : callbacks) {
927 c.surfaceChanged(mSurfaceHolder, lp.format,
928 mWidth, mHeight);
929 }
930 }
931 }
932 mIsCreating = false;
933 } else if (hadSurface) {
934 mSurfaceHolder.ungetCallbacks();
935 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
936 mSurfaceHolderCallback.surfaceDestroyed(mSurfaceHolder);
937 if (callbacks != null) {
938 for (SurfaceHolder.Callback c : callbacks) {
939 c.surfaceDestroyed(mSurfaceHolder);
940 }
941 }
942 mSurfaceHolder.mSurfaceLock.lock();
943 // Make surface invalid.
944 //mSurfaceHolder.mSurface.copyFrom(mSurface);
945 mSurfaceHolder.mSurface = new Surface();
946 mSurfaceHolder.mSurfaceLock.unlock();
947 }
948 }
949
Romain Guy812ccbe2010-06-01 14:07:24 -0700950 if (hwIntialized) {
Romain Guyfb8b7632010-08-23 21:05:08 -0700951 mHwRenderer.setup(mWidth, mHeight);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800952 }
953
954 boolean focusChangedDueToTouchMode = ensureTouchModeLocally(
Romain Guy2d4cff62010-04-09 15:39:00 -0700955 (relayoutResult&WindowManagerImpl.RELAYOUT_IN_TOUCH_MODE) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800956 if (focusChangedDueToTouchMode || mWidth != host.mMeasuredWidth
957 || mHeight != host.mMeasuredHeight || contentInsetsChanged) {
958 childWidthMeasureSpec = getRootMeasureSpec(mWidth, lp.width);
959 childHeightMeasureSpec = getRootMeasureSpec(mHeight, lp.height);
960
961 if (DEBUG_LAYOUT) Log.v(TAG, "Ooops, something changed! mWidth="
962 + mWidth + " measuredWidth=" + host.mMeasuredWidth
963 + " mHeight=" + mHeight
964 + " measuredHeight" + host.mMeasuredHeight
965 + " coveredInsetsChanged=" + contentInsetsChanged);
Romain Guy8506ab42009-06-11 17:35:47 -0700966
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800967 // Ask host how big it wants to be
968 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
969
970 // Implementation of weights from WindowManager.LayoutParams
971 // We just grow the dimensions as needed and re-measure if
972 // needs be
973 int width = host.mMeasuredWidth;
974 int height = host.mMeasuredHeight;
975 boolean measureAgain = false;
976
977 if (lp.horizontalWeight > 0.0f) {
978 width += (int) ((mWidth - width) * lp.horizontalWeight);
979 childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(width,
980 MeasureSpec.EXACTLY);
981 measureAgain = true;
982 }
983 if (lp.verticalWeight > 0.0f) {
984 height += (int) ((mHeight - height) * lp.verticalWeight);
985 childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(height,
986 MeasureSpec.EXACTLY);
987 measureAgain = true;
988 }
989
990 if (measureAgain) {
991 if (DEBUG_LAYOUT) Log.v(TAG,
992 "And hey let's measure once more: width=" + width
993 + " height=" + height);
994 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
995 }
996
997 mLayoutRequested = true;
998 }
999 }
1000
1001 final boolean didLayout = mLayoutRequested;
1002 boolean triggerGlobalLayoutListener = didLayout
1003 || attachInfo.mRecomputeGlobalAttributes;
1004 if (didLayout) {
1005 mLayoutRequested = false;
1006 mScrollMayChange = true;
1007 if (DEBUG_ORIENTATION || DEBUG_LAYOUT) Log.v(
Jeff Brownc5ed5912010-07-14 18:48:53 -07001008 TAG, "Laying out " + host + " to (" +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001009 host.mMeasuredWidth + ", " + host.mMeasuredHeight + ")");
Romain Guy13922e02009-05-12 17:56:14 -07001010 long startTime = 0L;
Romain Guy5429e1d2010-09-07 12:38:00 -07001011 if (ViewDebug.DEBUG_PROFILE_LAYOUT) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001012 startTime = SystemClock.elapsedRealtime();
1013 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001014 host.layout(0, 0, host.mMeasuredWidth, host.mMeasuredHeight);
1015
Romain Guy13922e02009-05-12 17:56:14 -07001016 if (Config.DEBUG && ViewDebug.consistencyCheckEnabled) {
1017 if (!host.dispatchConsistencyCheck(ViewDebug.CONSISTENCY_LAYOUT)) {
1018 throw new IllegalStateException("The view hierarchy is an inconsistent state,"
1019 + "please refer to the logs with the tag "
1020 + ViewDebug.CONSISTENCY_LOG_TAG + " for more infomation.");
1021 }
1022 }
1023
Romain Guy5429e1d2010-09-07 12:38:00 -07001024 if (ViewDebug.DEBUG_PROFILE_LAYOUT) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001025 EventLog.writeEvent(60001, SystemClock.elapsedRealtime() - startTime);
1026 }
1027
1028 // By this point all views have been sized and positionned
1029 // We can compute the transparent area
1030
1031 if ((host.mPrivateFlags & View.REQUEST_TRANSPARENT_REGIONS) != 0) {
1032 // start out transparent
1033 // TODO: AVOID THAT CALL BY CACHING THE RESULT?
1034 host.getLocationInWindow(mTmpLocation);
1035 mTransparentRegion.set(mTmpLocation[0], mTmpLocation[1],
1036 mTmpLocation[0] + host.mRight - host.mLeft,
1037 mTmpLocation[1] + host.mBottom - host.mTop);
1038
1039 host.gatherTransparentRegion(mTransparentRegion);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001040 if (mTranslator != null) {
1041 mTranslator.translateRegionInWindowToScreen(mTransparentRegion);
1042 }
1043
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001044 if (!mTransparentRegion.equals(mPreviousTransparentRegion)) {
1045 mPreviousTransparentRegion.set(mTransparentRegion);
1046 // reconfigure window manager
1047 try {
1048 sWindowSession.setTransparentRegion(mWindow, mTransparentRegion);
1049 } catch (RemoteException e) {
1050 }
1051 }
1052 }
1053
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001054 if (DBG) {
1055 System.out.println("======================================");
1056 System.out.println("performTraversals -- after setFrame");
1057 host.debug();
1058 }
1059 }
1060
1061 if (triggerGlobalLayoutListener) {
1062 attachInfo.mRecomputeGlobalAttributes = false;
1063 attachInfo.mTreeObserver.dispatchOnGlobalLayout();
1064 }
1065
1066 if (computesInternalInsets) {
1067 ViewTreeObserver.InternalInsetsInfo insets = attachInfo.mGivenInternalInsets;
1068 final Rect givenContent = attachInfo.mGivenInternalInsets.contentInsets;
1069 final Rect givenVisible = attachInfo.mGivenInternalInsets.visibleInsets;
1070 givenContent.left = givenContent.top = givenContent.right
1071 = givenContent.bottom = givenVisible.left = givenVisible.top
1072 = givenVisible.right = givenVisible.bottom = 0;
1073 attachInfo.mTreeObserver.dispatchOnComputeInternalInsets(insets);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001074 Rect contentInsets = insets.contentInsets;
1075 Rect visibleInsets = insets.visibleInsets;
1076 if (mTranslator != null) {
1077 contentInsets = mTranslator.getTranslatedContentInsets(contentInsets);
1078 visibleInsets = mTranslator.getTranslatedVisbileInsets(visibleInsets);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001079 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001080 if (insetsPending || !mLastGivenInsets.equals(insets)) {
1081 mLastGivenInsets.set(insets);
1082 try {
1083 sWindowSession.setInsets(mWindow, insets.mTouchableInsets,
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001084 contentInsets, visibleInsets);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001085 } catch (RemoteException e) {
1086 }
1087 }
1088 }
Romain Guy8506ab42009-06-11 17:35:47 -07001089
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001090 if (mFirst) {
1091 // handle first focus request
1092 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: mView.hasFocus()="
1093 + mView.hasFocus());
1094 if (mView != null) {
1095 if (!mView.hasFocus()) {
1096 mView.requestFocus(View.FOCUS_FORWARD);
1097 mFocusedView = mRealFocusedView = mView.findFocus();
1098 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: requested focused view="
1099 + mFocusedView);
1100 } else {
1101 mRealFocusedView = mView.findFocus();
1102 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: existing focused view="
1103 + mRealFocusedView);
1104 }
1105 }
1106 }
1107
1108 mFirst = false;
1109 mWillDrawSoon = false;
1110 mNewSurfaceNeeded = false;
1111 mViewVisibility = viewVisibility;
1112
1113 if (mAttachInfo.mHasWindowFocus) {
1114 final boolean imTarget = WindowManager.LayoutParams
1115 .mayUseInputMethod(mWindowAttributes.flags);
1116 if (imTarget != mLastWasImTarget) {
1117 mLastWasImTarget = imTarget;
1118 InputMethodManager imm = InputMethodManager.peekInstance();
1119 if (imm != null && imTarget) {
1120 imm.startGettingWindowFocus(mView);
1121 imm.onWindowFocus(mView, mView.findFocus(),
1122 mWindowAttributes.softInputMode,
1123 !mHasHadWindowFocus, mWindowAttributes.flags);
1124 }
1125 }
1126 }
Romain Guy8506ab42009-06-11 17:35:47 -07001127
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001128 boolean cancelDraw = attachInfo.mTreeObserver.dispatchOnPreDraw();
1129
1130 if (!cancelDraw && !newSurface) {
1131 mFullRedrawNeeded = false;
1132 draw(fullRedrawNeeded);
1133
1134 if ((relayoutResult&WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0
1135 || mReportNextDraw) {
1136 if (LOCAL_LOGV) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001137 Log.v(TAG, "FINISHED DRAWING: " + mWindowAttributes.getTitle());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001138 }
1139 mReportNextDraw = false;
Dianne Hackbornd76b67c2010-07-13 17:48:30 -07001140 if (mSurfaceHolder != null && mSurface.isValid()) {
1141 mSurfaceHolderCallback.surfaceRedrawNeeded(mSurfaceHolder);
1142 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
1143 if (callbacks != null) {
1144 for (SurfaceHolder.Callback c : callbacks) {
1145 if (c instanceof SurfaceHolder.Callback2) {
1146 ((SurfaceHolder.Callback2)c).surfaceRedrawNeeded(
1147 mSurfaceHolder);
1148 }
1149 }
1150 }
1151 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001152 try {
1153 sWindowSession.finishDrawing(mWindow);
1154 } catch (RemoteException e) {
1155 }
1156 }
1157 } else {
1158 // We were supposed to report when we are done drawing. Since we canceled the
1159 // draw, remember it here.
1160 if ((relayoutResult&WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0) {
1161 mReportNextDraw = true;
1162 }
1163 if (fullRedrawNeeded) {
1164 mFullRedrawNeeded = true;
1165 }
1166 // Try again
1167 scheduleTraversals();
1168 }
1169 }
1170
1171 public void requestTransparentRegion(View child) {
1172 // the test below should not fail unless someone is messing with us
1173 checkThread();
1174 if (mView == child) {
1175 mView.mPrivateFlags |= View.REQUEST_TRANSPARENT_REGIONS;
1176 // Need to make sure we re-evaluate the window attributes next
1177 // time around, to ensure the window has the correct format.
1178 mWindowAttributesChanged = true;
1179 }
1180 }
1181
1182 /**
1183 * Figures out the measure spec for the root view in a window based on it's
1184 * layout params.
1185 *
1186 * @param windowSize
1187 * The available width or height of the window
1188 *
1189 * @param rootDimension
1190 * The layout params for one dimension (width or height) of the
1191 * window.
1192 *
1193 * @return The measure spec to use to measure the root view.
1194 */
1195 private int getRootMeasureSpec(int windowSize, int rootDimension) {
1196 int measureSpec;
1197 switch (rootDimension) {
1198
Romain Guy980a9382010-01-08 15:06:28 -08001199 case ViewGroup.LayoutParams.MATCH_PARENT:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001200 // Window can't resize. Force root view to be windowSize.
1201 measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.EXACTLY);
1202 break;
1203 case ViewGroup.LayoutParams.WRAP_CONTENT:
1204 // Window can resize. Set max size for root view.
1205 measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.AT_MOST);
1206 break;
1207 default:
1208 // Window wants to be an exact size. Force root view to be that size.
1209 measureSpec = MeasureSpec.makeMeasureSpec(rootDimension, MeasureSpec.EXACTLY);
1210 break;
1211 }
1212 return measureSpec;
1213 }
1214
1215 private void draw(boolean fullRedrawNeeded) {
1216 Surface surface = mSurface;
1217 if (surface == null || !surface.isValid()) {
1218 return;
1219 }
1220
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001221 if (!sFirstDrawComplete) {
1222 synchronized (sFirstDrawHandlers) {
1223 sFirstDrawComplete = true;
Romain Guy812ccbe2010-06-01 14:07:24 -07001224 final int count = sFirstDrawHandlers.size();
1225 for (int i = 0; i< count; i++) {
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001226 post(sFirstDrawHandlers.get(i));
1227 }
1228 }
1229 }
1230
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001231 scrollToRectOrFocus(null, false);
1232
1233 if (mAttachInfo.mViewScrollChanged) {
1234 mAttachInfo.mViewScrollChanged = false;
1235 mAttachInfo.mTreeObserver.dispatchOnScrollChanged();
1236 }
Romain Guy8506ab42009-06-11 17:35:47 -07001237
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001238 int yoff;
Romain Guy5bcdff42009-05-14 21:27:18 -07001239 final boolean scrolling = mScroller != null && mScroller.computeScrollOffset();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001240 if (scrolling) {
1241 yoff = mScroller.getCurrY();
1242 } else {
1243 yoff = mScrollY;
1244 }
1245 if (mCurScrollY != yoff) {
1246 mCurScrollY = yoff;
1247 fullRedrawNeeded = true;
1248 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001249 float appScale = mAttachInfo.mApplicationScale;
1250 boolean scalingRequired = mAttachInfo.mScalingRequired;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001251
1252 Rect dirty = mDirty;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001253 if (mSurfaceHolder != null) {
1254 // The app owns the surface, we won't draw.
1255 dirty.setEmpty();
1256 return;
1257 }
1258
Romain Guy2d614592010-06-09 18:21:37 -07001259 if (mHwRenderer != null && mHwRenderer.isEnabled()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001260 if (!dirty.isEmpty()) {
Romain Guydbd77cd2010-07-09 10:36:05 -07001261 mHwRenderer.draw(mView, mAttachInfo, yoff);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001262 }
Romain Guy812ccbe2010-06-01 14:07:24 -07001263
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001264 if (scrolling) {
1265 mFullRedrawNeeded = true;
1266 scheduleTraversals();
1267 }
Romain Guy812ccbe2010-06-01 14:07:24 -07001268
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001269 return;
1270 }
1271
Romain Guy5bcdff42009-05-14 21:27:18 -07001272 if (fullRedrawNeeded) {
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001273 mAttachInfo.mIgnoreDirtyState = true;
Mitsuru Oshima61324e52009-07-21 15:40:36 -07001274 dirty.union(0, 0, (int) (mWidth * appScale + 0.5f), (int) (mHeight * appScale + 0.5f));
Romain Guy5bcdff42009-05-14 21:27:18 -07001275 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001276
1277 if (DEBUG_ORIENTATION || DEBUG_DRAW) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001278 Log.v(TAG, "Draw " + mView + "/"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001279 + mWindowAttributes.getTitle()
1280 + ": dirty={" + dirty.left + "," + dirty.top
1281 + "," + dirty.right + "," + dirty.bottom + "} surface="
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001282 + surface + " surface.isValid()=" + surface.isValid() + ", appScale:" +
1283 appScale + ", width=" + mWidth + ", height=" + mHeight);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001284 }
1285
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001286 if (!dirty.isEmpty() || mIsAnimating) {
1287 Canvas canvas;
1288 try {
1289 int left = dirty.left;
1290 int top = dirty.top;
1291 int right = dirty.right;
1292 int bottom = dirty.bottom;
1293 canvas = surface.lockCanvas(dirty);
Romain Guy5bcdff42009-05-14 21:27:18 -07001294
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001295 if (left != dirty.left || top != dirty.top || right != dirty.right ||
1296 bottom != dirty.bottom) {
1297 mAttachInfo.mIgnoreDirtyState = true;
1298 }
1299
1300 // TODO: Do this in native
1301 canvas.setDensity(mDensity);
1302 } catch (Surface.OutOfResourcesException e) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001303 Log.e(TAG, "OutOfResourcesException locking surface", e);
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001304 // TODO: we should ask the window manager to do something!
1305 // for now we just do nothing
1306 return;
1307 } catch (IllegalArgumentException e) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001308 Log.e(TAG, "IllegalArgumentException locking surface", e);
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001309 // TODO: we should ask the window manager to do something!
1310 // for now we just do nothing
1311 return;
Romain Guy5bcdff42009-05-14 21:27:18 -07001312 }
1313
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001314 try {
1315 if (!dirty.isEmpty() || mIsAnimating) {
1316 long startTime = 0L;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001317
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001318 if (DEBUG_ORIENTATION || DEBUG_DRAW) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001319 Log.v(TAG, "Surface " + surface + " drawing to bitmap w="
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001320 + canvas.getWidth() + ", h=" + canvas.getHeight());
1321 //canvas.drawARGB(255, 255, 0, 0);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001322 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001323
Romain Guy5429e1d2010-09-07 12:38:00 -07001324 if (ViewDebug.DEBUG_PROFILE_DRAWING) {
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001325 startTime = SystemClock.elapsedRealtime();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001326 }
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001327
1328 // If this bitmap's format includes an alpha channel, we
1329 // need to clear it before drawing so that the child will
1330 // properly re-composite its drawing on a transparent
1331 // background. This automatically respects the clip/dirty region
1332 // or
1333 // If we are applying an offset, we need to clear the area
1334 // where the offset doesn't appear to avoid having garbage
1335 // left in the blank areas.
1336 if (!canvas.isOpaque() || yoff != 0) {
1337 canvas.drawColor(0, PorterDuff.Mode.CLEAR);
1338 }
1339
1340 dirty.setEmpty();
1341 mIsAnimating = false;
1342 mAttachInfo.mDrawingTime = SystemClock.uptimeMillis();
1343 mView.mPrivateFlags |= View.DRAWN;
1344
1345 if (DEBUG_DRAW) {
1346 Context cxt = mView.getContext();
1347 Log.i(TAG, "Drawing: package:" + cxt.getPackageName() +
1348 ", metrics=" + cxt.getResources().getDisplayMetrics() +
1349 ", compatibilityInfo=" + cxt.getResources().getCompatibilityInfo());
1350 }
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001351 try {
1352 canvas.translate(0, -yoff);
1353 if (mTranslator != null) {
1354 mTranslator.translateCanvas(canvas);
1355 }
1356 canvas.setScreenDensity(scalingRequired
1357 ? DisplayMetrics.DENSITY_DEVICE : 0);
1358 mView.draw(canvas);
1359 } finally {
1360 mAttachInfo.mIgnoreDirtyState = false;
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001361 }
1362
1363 if (Config.DEBUG && ViewDebug.consistencyCheckEnabled) {
1364 mView.dispatchConsistencyCheck(ViewDebug.CONSISTENCY_DRAWING);
1365 }
1366
Romain Guy5429e1d2010-09-07 12:38:00 -07001367 if (SHOW_FPS || ViewDebug.DEBUG_SHOW_FPS) {
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001368 int now = (int)SystemClock.elapsedRealtime();
1369 if (sDrawTime != 0) {
1370 nativeShowFPS(canvas, now - sDrawTime);
1371 }
1372 sDrawTime = now;
1373 }
1374
Romain Guy5429e1d2010-09-07 12:38:00 -07001375 if (ViewDebug.DEBUG_PROFILE_DRAWING) {
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001376 EventLog.writeEvent(60000, SystemClock.elapsedRealtime() - startTime);
1377 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001378 }
1379
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001380 } finally {
1381 surface.unlockCanvasAndPost(canvas);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001382 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001383 }
1384
1385 if (LOCAL_LOGV) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001386 Log.v(TAG, "Surface " + surface + " unlockCanvasAndPost");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001387 }
Romain Guy8506ab42009-06-11 17:35:47 -07001388
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001389 if (scrolling) {
1390 mFullRedrawNeeded = true;
1391 scheduleTraversals();
1392 }
1393 }
1394
1395 boolean scrollToRectOrFocus(Rect rectangle, boolean immediate) {
1396 final View.AttachInfo attachInfo = mAttachInfo;
1397 final Rect ci = attachInfo.mContentInsets;
1398 final Rect vi = attachInfo.mVisibleInsets;
1399 int scrollY = 0;
1400 boolean handled = false;
Romain Guy8506ab42009-06-11 17:35:47 -07001401
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001402 if (vi.left > ci.left || vi.top > ci.top
1403 || vi.right > ci.right || vi.bottom > ci.bottom) {
1404 // We'll assume that we aren't going to change the scroll
1405 // offset, since we want to avoid that unless it is actually
1406 // going to make the focus visible... otherwise we scroll
1407 // all over the place.
1408 scrollY = mScrollY;
1409 // We can be called for two different situations: during a draw,
1410 // to update the scroll position if the focus has changed (in which
1411 // case 'rectangle' is null), or in response to a
1412 // requestChildRectangleOnScreen() call (in which case 'rectangle'
1413 // is non-null and we just want to scroll to whatever that
1414 // rectangle is).
1415 View focus = mRealFocusedView;
Romain Guye8b16522009-07-14 13:06:42 -07001416
1417 // When in touch mode, focus points to the previously focused view,
1418 // which may have been removed from the view hierarchy. The following
Joe Onoratob71193b2009-11-24 18:34:42 -05001419 // line checks whether the view is still in our hierarchy.
1420 if (focus == null || focus.mAttachInfo != mAttachInfo) {
Romain Guye8b16522009-07-14 13:06:42 -07001421 mRealFocusedView = null;
1422 return false;
1423 }
1424
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001425 if (focus != mLastScrolledFocus) {
1426 // If the focus has changed, then ignore any requests to scroll
1427 // to a rectangle; first we want to make sure the entire focus
1428 // view is visible.
1429 rectangle = null;
1430 }
1431 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Eval scroll: focus=" + focus
1432 + " rectangle=" + rectangle + " ci=" + ci
1433 + " vi=" + vi);
1434 if (focus == mLastScrolledFocus && !mScrollMayChange
1435 && rectangle == null) {
1436 // Optimization: if the focus hasn't changed since last
1437 // time, and no layout has happened, then just leave things
1438 // as they are.
1439 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Keeping scroll y="
1440 + mScrollY + " vi=" + vi.toShortString());
1441 } else if (focus != null) {
1442 // We need to determine if the currently focused view is
1443 // within the visible part of the window and, if not, apply
1444 // a pan so it can be seen.
1445 mLastScrolledFocus = focus;
1446 mScrollMayChange = false;
1447 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Need to scroll?");
1448 // Try to find the rectangle from the focus view.
1449 if (focus.getGlobalVisibleRect(mVisRect, null)) {
1450 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Root w="
1451 + mView.getWidth() + " h=" + mView.getHeight()
1452 + " ci=" + ci.toShortString()
1453 + " vi=" + vi.toShortString());
1454 if (rectangle == null) {
1455 focus.getFocusedRect(mTempRect);
1456 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Focus " + focus
1457 + ": focusRect=" + mTempRect.toShortString());
Dianne Hackborn1c6a8942010-03-23 16:34:20 -07001458 if (mView instanceof ViewGroup) {
1459 ((ViewGroup) mView).offsetDescendantRectToMyCoords(
1460 focus, mTempRect);
1461 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001462 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1463 "Focus in window: focusRect="
1464 + mTempRect.toShortString()
1465 + " visRect=" + mVisRect.toShortString());
1466 } else {
1467 mTempRect.set(rectangle);
1468 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1469 "Request scroll to rect: "
1470 + mTempRect.toShortString()
1471 + " visRect=" + mVisRect.toShortString());
1472 }
1473 if (mTempRect.intersect(mVisRect)) {
1474 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1475 "Focus window visible rect: "
1476 + mTempRect.toShortString());
1477 if (mTempRect.height() >
1478 (mView.getHeight()-vi.top-vi.bottom)) {
1479 // If the focus simply is not going to fit, then
1480 // best is probably just to leave things as-is.
1481 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1482 "Too tall; leaving scrollY=" + scrollY);
1483 } else if ((mTempRect.top-scrollY) < vi.top) {
1484 scrollY -= vi.top - (mTempRect.top-scrollY);
1485 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1486 "Top covered; scrollY=" + scrollY);
1487 } else if ((mTempRect.bottom-scrollY)
1488 > (mView.getHeight()-vi.bottom)) {
1489 scrollY += (mTempRect.bottom-scrollY)
1490 - (mView.getHeight()-vi.bottom);
1491 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1492 "Bottom covered; scrollY=" + scrollY);
1493 }
1494 handled = true;
1495 }
1496 }
1497 }
1498 }
Romain Guy8506ab42009-06-11 17:35:47 -07001499
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001500 if (scrollY != mScrollY) {
1501 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Pan scroll changed: old="
1502 + mScrollY + " , new=" + scrollY);
1503 if (!immediate) {
1504 if (mScroller == null) {
1505 mScroller = new Scroller(mView.getContext());
1506 }
1507 mScroller.startScroll(0, mScrollY, 0, scrollY-mScrollY);
1508 } else if (mScroller != null) {
1509 mScroller.abortAnimation();
1510 }
1511 mScrollY = scrollY;
1512 }
Romain Guy8506ab42009-06-11 17:35:47 -07001513
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001514 return handled;
1515 }
Romain Guy8506ab42009-06-11 17:35:47 -07001516
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001517 public void requestChildFocus(View child, View focused) {
1518 checkThread();
1519 if (mFocusedView != focused) {
1520 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(mFocusedView, focused);
1521 scheduleTraversals();
1522 }
1523 mFocusedView = mRealFocusedView = focused;
1524 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Request child focus: focus now "
1525 + mFocusedView);
1526 }
1527
1528 public void clearChildFocus(View child) {
1529 checkThread();
1530
1531 View oldFocus = mFocusedView;
1532
1533 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Clearing child focus");
1534 mFocusedView = mRealFocusedView = null;
1535 if (mView != null && !mView.hasFocus()) {
1536 // If a view gets the focus, the listener will be invoked from requestChildFocus()
1537 if (!mView.requestFocus(View.FOCUS_FORWARD)) {
1538 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
1539 }
1540 } else if (oldFocus != null) {
1541 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
1542 }
1543 }
1544
1545
1546 public void focusableViewAvailable(View v) {
1547 checkThread();
1548
1549 if (mView != null && !mView.hasFocus()) {
1550 v.requestFocus();
1551 } else {
1552 // the one case where will transfer focus away from the current one
1553 // is if the current view is a view group that prefers to give focus
1554 // to its children first AND the view is a descendant of it.
1555 mFocusedView = mView.findFocus();
1556 boolean descendantsHaveDibsOnFocus =
1557 (mFocusedView instanceof ViewGroup) &&
1558 (((ViewGroup) mFocusedView).getDescendantFocusability() ==
1559 ViewGroup.FOCUS_AFTER_DESCENDANTS);
1560 if (descendantsHaveDibsOnFocus && isViewDescendantOf(v, mFocusedView)) {
1561 // If a view gets the focus, the listener will be invoked from requestChildFocus()
1562 v.requestFocus();
1563 }
1564 }
1565 }
1566
1567 public void recomputeViewAttributes(View child) {
1568 checkThread();
1569 if (mView == child) {
1570 mAttachInfo.mRecomputeGlobalAttributes = true;
1571 if (!mWillDrawSoon) {
1572 scheduleTraversals();
1573 }
1574 }
1575 }
1576
1577 void dispatchDetachedFromWindow() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001578 if (mView != null) {
1579 mView.dispatchDetachedFromWindow();
1580 }
1581
1582 mView = null;
1583 mAttachInfo.mRootView = null;
Mathias Agopian5583dc62009-07-09 16:28:11 -07001584 mAttachInfo.mSurface = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001585
Romain Guy4caa4ed2010-08-25 14:46:24 -07001586 if (mHwRenderer != null) {
1587 mHwRenderer.destroy(true);
1588 mHwRenderer = null;
1589 }
1590
Dianne Hackborn0586a1b2009-09-06 21:08:27 -07001591 mSurface.release();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001592
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001593 if (mInputChannel != null) {
1594 if (mInputQueueCallback != null) {
1595 mInputQueueCallback.onInputQueueDestroyed(mInputQueue);
1596 mInputQueueCallback = null;
1597 } else {
1598 InputQueue.unregisterInputChannel(mInputChannel);
Jeff Brown46b9ac02010-04-22 18:58:52 -07001599 }
1600 }
1601
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001602 try {
1603 sWindowSession.remove(mWindow);
1604 } catch (RemoteException e) {
1605 }
Jeff Brown349703e2010-06-22 01:27:15 -07001606
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001607 // Dispose the input channel after removing the window so the Window Manager
1608 // doesn't interpret the input channel being closed as an abnormal termination.
1609 if (mInputChannel != null) {
1610 mInputChannel.dispose();
1611 mInputChannel = null;
Jeff Brown349703e2010-06-22 01:27:15 -07001612 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001613 }
Romain Guy8506ab42009-06-11 17:35:47 -07001614
Dianne Hackborn694f79b2010-03-17 19:44:59 -07001615 void updateConfiguration(Configuration config, boolean force) {
1616 if (DEBUG_CONFIGURATION) Log.v(TAG,
1617 "Applying new config to window "
1618 + mWindowAttributes.getTitle()
1619 + ": " + config);
1620 synchronized (sConfigCallbacks) {
1621 for (int i=sConfigCallbacks.size()-1; i>=0; i--) {
1622 sConfigCallbacks.get(i).onConfigurationChanged(config);
1623 }
1624 }
1625 if (mView != null) {
1626 // At this point the resources have been updated to
1627 // have the most recent config, whatever that is. Use
1628 // the on in them which may be newer.
1629 if (mView != null) {
1630 config = mView.getResources().getConfiguration();
1631 }
1632 if (force || mLastConfiguration.diff(config) != 0) {
1633 mLastConfiguration.setTo(config);
1634 mView.dispatchConfigurationChanged(config);
1635 }
1636 }
1637 }
1638
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001639 /**
1640 * Return true if child is an ancestor of parent, (or equal to the parent).
1641 */
1642 private static boolean isViewDescendantOf(View child, View parent) {
1643 if (child == parent) {
1644 return true;
1645 }
1646
1647 final ViewParent theParent = child.getParent();
1648 return (theParent instanceof ViewGroup) && isViewDescendantOf((View) theParent, parent);
1649 }
1650
Romain Guycdb86672010-03-18 18:54:50 -07001651 private static void forceLayout(View view) {
1652 view.forceLayout();
1653 if (view instanceof ViewGroup) {
1654 ViewGroup group = (ViewGroup) view;
1655 final int count = group.getChildCount();
1656 for (int i = 0; i < count; i++) {
1657 forceLayout(group.getChildAt(i));
1658 }
1659 }
1660 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001661
1662 public final static int DO_TRAVERSAL = 1000;
1663 public final static int DIE = 1001;
1664 public final static int RESIZED = 1002;
1665 public final static int RESIZED_REPORT = 1003;
1666 public final static int WINDOW_FOCUS_CHANGED = 1004;
1667 public final static int DISPATCH_KEY = 1005;
1668 public final static int DISPATCH_POINTER = 1006;
1669 public final static int DISPATCH_TRACKBALL = 1007;
1670 public final static int DISPATCH_APP_VISIBILITY = 1008;
1671 public final static int DISPATCH_GET_NEW_SURFACE = 1009;
1672 public final static int FINISHED_EVENT = 1010;
1673 public final static int DISPATCH_KEY_FROM_IME = 1011;
1674 public final static int FINISH_INPUT_CONNECTION = 1012;
1675 public final static int CHECK_FOCUS = 1013;
Dianne Hackbornffa42482009-09-23 22:20:11 -07001676 public final static int CLOSE_SYSTEM_DIALOGS = 1014;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001677
1678 @Override
1679 public void handleMessage(Message msg) {
1680 switch (msg.what) {
1681 case View.AttachInfo.INVALIDATE_MSG:
1682 ((View) msg.obj).invalidate();
1683 break;
1684 case View.AttachInfo.INVALIDATE_RECT_MSG:
1685 final View.AttachInfo.InvalidateInfo info = (View.AttachInfo.InvalidateInfo) msg.obj;
1686 info.target.invalidate(info.left, info.top, info.right, info.bottom);
1687 info.release();
1688 break;
1689 case DO_TRAVERSAL:
1690 if (mProfile) {
1691 Debug.startMethodTracing("ViewRoot");
1692 }
1693
1694 performTraversals();
1695
1696 if (mProfile) {
1697 Debug.stopMethodTracing();
1698 mProfile = false;
1699 }
1700 break;
1701 case FINISHED_EVENT:
1702 handleFinishedEvent(msg.arg1, msg.arg2 != 0);
1703 break;
1704 case DISPATCH_KEY:
1705 if (LOCAL_LOGV) Log.v(
Jeff Brownc5ed5912010-07-14 18:48:53 -07001706 TAG, "Dispatching key "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001707 + msg.obj + " to " + mView);
Jeff Brown92ff1dd2010-08-11 16:16:06 -07001708 deliverKeyEvent((KeyEvent)msg.obj, msg.arg1 != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001709 break;
The Android Open Source Project10592532009-03-18 17:39:46 -07001710 case DISPATCH_POINTER: {
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001711 MotionEvent event = (MotionEvent) msg.obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001712 try {
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001713 deliverPointerEvent(event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001714 } finally {
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001715 event.recycle();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001716 if (LOCAL_LOGV || WATCH_POINTER) Log.i(TAG, "Done dispatching!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001717 }
The Android Open Source Project10592532009-03-18 17:39:46 -07001718 } break;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001719 case DISPATCH_TRACKBALL: {
1720 MotionEvent event = (MotionEvent) msg.obj;
1721 try {
1722 deliverTrackballEvent(event);
1723 } finally {
1724 event.recycle();
1725 }
1726 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001727 case DISPATCH_APP_VISIBILITY:
1728 handleAppVisibility(msg.arg1 != 0);
1729 break;
1730 case DISPATCH_GET_NEW_SURFACE:
1731 handleGetNewSurface();
1732 break;
1733 case RESIZED:
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001734 ResizedInfo ri = (ResizedInfo)msg.obj;
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001735
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001736 if (mWinFrame.width() == msg.arg1 && mWinFrame.height() == msg.arg2
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001737 && mPendingContentInsets.equals(ri.coveredInsets)
Dianne Hackbornd49258f2010-03-26 00:44:29 -07001738 && mPendingVisibleInsets.equals(ri.visibleInsets)
1739 && ((ResizedInfo)msg.obj).newConfig == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001740 break;
1741 }
1742 // fall through...
1743 case RESIZED_REPORT:
1744 if (mAdded) {
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001745 Configuration config = ((ResizedInfo)msg.obj).newConfig;
1746 if (config != null) {
Dianne Hackborn694f79b2010-03-17 19:44:59 -07001747 updateConfiguration(config, false);
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001748 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001749 mWinFrame.left = 0;
1750 mWinFrame.right = msg.arg1;
1751 mWinFrame.top = 0;
1752 mWinFrame.bottom = msg.arg2;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001753 mPendingContentInsets.set(((ResizedInfo)msg.obj).coveredInsets);
1754 mPendingVisibleInsets.set(((ResizedInfo)msg.obj).visibleInsets);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001755 if (msg.what == RESIZED_REPORT) {
1756 mReportNextDraw = true;
1757 }
Romain Guycdb86672010-03-18 18:54:50 -07001758
1759 if (mView != null) {
1760 forceLayout(mView);
1761 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001762 requestLayout();
1763 }
1764 break;
1765 case WINDOW_FOCUS_CHANGED: {
1766 if (mAdded) {
1767 boolean hasWindowFocus = msg.arg1 != 0;
1768 mAttachInfo.mHasWindowFocus = hasWindowFocus;
1769 if (hasWindowFocus) {
1770 boolean inTouchMode = msg.arg2 != 0;
Romain Guy2d4cff62010-04-09 15:39:00 -07001771 ensureTouchModeLocally(inTouchMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001772
Romain Guy812ccbe2010-06-01 14:07:24 -07001773 if (mHwRenderer != null) {
Romain Guy2d614592010-06-09 18:21:37 -07001774 mHwRenderer.initializeIfNeeded(mWidth, mHeight, mAttachInfo, mHolder);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001775 }
1776 }
Romain Guy8506ab42009-06-11 17:35:47 -07001777
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001778 mLastWasImTarget = WindowManager.LayoutParams
1779 .mayUseInputMethod(mWindowAttributes.flags);
Romain Guy8506ab42009-06-11 17:35:47 -07001780
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001781 InputMethodManager imm = InputMethodManager.peekInstance();
1782 if (mView != null) {
1783 if (hasWindowFocus && imm != null && mLastWasImTarget) {
1784 imm.startGettingWindowFocus(mView);
1785 }
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07001786 mAttachInfo.mKeyDispatchState.reset();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001787 mView.dispatchWindowFocusChanged(hasWindowFocus);
1788 }
svetoslavganov75986cf2009-05-14 22:28:01 -07001789
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001790 // Note: must be done after the focus change callbacks,
1791 // so all of the view state is set up correctly.
1792 if (hasWindowFocus) {
1793 if (imm != null && mLastWasImTarget) {
1794 imm.onWindowFocus(mView, mView.findFocus(),
1795 mWindowAttributes.softInputMode,
1796 !mHasHadWindowFocus, mWindowAttributes.flags);
1797 }
1798 // Clear the forward bit. We can just do this directly, since
1799 // the window manager doesn't care about it.
1800 mWindowAttributes.softInputMode &=
1801 ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
1802 ((WindowManager.LayoutParams)mView.getLayoutParams())
1803 .softInputMode &=
1804 ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
1805 mHasHadWindowFocus = true;
1806 }
svetoslavganov75986cf2009-05-14 22:28:01 -07001807
1808 if (hasWindowFocus && mView != null) {
1809 sendAccessibilityEvents();
1810 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001811 }
1812 } break;
1813 case DIE:
Dianne Hackborn94d69142009-09-28 22:14:42 -07001814 doDie();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001815 break;
The Android Open Source Project10592532009-03-18 17:39:46 -07001816 case DISPATCH_KEY_FROM_IME: {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001817 if (LOCAL_LOGV) Log.v(
Jeff Brownc5ed5912010-07-14 18:48:53 -07001818 TAG, "Dispatching key "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001819 + msg.obj + " from IME to " + mView);
The Android Open Source Project10592532009-03-18 17:39:46 -07001820 KeyEvent event = (KeyEvent)msg.obj;
1821 if ((event.getFlags()&KeyEvent.FLAG_FROM_SYSTEM) != 0) {
1822 // The IME is trying to say this event is from the
1823 // system! Bad bad bad!
Romain Guy812ccbe2010-06-01 14:07:24 -07001824 event = KeyEvent.changeFlags(event, event.getFlags() & ~KeyEvent.FLAG_FROM_SYSTEM);
The Android Open Source Project10592532009-03-18 17:39:46 -07001825 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001826 deliverKeyEventToViewHierarchy((KeyEvent)msg.obj, false);
The Android Open Source Project10592532009-03-18 17:39:46 -07001827 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001828 case FINISH_INPUT_CONNECTION: {
1829 InputMethodManager imm = InputMethodManager.peekInstance();
1830 if (imm != null) {
1831 imm.reportFinishInputConnection((InputConnection)msg.obj);
1832 }
1833 } break;
1834 case CHECK_FOCUS: {
1835 InputMethodManager imm = InputMethodManager.peekInstance();
1836 if (imm != null) {
1837 imm.checkFocus();
1838 }
1839 } break;
Dianne Hackbornffa42482009-09-23 22:20:11 -07001840 case CLOSE_SYSTEM_DIALOGS: {
1841 if (mView != null) {
1842 mView.onCloseSystemDialogs((String)msg.obj);
1843 }
1844 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001845 }
1846 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07001847
1848 private void finishKeyEvent(KeyEvent event) {
Jeff Brown92ff1dd2010-08-11 16:16:06 -07001849 if (LOCAL_LOGV) Log.v(TAG, "Telling window manager key is finished");
1850
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001851 if (mFinishedCallback != null) {
1852 mFinishedCallback.run();
1853 mFinishedCallback = null;
Jeff Brown92ff1dd2010-08-11 16:16:06 -07001854 } else {
1855 Slog.w(TAG, "Attempted to tell the input queue that the current key event "
1856 + "is finished but there is no key event actually in progress.");
Jeff Brown46b9ac02010-04-22 18:58:52 -07001857 }
1858 }
1859
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001860 /**
1861 * Something in the current window tells us we need to change the touch mode. For
1862 * example, we are not in touch mode, and the user touches the screen.
1863 *
1864 * If the touch mode has changed, tell the window manager, and handle it locally.
1865 *
1866 * @param inTouchMode Whether we want to be in touch mode.
1867 * @return True if the touch mode changed and focus changed was changed as a result
1868 */
1869 boolean ensureTouchMode(boolean inTouchMode) {
1870 if (DBG) Log.d("touchmode", "ensureTouchMode(" + inTouchMode + "), current "
1871 + "touch mode is " + mAttachInfo.mInTouchMode);
1872 if (mAttachInfo.mInTouchMode == inTouchMode) return false;
1873
1874 // tell the window manager
1875 try {
1876 sWindowSession.setInTouchMode(inTouchMode);
1877 } catch (RemoteException e) {
1878 throw new RuntimeException(e);
1879 }
1880
1881 // handle the change
Romain Guy2d4cff62010-04-09 15:39:00 -07001882 return ensureTouchModeLocally(inTouchMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001883 }
1884
1885 /**
1886 * Ensure that the touch mode for this window is set, and if it is changing,
1887 * take the appropriate action.
1888 * @param inTouchMode Whether we want to be in touch mode.
1889 * @return True if the touch mode changed and focus changed was changed as a result
1890 */
Romain Guy2d4cff62010-04-09 15:39:00 -07001891 private boolean ensureTouchModeLocally(boolean inTouchMode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001892 if (DBG) Log.d("touchmode", "ensureTouchModeLocally(" + inTouchMode + "), current "
1893 + "touch mode is " + mAttachInfo.mInTouchMode);
1894
1895 if (mAttachInfo.mInTouchMode == inTouchMode) return false;
1896
1897 mAttachInfo.mInTouchMode = inTouchMode;
1898 mAttachInfo.mTreeObserver.dispatchOnTouchModeChanged(inTouchMode);
1899
Romain Guy2d4cff62010-04-09 15:39:00 -07001900 return (inTouchMode) ? enterTouchMode() : leaveTouchMode();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001901 }
1902
1903 private boolean enterTouchMode() {
1904 if (mView != null) {
1905 if (mView.hasFocus()) {
1906 // note: not relying on mFocusedView here because this could
1907 // be when the window is first being added, and mFocused isn't
1908 // set yet.
1909 final View focused = mView.findFocus();
1910 if (focused != null && !focused.isFocusableInTouchMode()) {
1911
1912 final ViewGroup ancestorToTakeFocus =
1913 findAncestorToTakeFocusInTouchMode(focused);
1914 if (ancestorToTakeFocus != null) {
1915 // there is an ancestor that wants focus after its descendants that
1916 // is focusable in touch mode.. give it focus
1917 return ancestorToTakeFocus.requestFocus();
1918 } else {
1919 // nothing appropriate to have focus in touch mode, clear it out
1920 mView.unFocus();
1921 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(focused, null);
1922 mFocusedView = null;
1923 return true;
1924 }
1925 }
1926 }
1927 }
1928 return false;
1929 }
1930
1931
1932 /**
1933 * Find an ancestor of focused that wants focus after its descendants and is
1934 * focusable in touch mode.
1935 * @param focused The currently focused view.
1936 * @return An appropriate view, or null if no such view exists.
1937 */
1938 private ViewGroup findAncestorToTakeFocusInTouchMode(View focused) {
1939 ViewParent parent = focused.getParent();
1940 while (parent instanceof ViewGroup) {
1941 final ViewGroup vgParent = (ViewGroup) parent;
1942 if (vgParent.getDescendantFocusability() == ViewGroup.FOCUS_AFTER_DESCENDANTS
1943 && vgParent.isFocusableInTouchMode()) {
1944 return vgParent;
1945 }
1946 if (vgParent.isRootNamespace()) {
1947 return null;
1948 } else {
1949 parent = vgParent.getParent();
1950 }
1951 }
1952 return null;
1953 }
1954
1955 private boolean leaveTouchMode() {
1956 if (mView != null) {
1957 if (mView.hasFocus()) {
1958 // i learned the hard way to not trust mFocusedView :)
1959 mFocusedView = mView.findFocus();
1960 if (!(mFocusedView instanceof ViewGroup)) {
1961 // some view has focus, let it keep it
1962 return false;
1963 } else if (((ViewGroup)mFocusedView).getDescendantFocusability() !=
1964 ViewGroup.FOCUS_AFTER_DESCENDANTS) {
1965 // some view group has focus, and doesn't prefer its children
1966 // over itself for focus, so let them keep it.
1967 return false;
1968 }
1969 }
1970
1971 // find the best view to give focus to in this brave new non-touch-mode
1972 // world
1973 final View focused = focusSearch(null, View.FOCUS_DOWN);
1974 if (focused != null) {
1975 return focused.requestFocus(View.FOCUS_DOWN);
1976 }
1977 }
1978 return false;
1979 }
1980
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001981 private void deliverPointerEvent(MotionEvent event) {
1982 if (mTranslator != null) {
1983 mTranslator.translateEventInScreenToAppWindow(event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001984 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001985
1986 boolean handled;
1987 if (mView != null && mAdded) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001988
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001989 // enter touch mode on the down
1990 boolean isDown = event.getAction() == MotionEvent.ACTION_DOWN;
1991 if (isDown) {
1992 ensureTouchMode(true);
1993 }
1994 if(Config.LOGV) {
1995 captureMotionLog("captureDispatchPointer", event);
1996 }
1997 if (mCurScrollY != 0) {
1998 event.offsetLocation(0, mCurScrollY);
1999 }
2000 if (MEASURE_LATENCY) {
2001 lt.sample("A Dispatching TouchEvents", System.nanoTime() - event.getEventTimeNano());
2002 }
2003 handled = mView.dispatchTouchEvent(event);
2004 if (MEASURE_LATENCY) {
2005 lt.sample("B Dispatched TouchEvents ", System.nanoTime() - event.getEventTimeNano());
2006 }
2007 if (!handled && isDown) {
2008 int edgeSlop = mViewConfiguration.getScaledEdgeSlop();
2009
2010 final int edgeFlags = event.getEdgeFlags();
2011 int direction = View.FOCUS_UP;
2012 int x = (int)event.getX();
2013 int y = (int)event.getY();
2014 final int[] deltas = new int[2];
2015
2016 if ((edgeFlags & MotionEvent.EDGE_TOP) != 0) {
2017 direction = View.FOCUS_DOWN;
2018 if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
2019 deltas[0] = edgeSlop;
2020 x += edgeSlop;
2021 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
2022 deltas[0] = -edgeSlop;
2023 x -= edgeSlop;
2024 }
2025 } else if ((edgeFlags & MotionEvent.EDGE_BOTTOM) != 0) {
2026 direction = View.FOCUS_UP;
2027 if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
2028 deltas[0] = edgeSlop;
2029 x += edgeSlop;
2030 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
2031 deltas[0] = -edgeSlop;
2032 x -= edgeSlop;
2033 }
2034 } else if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
2035 direction = View.FOCUS_RIGHT;
2036 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
2037 direction = View.FOCUS_LEFT;
2038 }
2039
2040 if (edgeFlags != 0 && mView instanceof ViewGroup) {
2041 View nearest = FocusFinder.getInstance().findNearestTouchable(
2042 ((ViewGroup) mView), x, y, direction, deltas);
2043 if (nearest != null) {
2044 event.offsetLocation(deltas[0], deltas[1]);
2045 event.setEdgeFlags(0);
2046 mView.dispatchTouchEvent(event);
2047 }
2048 }
2049 }
2050 }
2051 }
2052
2053 private void deliverTrackballEvent(MotionEvent event) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002054 if (DEBUG_TRACKBALL) Log.v(TAG, "Motion event:" + event);
2055
2056 boolean handled = false;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002057 if (mView != null && mAdded) {
2058 handled = mView.dispatchTrackballEvent(event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002059 if (handled) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002060 // If we reach this, we delivered a trackball event to mView and
2061 // mView consumed it. Because we will not translate the trackball
2062 // event into a key event, touch mode will not exit, so we exit
2063 // touch mode here.
2064 ensureTouchMode(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002065 return;
2066 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002067
2068 // Otherwise we could do something here, like changing the focus
2069 // or something?
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002070 }
2071
2072 final TrackballAxis x = mTrackballAxisX;
2073 final TrackballAxis y = mTrackballAxisY;
2074
2075 long curTime = SystemClock.uptimeMillis();
2076 if ((mLastTrackballTime+MAX_TRACKBALL_DELAY) < curTime) {
2077 // It has been too long since the last movement,
2078 // so restart at the beginning.
2079 x.reset(0);
2080 y.reset(0);
2081 mLastTrackballTime = curTime;
2082 }
2083
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002084 final int action = event.getAction();
2085 final int metastate = event.getMetaState();
2086 switch (action) {
2087 case MotionEvent.ACTION_DOWN:
2088 x.reset(2);
2089 y.reset(2);
2090 deliverKeyEvent(new KeyEvent(curTime, curTime,
2091 KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_CENTER,
2092 0, metastate), false);
2093 break;
2094 case MotionEvent.ACTION_UP:
2095 x.reset(2);
2096 y.reset(2);
2097 deliverKeyEvent(new KeyEvent(curTime, curTime,
2098 KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_CENTER,
2099 0, metastate), false);
2100 break;
2101 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002102
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002103 if (DEBUG_TRACKBALL) Log.v(TAG, "TB X=" + x.position + " step="
2104 + x.step + " dir=" + x.dir + " acc=" + x.acceleration
2105 + " move=" + event.getX()
2106 + " / Y=" + y.position + " step="
2107 + y.step + " dir=" + y.dir + " acc=" + y.acceleration
2108 + " move=" + event.getY());
2109 final float xOff = x.collect(event.getX(), event.getEventTime(), "X");
2110 final float yOff = y.collect(event.getY(), event.getEventTime(), "Y");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002111
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002112 // Generate DPAD events based on the trackball movement.
2113 // We pick the axis that has moved the most as the direction of
2114 // the DPAD. When we generate DPAD events for one axis, then the
2115 // other axis is reset -- we don't want to perform DPAD jumps due
2116 // to slight movements in the trackball when making major movements
2117 // along the other axis.
2118 int keycode = 0;
2119 int movement = 0;
2120 float accel = 1;
2121 if (xOff > yOff) {
2122 movement = x.generate((2/event.getXPrecision()));
2123 if (movement != 0) {
2124 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_RIGHT
2125 : KeyEvent.KEYCODE_DPAD_LEFT;
2126 accel = x.acceleration;
2127 y.reset(2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002128 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002129 } else if (yOff > 0) {
2130 movement = y.generate((2/event.getYPrecision()));
2131 if (movement != 0) {
2132 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_DOWN
2133 : KeyEvent.KEYCODE_DPAD_UP;
2134 accel = y.acceleration;
2135 x.reset(2);
2136 }
2137 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002138
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002139 if (keycode != 0) {
2140 if (movement < 0) movement = -movement;
2141 int accelMovement = (int)(movement * accel);
2142 if (DEBUG_TRACKBALL) Log.v(TAG, "Move: movement=" + movement
2143 + " accelMovement=" + accelMovement
2144 + " accel=" + accel);
2145 if (accelMovement > movement) {
2146 if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: "
2147 + keycode);
2148 movement--;
2149 deliverKeyEvent(new KeyEvent(curTime, curTime,
2150 KeyEvent.ACTION_MULTIPLE, keycode,
2151 accelMovement-movement, metastate), false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002152 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002153 while (movement > 0) {
2154 if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: "
2155 + keycode);
2156 movement--;
2157 curTime = SystemClock.uptimeMillis();
2158 deliverKeyEvent(new KeyEvent(curTime, curTime,
2159 KeyEvent.ACTION_DOWN, keycode, 0, event.getMetaState()), false);
2160 deliverKeyEvent(new KeyEvent(curTime, curTime,
2161 KeyEvent.ACTION_UP, keycode, 0, metastate), false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002162 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002163 mLastTrackballTime = curTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002164 }
2165 }
2166
2167 /**
2168 * @param keyCode The key code
2169 * @return True if the key is directional.
2170 */
2171 static boolean isDirectional(int keyCode) {
2172 switch (keyCode) {
2173 case KeyEvent.KEYCODE_DPAD_LEFT:
2174 case KeyEvent.KEYCODE_DPAD_RIGHT:
2175 case KeyEvent.KEYCODE_DPAD_UP:
2176 case KeyEvent.KEYCODE_DPAD_DOWN:
2177 return true;
2178 }
2179 return false;
2180 }
2181
2182 /**
2183 * Returns true if this key is a keyboard key.
2184 * @param keyEvent The key event.
2185 * @return whether this key is a keyboard key.
2186 */
2187 private static boolean isKeyboardKey(KeyEvent keyEvent) {
2188 final int convertedKey = keyEvent.getUnicodeChar();
2189 return convertedKey > 0;
2190 }
2191
2192
2193
2194 /**
2195 * See if the key event means we should leave touch mode (and leave touch
2196 * mode if so).
2197 * @param event The key event.
2198 * @return Whether this key event should be consumed (meaning the act of
2199 * leaving touch mode alone is considered the event).
2200 */
2201 private boolean checkForLeavingTouchModeAndConsume(KeyEvent event) {
Adam Powell51a6bee2010-03-15 14:07:28 -07002202 final int action = event.getAction();
2203 if (action != KeyEvent.ACTION_DOWN && action != KeyEvent.ACTION_MULTIPLE) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002204 return false;
2205 }
2206 if ((event.getFlags()&KeyEvent.FLAG_KEEP_TOUCH_MODE) != 0) {
2207 return false;
2208 }
2209
2210 // only relevant if we are in touch mode
2211 if (!mAttachInfo.mInTouchMode) {
2212 return false;
2213 }
2214
2215 // if something like an edit text has focus and the user is typing,
2216 // leave touch mode
2217 //
2218 // note: the condition of not being a keyboard key is kind of a hacky
2219 // approximation of whether we think the focused view will want the
2220 // key; if we knew for sure whether the focused view would consume
2221 // the event, that would be better.
2222 if (isKeyboardKey(event) && mView != null && mView.hasFocus()) {
2223 mFocusedView = mView.findFocus();
2224 if ((mFocusedView instanceof ViewGroup)
2225 && ((ViewGroup) mFocusedView).getDescendantFocusability() ==
2226 ViewGroup.FOCUS_AFTER_DESCENDANTS) {
2227 // something has focus, but is holding it weakly as a container
2228 return false;
2229 }
2230 if (ensureTouchMode(false)) {
2231 throw new IllegalStateException("should not have changed focus "
2232 + "when leaving touch mode while a view has focus.");
2233 }
2234 return false;
2235 }
2236
2237 if (isDirectional(event.getKeyCode())) {
2238 // no view has focus, so we leave touch mode (and find something
2239 // to give focus to). the event is consumed if we were able to
2240 // find something to give focus to.
2241 return ensureTouchMode(false);
2242 }
2243 return false;
2244 }
2245
2246 /**
Romain Guy8506ab42009-06-11 17:35:47 -07002247 * log motion events
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002248 */
2249 private static void captureMotionLog(String subTag, MotionEvent ev) {
Romain Guy8506ab42009-06-11 17:35:47 -07002250 //check dynamic switch
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002251 if (ev == null ||
2252 SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_EVENT, 0) == 0) {
2253 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002254 }
Romain Guy8506ab42009-06-11 17:35:47 -07002255
2256 StringBuilder sb = new StringBuilder(subTag + ": ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002257 sb.append(ev.getDownTime()).append(',');
2258 sb.append(ev.getEventTime()).append(',');
2259 sb.append(ev.getAction()).append(',');
Romain Guy8506ab42009-06-11 17:35:47 -07002260 sb.append(ev.getX()).append(',');
2261 sb.append(ev.getY()).append(',');
2262 sb.append(ev.getPressure()).append(',');
2263 sb.append(ev.getSize()).append(',');
2264 sb.append(ev.getMetaState()).append(',');
2265 sb.append(ev.getXPrecision()).append(',');
2266 sb.append(ev.getYPrecision()).append(',');
2267 sb.append(ev.getDeviceId()).append(',');
2268 sb.append(ev.getEdgeFlags());
2269 Log.d(TAG, sb.toString());
2270 }
2271 /**
2272 * log motion events
2273 */
2274 private static void captureKeyLog(String subTag, KeyEvent ev) {
2275 //check dynamic switch
2276 if (ev == null ||
2277 SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_EVENT, 0) == 0) {
2278 return;
2279 }
2280 StringBuilder sb = new StringBuilder(subTag + ": ");
2281 sb.append(ev.getDownTime()).append(',');
2282 sb.append(ev.getEventTime()).append(',');
2283 sb.append(ev.getAction()).append(',');
2284 sb.append(ev.getKeyCode()).append(',');
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002285 sb.append(ev.getRepeatCount()).append(',');
2286 sb.append(ev.getMetaState()).append(',');
2287 sb.append(ev.getDeviceId()).append(',');
2288 sb.append(ev.getScanCode());
Romain Guy8506ab42009-06-11 17:35:47 -07002289 Log.d(TAG, sb.toString());
2290 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002291
2292 int enqueuePendingEvent(Object event, boolean sendDone) {
2293 int seq = mPendingEventSeq+1;
2294 if (seq < 0) seq = 0;
2295 mPendingEventSeq = seq;
2296 mPendingEvents.put(seq, event);
2297 return sendDone ? seq : -seq;
2298 }
2299
2300 Object retrievePendingEvent(int seq) {
2301 if (seq < 0) seq = -seq;
2302 Object event = mPendingEvents.get(seq);
2303 if (event != null) {
2304 mPendingEvents.remove(seq);
2305 }
2306 return event;
2307 }
Romain Guy8506ab42009-06-11 17:35:47 -07002308
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002309 private void deliverKeyEvent(KeyEvent event, boolean sendDone) {
2310 // If mView is null, we just consume the key event because it doesn't
2311 // make sense to do anything else with it.
Romain Guy812ccbe2010-06-01 14:07:24 -07002312 boolean handled = mView == null || mView.dispatchKeyEventPreIme(event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002313 if (handled) {
2314 if (sendDone) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002315 finishKeyEvent(event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002316 }
2317 return;
2318 }
2319 // If it is possible for this window to interact with the input
2320 // method window, then we want to first dispatch our key events
2321 // to the input method.
2322 if (mLastWasImTarget) {
2323 InputMethodManager imm = InputMethodManager.peekInstance();
2324 if (imm != null && mView != null) {
2325 int seq = enqueuePendingEvent(event, sendDone);
2326 if (DEBUG_IMF) Log.v(TAG, "Sending key event to IME: seq="
2327 + seq + " event=" + event);
2328 imm.dispatchKeyEvent(mView.getContext(), seq, event,
2329 mInputMethodCallback);
2330 return;
2331 }
2332 }
2333 deliverKeyEventToViewHierarchy(event, sendDone);
2334 }
2335
2336 void handleFinishedEvent(int seq, boolean handled) {
2337 final KeyEvent event = (KeyEvent)retrievePendingEvent(seq);
2338 if (DEBUG_IMF) Log.v(TAG, "IME finished event: seq=" + seq
2339 + " handled=" + handled + " event=" + event);
2340 if (event != null) {
2341 final boolean sendDone = seq >= 0;
2342 if (!handled) {
2343 deliverKeyEventToViewHierarchy(event, sendDone);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002344 } else if (sendDone) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002345 finishKeyEvent(event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002346 } else {
Jeff Brownc5ed5912010-07-14 18:48:53 -07002347 Log.w(TAG, "handleFinishedEvent(seq=" + seq
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002348 + " handled=" + handled + " ev=" + event
2349 + ") neither delivering nor finishing key");
2350 }
2351 }
2352 }
Romain Guy8506ab42009-06-11 17:35:47 -07002353
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002354 private void deliverKeyEventToViewHierarchy(KeyEvent event, boolean sendDone) {
2355 try {
2356 if (mView != null && mAdded) {
2357 final int action = event.getAction();
2358 boolean isDown = (action == KeyEvent.ACTION_DOWN);
2359
2360 if (checkForLeavingTouchModeAndConsume(event)) {
2361 return;
Romain Guy8506ab42009-06-11 17:35:47 -07002362 }
2363
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002364 if (Config.LOGV) {
2365 captureKeyLog("captureDispatchKeyEvent", event);
2366 }
2367 boolean keyHandled = mView.dispatchKeyEvent(event);
2368
2369 if (!keyHandled && isDown) {
2370 int direction = 0;
2371 switch (event.getKeyCode()) {
2372 case KeyEvent.KEYCODE_DPAD_LEFT:
2373 direction = View.FOCUS_LEFT;
2374 break;
2375 case KeyEvent.KEYCODE_DPAD_RIGHT:
2376 direction = View.FOCUS_RIGHT;
2377 break;
2378 case KeyEvent.KEYCODE_DPAD_UP:
2379 direction = View.FOCUS_UP;
2380 break;
2381 case KeyEvent.KEYCODE_DPAD_DOWN:
2382 direction = View.FOCUS_DOWN;
2383 break;
2384 }
2385
2386 if (direction != 0) {
2387
2388 View focused = mView != null ? mView.findFocus() : null;
2389 if (focused != null) {
2390 View v = focused.focusSearch(direction);
2391 boolean focusPassed = false;
2392 if (v != null && v != focused) {
2393 // do the math the get the interesting rect
2394 // of previous focused into the coord system of
2395 // newly focused view
2396 focused.getFocusedRect(mTempRect);
Dianne Hackborn1c6a8942010-03-23 16:34:20 -07002397 if (mView instanceof ViewGroup) {
2398 ((ViewGroup) mView).offsetDescendantRectToMyCoords(
2399 focused, mTempRect);
2400 ((ViewGroup) mView).offsetRectIntoDescendantCoords(
2401 v, mTempRect);
2402 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002403 focusPassed = v.requestFocus(direction, mTempRect);
2404 }
2405
2406 if (!focusPassed) {
2407 mView.dispatchUnhandledMove(focused, direction);
2408 } else {
2409 playSoundEffect(SoundEffectConstants.getContantForFocusDirection(direction));
2410 }
2411 }
2412 }
2413 }
2414 }
2415
2416 } finally {
2417 if (sendDone) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002418 finishKeyEvent(event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002419 }
2420 // Let the exception fall through -- the looper will catch
2421 // it and take care of the bad app for us.
2422 }
2423 }
2424
2425 private AudioManager getAudioManager() {
2426 if (mView == null) {
2427 throw new IllegalStateException("getAudioManager called when there is no mView");
2428 }
2429 if (mAudioManager == null) {
2430 mAudioManager = (AudioManager) mView.getContext().getSystemService(Context.AUDIO_SERVICE);
2431 }
2432 return mAudioManager;
2433 }
2434
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002435 private int relayoutWindow(WindowManager.LayoutParams params, int viewVisibility,
2436 boolean insetsPending) throws RemoteException {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002437
2438 float appScale = mAttachInfo.mApplicationScale;
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002439 boolean restore = false;
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002440 if (params != null && mTranslator != null) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07002441 restore = true;
2442 params.backup();
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002443 mTranslator.translateWindowLayout(params);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002444 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002445 if (params != null) {
2446 if (DBG) Log.d(TAG, "WindowLayout in layoutWindow:" + params);
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002447 }
Dianne Hackborn694f79b2010-03-17 19:44:59 -07002448 mPendingConfiguration.seq = 0;
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002449 int relayoutResult = sWindowSession.relayout(
2450 mWindow, params,
Mitsuru Oshima61324e52009-07-21 15:40:36 -07002451 (int) (mView.mMeasuredWidth * appScale + 0.5f),
2452 (int) (mView.mMeasuredHeight * appScale + 0.5f),
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002453 viewVisibility, insetsPending, mWinFrame,
Dianne Hackborn694f79b2010-03-17 19:44:59 -07002454 mPendingContentInsets, mPendingVisibleInsets,
2455 mPendingConfiguration, mSurface);
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002456 if (restore) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07002457 params.restore();
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002458 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002459
2460 if (mTranslator != null) {
2461 mTranslator.translateRectInScreenToAppWinFrame(mWinFrame);
2462 mTranslator.translateRectInScreenToAppWindow(mPendingContentInsets);
2463 mTranslator.translateRectInScreenToAppWindow(mPendingVisibleInsets);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002464 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002465 return relayoutResult;
2466 }
Romain Guy8506ab42009-06-11 17:35:47 -07002467
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002468 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002469 * {@inheritDoc}
2470 */
2471 public void playSoundEffect(int effectId) {
2472 checkThread();
2473
Jean-Michel Trivi13b18fd2010-05-05 09:18:15 -07002474 try {
2475 final AudioManager audioManager = getAudioManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002476
Jean-Michel Trivi13b18fd2010-05-05 09:18:15 -07002477 switch (effectId) {
2478 case SoundEffectConstants.CLICK:
2479 audioManager.playSoundEffect(AudioManager.FX_KEY_CLICK);
2480 return;
2481 case SoundEffectConstants.NAVIGATION_DOWN:
2482 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_DOWN);
2483 return;
2484 case SoundEffectConstants.NAVIGATION_LEFT:
2485 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_LEFT);
2486 return;
2487 case SoundEffectConstants.NAVIGATION_RIGHT:
2488 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_RIGHT);
2489 return;
2490 case SoundEffectConstants.NAVIGATION_UP:
2491 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_UP);
2492 return;
2493 default:
2494 throw new IllegalArgumentException("unknown effect id " + effectId +
2495 " not defined in " + SoundEffectConstants.class.getCanonicalName());
2496 }
2497 } catch (IllegalStateException e) {
2498 // Exception thrown by getAudioManager() when mView is null
2499 Log.e(TAG, "FATAL EXCEPTION when attempting to play sound effect: " + e);
2500 e.printStackTrace();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002501 }
2502 }
2503
2504 /**
2505 * {@inheritDoc}
2506 */
2507 public boolean performHapticFeedback(int effectId, boolean always) {
2508 try {
2509 return sWindowSession.performHapticFeedback(mWindow, effectId, always);
2510 } catch (RemoteException e) {
2511 return false;
2512 }
2513 }
2514
2515 /**
2516 * {@inheritDoc}
2517 */
2518 public View focusSearch(View focused, int direction) {
2519 checkThread();
2520 if (!(mView instanceof ViewGroup)) {
2521 return null;
2522 }
2523 return FocusFinder.getInstance().findNextFocus((ViewGroup) mView, focused, direction);
2524 }
2525
2526 public void debug() {
2527 mView.debug();
2528 }
2529
2530 public void die(boolean immediate) {
Dianne Hackborn94d69142009-09-28 22:14:42 -07002531 if (immediate) {
2532 doDie();
2533 } else {
2534 sendEmptyMessage(DIE);
2535 }
2536 }
2537
2538 void doDie() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002539 checkThread();
Jeff Brownb75fa302010-07-15 23:47:29 -07002540 if (LOCAL_LOGV) Log.v(TAG, "DIE in " + this + " of " + mSurface);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002541 synchronized (this) {
2542 if (mAdded && !mFirst) {
2543 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
2567 public void dispatchFinishedEvent(int seq, boolean handled) {
2568 Message msg = obtainMessage(FINISHED_EVENT);
2569 msg.arg1 = seq;
2570 msg.arg2 = handled ? 1 : 0;
2571 sendMessage(msg);
2572 }
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002573
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002574 public void dispatchResized(int w, int h, Rect coveredInsets,
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002575 Rect visibleInsets, boolean reportDraw, Configuration newConfig) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002576 if (DEBUG_LAYOUT) Log.v(TAG, "Resizing " + this + ": w=" + w
2577 + " h=" + h + " coveredInsets=" + coveredInsets.toShortString()
2578 + " visibleInsets=" + visibleInsets.toShortString()
2579 + " reportDraw=" + reportDraw);
2580 Message msg = obtainMessage(reportDraw ? RESIZED_REPORT :RESIZED);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002581 if (mTranslator != null) {
2582 mTranslator.translateRectInScreenToAppWindow(coveredInsets);
2583 mTranslator.translateRectInScreenToAppWindow(visibleInsets);
2584 w *= mTranslator.applicationInvertedScale;
2585 h *= mTranslator.applicationInvertedScale;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002586 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002587 msg.arg1 = w;
2588 msg.arg2 = h;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002589 ResizedInfo ri = new ResizedInfo();
2590 ri.coveredInsets = new Rect(coveredInsets);
2591 ri.visibleInsets = new Rect(visibleInsets);
2592 ri.newConfig = newConfig;
2593 msg.obj = ri;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002594 sendMessage(msg);
2595 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002596
2597 private Runnable mFinishedCallback;
2598
2599 private final InputHandler mInputHandler = new InputHandler() {
2600 public void handleKey(KeyEvent event, Runnable finishedCallback) {
Jeff Brown92ff1dd2010-08-11 16:16:06 -07002601 if (mFinishedCallback != null) {
2602 Slog.w(TAG, "Received a new key event from the input queue but there is "
2603 + "already an unfinished key event in progress.");
2604 }
2605
Jeff Brown46b9ac02010-04-22 18:58:52 -07002606 mFinishedCallback = finishedCallback;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002607
Jeff Brown92ff1dd2010-08-11 16:16:06 -07002608 dispatchKey(event, true);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002609 }
2610
Jeff Brownc5ed5912010-07-14 18:48:53 -07002611 public void handleMotion(MotionEvent event, Runnable finishedCallback) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002612 finishedCallback.run();
2613
Jeff Brownc5ed5912010-07-14 18:48:53 -07002614 dispatchMotion(event);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002615 }
2616 };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002617
2618 public void dispatchKey(KeyEvent event) {
Jeff Brown92ff1dd2010-08-11 16:16:06 -07002619 dispatchKey(event, false);
2620 }
2621
2622 private void dispatchKey(KeyEvent event, boolean sendDone) {
2623 //noinspection ConstantConditions
2624 if (false && event.getAction() == KeyEvent.ACTION_DOWN) {
2625 if (event.getKeyCode() == KeyEvent.KEYCODE_CAMERA) {
Romain Guy812ccbe2010-06-01 14:07:24 -07002626 if (DBG) Log.d("keydisp", "===================================================");
2627 if (DBG) Log.d("keydisp", "Focused view Hierarchy is:");
2628
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002629 debug();
2630
Romain Guy812ccbe2010-06-01 14:07:24 -07002631 if (DBG) Log.d("keydisp", "===================================================");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002632 }
2633 }
2634
2635 Message msg = obtainMessage(DISPATCH_KEY);
2636 msg.obj = event;
Jeff Brown92ff1dd2010-08-11 16:16:06 -07002637 msg.arg1 = sendDone ? 1 : 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002638
2639 if (LOCAL_LOGV) Log.v(
Jeff Brownc5ed5912010-07-14 18:48:53 -07002640 TAG, "sending key " + event + " to " + mView);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002641
2642 sendMessageAtTime(msg, event.getEventTime());
2643 }
Jeff Brownc5ed5912010-07-14 18:48:53 -07002644
2645 public void dispatchMotion(MotionEvent event) {
2646 int source = event.getSource();
2647 if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
2648 dispatchPointer(event);
2649 } else if ((source & InputDevice.SOURCE_CLASS_TRACKBALL) != 0) {
2650 dispatchTrackball(event);
2651 } else {
2652 // TODO
2653 Log.v(TAG, "Dropping unsupported motion event (unimplemented): " + event);
2654 }
2655 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002656
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002657 public void dispatchPointer(MotionEvent event) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002658 Message msg = obtainMessage(DISPATCH_POINTER);
2659 msg.obj = event;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002660 sendMessageAtTime(msg, event.getEventTime());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002661 }
2662
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002663 public void dispatchTrackball(MotionEvent event) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002664 Message msg = obtainMessage(DISPATCH_TRACKBALL);
2665 msg.obj = event;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002666 sendMessageAtTime(msg, event.getEventTime());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002667 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002668
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002669 public void dispatchAppVisibility(boolean visible) {
2670 Message msg = obtainMessage(DISPATCH_APP_VISIBILITY);
2671 msg.arg1 = visible ? 1 : 0;
2672 sendMessage(msg);
2673 }
2674
2675 public void dispatchGetNewSurface() {
2676 Message msg = obtainMessage(DISPATCH_GET_NEW_SURFACE);
2677 sendMessage(msg);
2678 }
2679
2680 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
2681 Message msg = Message.obtain();
2682 msg.what = WINDOW_FOCUS_CHANGED;
2683 msg.arg1 = hasFocus ? 1 : 0;
2684 msg.arg2 = inTouchMode ? 1 : 0;
2685 sendMessage(msg);
2686 }
2687
Dianne Hackbornffa42482009-09-23 22:20:11 -07002688 public void dispatchCloseSystemDialogs(String reason) {
2689 Message msg = Message.obtain();
2690 msg.what = CLOSE_SYSTEM_DIALOGS;
2691 msg.obj = reason;
2692 sendMessage(msg);
2693 }
2694
svetoslavganov75986cf2009-05-14 22:28:01 -07002695 /**
2696 * The window is getting focus so if there is anything focused/selected
2697 * send an {@link AccessibilityEvent} to announce that.
2698 */
2699 private void sendAccessibilityEvents() {
2700 if (!AccessibilityManager.getInstance(mView.getContext()).isEnabled()) {
2701 return;
2702 }
2703 mView.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
2704 View focusedView = mView.findFocus();
2705 if (focusedView != null && focusedView != mView) {
2706 focusedView.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
2707 }
2708 }
2709
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002710 public boolean showContextMenuForChild(View originalView) {
2711 return false;
2712 }
2713
Adam Powell6e346362010-07-23 10:18:23 -07002714 public ActionMode startActionModeForChild(View originalView, ActionMode.Callback callback) {
2715 return null;
2716 }
2717
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002718 public void createContextMenu(ContextMenu menu) {
2719 }
2720
2721 public void childDrawableStateChanged(View child) {
2722 }
2723
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002724 void checkThread() {
2725 if (mThread != Thread.currentThread()) {
2726 throw new CalledFromWrongThreadException(
2727 "Only the original thread that created a view hierarchy can touch its views.");
2728 }
2729 }
2730
2731 public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
2732 // ViewRoot never intercepts touch event, so this can be a no-op
2733 }
2734
2735 public boolean requestChildRectangleOnScreen(View child, Rect rectangle,
2736 boolean immediate) {
2737 return scrollToRectOrFocus(rectangle, immediate);
2738 }
Romain Guy8506ab42009-06-11 17:35:47 -07002739
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07002740 class TakenSurfaceHolder extends BaseSurfaceHolder {
2741 @Override
2742 public boolean onAllowLockCanvas() {
2743 return mDrawingAllowed;
2744 }
2745
2746 @Override
2747 public void onRelayoutContainer() {
2748 // Not currently interesting -- from changing between fixed and layout size.
2749 }
2750
2751 public void setFormat(int format) {
2752 ((RootViewSurfaceTaker)mView).setSurfaceFormat(format);
2753 }
2754
2755 public void setType(int type) {
2756 ((RootViewSurfaceTaker)mView).setSurfaceType(type);
2757 }
2758
2759 @Override
2760 public void onUpdateSurface() {
2761 // We take care of format and type changes on our own.
2762 throw new IllegalStateException("Shouldn't be here");
2763 }
2764
2765 public boolean isCreating() {
2766 return mIsCreating;
2767 }
2768
2769 @Override
2770 public void setFixedSize(int width, int height) {
2771 throw new UnsupportedOperationException(
2772 "Currently only support sizing from layout");
2773 }
2774
2775 public void setKeepScreenOn(boolean screenOn) {
2776 ((RootViewSurfaceTaker)mView).setSurfaceKeepScreenOn(screenOn);
2777 }
2778 }
2779
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002780 static class InputMethodCallback extends IInputMethodCallback.Stub {
2781 private WeakReference<ViewRoot> mViewRoot;
2782
2783 public InputMethodCallback(ViewRoot viewRoot) {
2784 mViewRoot = new WeakReference<ViewRoot>(viewRoot);
2785 }
Romain Guy8506ab42009-06-11 17:35:47 -07002786
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002787 public void finishedEvent(int seq, boolean handled) {
2788 final ViewRoot viewRoot = mViewRoot.get();
2789 if (viewRoot != null) {
2790 viewRoot.dispatchFinishedEvent(seq, handled);
2791 }
2792 }
2793
2794 public void sessionCreated(IInputMethodSession session) throws RemoteException {
2795 // Stub -- not for use in the client.
2796 }
2797 }
Romain Guy8506ab42009-06-11 17:35:47 -07002798
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002799 static class W extends IWindow.Stub {
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002800 private final WeakReference<ViewRoot> mViewRoot;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002801
Romain Guyfb8b7632010-08-23 21:05:08 -07002802 W(ViewRoot viewRoot) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002803 mViewRoot = new WeakReference<ViewRoot>(viewRoot);
2804 }
2805
Romain Guyfb8b7632010-08-23 21:05:08 -07002806 public void resized(int w, int h, Rect coveredInsets, Rect visibleInsets,
2807 boolean reportDraw, Configuration newConfig) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002808 final ViewRoot viewRoot = mViewRoot.get();
2809 if (viewRoot != null) {
Romain Guyfb8b7632010-08-23 21:05:08 -07002810 viewRoot.dispatchResized(w, h, coveredInsets, visibleInsets, reportDraw, newConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002811 }
2812 }
2813
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002814 public void dispatchAppVisibility(boolean visible) {
2815 final ViewRoot viewRoot = mViewRoot.get();
2816 if (viewRoot != null) {
2817 viewRoot.dispatchAppVisibility(visible);
2818 }
2819 }
2820
2821 public void dispatchGetNewSurface() {
2822 final ViewRoot viewRoot = mViewRoot.get();
2823 if (viewRoot != null) {
2824 viewRoot.dispatchGetNewSurface();
2825 }
2826 }
2827
2828 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
2829 final ViewRoot viewRoot = mViewRoot.get();
2830 if (viewRoot != null) {
2831 viewRoot.windowFocusChanged(hasFocus, inTouchMode);
2832 }
2833 }
2834
2835 private static int checkCallingPermission(String permission) {
2836 if (!Process.supportsProcesses()) {
2837 return PackageManager.PERMISSION_GRANTED;
2838 }
2839
2840 try {
2841 return ActivityManagerNative.getDefault().checkPermission(
2842 permission, Binder.getCallingPid(), Binder.getCallingUid());
2843 } catch (RemoteException e) {
2844 return PackageManager.PERMISSION_DENIED;
2845 }
2846 }
2847
2848 public void executeCommand(String command, String parameters, ParcelFileDescriptor out) {
2849 final ViewRoot viewRoot = mViewRoot.get();
2850 if (viewRoot != null) {
2851 final View view = viewRoot.mView;
2852 if (view != null) {
2853 if (checkCallingPermission(Manifest.permission.DUMP) !=
2854 PackageManager.PERMISSION_GRANTED) {
2855 throw new SecurityException("Insufficient permissions to invoke"
2856 + " executeCommand() from pid=" + Binder.getCallingPid()
2857 + ", uid=" + Binder.getCallingUid());
2858 }
2859
2860 OutputStream clientStream = null;
2861 try {
2862 clientStream = new ParcelFileDescriptor.AutoCloseOutputStream(out);
2863 ViewDebug.dispatchCommand(view, command, parameters, clientStream);
2864 } catch (IOException e) {
2865 e.printStackTrace();
2866 } finally {
2867 if (clientStream != null) {
2868 try {
2869 clientStream.close();
2870 } catch (IOException e) {
2871 e.printStackTrace();
2872 }
2873 }
2874 }
2875 }
2876 }
2877 }
Dianne Hackborn72c82ab2009-08-11 21:13:54 -07002878
Dianne Hackbornffa42482009-09-23 22:20:11 -07002879 public void closeSystemDialogs(String reason) {
2880 final ViewRoot viewRoot = mViewRoot.get();
2881 if (viewRoot != null) {
2882 viewRoot.dispatchCloseSystemDialogs(reason);
2883 }
2884 }
2885
Marco Nelissenbf6956b2009-11-09 15:21:13 -08002886 public void dispatchWallpaperOffsets(float x, float y, float xStep, float yStep,
2887 boolean sync) {
Dianne Hackborn19382ac2009-09-11 21:13:37 -07002888 if (sync) {
2889 try {
2890 sWindowSession.wallpaperOffsetsComplete(asBinder());
2891 } catch (RemoteException e) {
2892 }
2893 }
Dianne Hackborn72c82ab2009-08-11 21:13:54 -07002894 }
Dianne Hackborn75804932009-10-20 20:15:20 -07002895
2896 public void dispatchWallpaperCommand(String action, int x, int y,
2897 int z, Bundle extras, boolean sync) {
2898 if (sync) {
2899 try {
2900 sWindowSession.wallpaperCommandComplete(asBinder(), null);
2901 } catch (RemoteException e) {
2902 }
2903 }
2904 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002905 }
2906
2907 /**
2908 * Maintains state information for a single trackball axis, generating
2909 * discrete (DPAD) movements based on raw trackball motion.
2910 */
2911 static final class TrackballAxis {
2912 /**
2913 * The maximum amount of acceleration we will apply.
2914 */
2915 static final float MAX_ACCELERATION = 20;
Romain Guy8506ab42009-06-11 17:35:47 -07002916
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002917 /**
2918 * The maximum amount of time (in milliseconds) between events in order
2919 * for us to consider the user to be doing fast trackball movements,
2920 * and thus apply an acceleration.
2921 */
2922 static final long FAST_MOVE_TIME = 150;
Romain Guy8506ab42009-06-11 17:35:47 -07002923
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002924 /**
2925 * Scaling factor to the time (in milliseconds) between events to how
2926 * much to multiple/divide the current acceleration. When movement
2927 * is < FAST_MOVE_TIME this multiplies the acceleration; when >
2928 * FAST_MOVE_TIME it divides it.
2929 */
2930 static final float ACCEL_MOVE_SCALING_FACTOR = (1.0f/40);
Romain Guy8506ab42009-06-11 17:35:47 -07002931
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002932 float position;
2933 float absPosition;
2934 float acceleration = 1;
2935 long lastMoveTime = 0;
2936 int step;
2937 int dir;
2938 int nonAccelMovement;
2939
2940 void reset(int _step) {
2941 position = 0;
2942 acceleration = 1;
2943 lastMoveTime = 0;
2944 step = _step;
2945 dir = 0;
2946 }
2947
2948 /**
2949 * Add trackball movement into the state. If the direction of movement
2950 * has been reversed, the state is reset before adding the
2951 * movement (so that you don't have to compensate for any previously
2952 * collected movement before see the result of the movement in the
2953 * new direction).
2954 *
2955 * @return Returns the absolute value of the amount of movement
2956 * collected so far.
2957 */
2958 float collect(float off, long time, String axis) {
2959 long normTime;
2960 if (off > 0) {
2961 normTime = (long)(off * FAST_MOVE_TIME);
2962 if (dir < 0) {
2963 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to positive!");
2964 position = 0;
2965 step = 0;
2966 acceleration = 1;
2967 lastMoveTime = 0;
2968 }
2969 dir = 1;
2970 } else if (off < 0) {
2971 normTime = (long)((-off) * FAST_MOVE_TIME);
2972 if (dir > 0) {
2973 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to negative!");
2974 position = 0;
2975 step = 0;
2976 acceleration = 1;
2977 lastMoveTime = 0;
2978 }
2979 dir = -1;
2980 } else {
2981 normTime = 0;
2982 }
Romain Guy8506ab42009-06-11 17:35:47 -07002983
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002984 // The number of milliseconds between each movement that is
2985 // considered "normal" and will not result in any acceleration
2986 // or deceleration, scaled by the offset we have here.
2987 if (normTime > 0) {
2988 long delta = time - lastMoveTime;
2989 lastMoveTime = time;
2990 float acc = acceleration;
2991 if (delta < normTime) {
2992 // The user is scrolling rapidly, so increase acceleration.
2993 float scale = (normTime-delta) * ACCEL_MOVE_SCALING_FACTOR;
2994 if (scale > 1) acc *= scale;
2995 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " accelerate: off="
2996 + off + " normTime=" + normTime + " delta=" + delta
2997 + " scale=" + scale + " acc=" + acc);
2998 acceleration = acc < MAX_ACCELERATION ? acc : MAX_ACCELERATION;
2999 } else {
3000 // The user is scrolling slowly, so decrease acceleration.
3001 float scale = (delta-normTime) * ACCEL_MOVE_SCALING_FACTOR;
3002 if (scale > 1) acc /= scale;
3003 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " deccelerate: off="
3004 + off + " normTime=" + normTime + " delta=" + delta
3005 + " scale=" + scale + " acc=" + acc);
3006 acceleration = acc > 1 ? acc : 1;
3007 }
3008 }
3009 position += off;
3010 return (absPosition = Math.abs(position));
3011 }
3012
3013 /**
3014 * Generate the number of discrete movement events appropriate for
3015 * the currently collected trackball movement.
3016 *
3017 * @param precision The minimum movement required to generate the
3018 * first discrete movement.
3019 *
3020 * @return Returns the number of discrete movements, either positive
3021 * or negative, or 0 if there is not enough trackball movement yet
3022 * for a discrete movement.
3023 */
3024 int generate(float precision) {
3025 int movement = 0;
3026 nonAccelMovement = 0;
3027 do {
3028 final int dir = position >= 0 ? 1 : -1;
3029 switch (step) {
3030 // If we are going to execute the first step, then we want
3031 // to do this as soon as possible instead of waiting for
3032 // a full movement, in order to make things look responsive.
3033 case 0:
3034 if (absPosition < precision) {
3035 return movement;
3036 }
3037 movement += dir;
3038 nonAccelMovement += dir;
3039 step = 1;
3040 break;
3041 // If we have generated the first movement, then we need
3042 // to wait for the second complete trackball motion before
3043 // generating the second discrete movement.
3044 case 1:
3045 if (absPosition < 2) {
3046 return movement;
3047 }
3048 movement += dir;
3049 nonAccelMovement += dir;
3050 position += dir > 0 ? -2 : 2;
3051 absPosition = Math.abs(position);
3052 step = 2;
3053 break;
3054 // After the first two, we generate discrete movements
3055 // consistently with the trackball, applying an acceleration
3056 // if the trackball is moving quickly. This is a simple
3057 // acceleration on top of what we already compute based
3058 // on how quickly the wheel is being turned, to apply
3059 // a longer increasing acceleration to continuous movement
3060 // in one direction.
3061 default:
3062 if (absPosition < 1) {
3063 return movement;
3064 }
3065 movement += dir;
3066 position += dir >= 0 ? -1 : 1;
3067 absPosition = Math.abs(position);
3068 float acc = acceleration;
3069 acc *= 1.1f;
3070 acceleration = acc < MAX_ACCELERATION ? acc : acceleration;
3071 break;
3072 }
3073 } while (true);
3074 }
3075 }
3076
3077 public static final class CalledFromWrongThreadException extends AndroidRuntimeException {
3078 public CalledFromWrongThreadException(String msg) {
3079 super(msg);
3080 }
3081 }
3082
3083 private SurfaceHolder mHolder = new SurfaceHolder() {
3084 // we only need a SurfaceHolder for opengl. it would be nice
3085 // to implement everything else though, especially the callback
3086 // support (opengl doesn't make use of it right now, but eventually
3087 // will).
3088 public Surface getSurface() {
3089 return mSurface;
3090 }
3091
3092 public boolean isCreating() {
3093 return false;
3094 }
3095
3096 public void addCallback(Callback callback) {
3097 }
3098
3099 public void removeCallback(Callback callback) {
3100 }
3101
3102 public void setFixedSize(int width, int height) {
3103 }
3104
3105 public void setSizeFromLayout() {
3106 }
3107
3108 public void setFormat(int format) {
3109 }
3110
3111 public void setType(int type) {
3112 }
3113
3114 public void setKeepScreenOn(boolean screenOn) {
3115 }
3116
3117 public Canvas lockCanvas() {
3118 return null;
3119 }
3120
3121 public Canvas lockCanvas(Rect dirty) {
3122 return null;
3123 }
3124
3125 public void unlockCanvasAndPost(Canvas canvas) {
3126 }
3127 public Rect getSurfaceFrame() {
3128 return null;
3129 }
3130 };
3131
3132 static RunQueue getRunQueue() {
3133 RunQueue rq = sRunQueues.get();
3134 if (rq != null) {
3135 return rq;
3136 }
3137 rq = new RunQueue();
3138 sRunQueues.set(rq);
3139 return rq;
3140 }
Romain Guy8506ab42009-06-11 17:35:47 -07003141
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003142 /**
3143 * @hide
3144 */
3145 static final class RunQueue {
3146 private final ArrayList<HandlerAction> mActions = new ArrayList<HandlerAction>();
3147
3148 void post(Runnable action) {
3149 postDelayed(action, 0);
3150 }
3151
3152 void postDelayed(Runnable action, long delayMillis) {
3153 HandlerAction handlerAction = new HandlerAction();
3154 handlerAction.action = action;
3155 handlerAction.delay = delayMillis;
3156
3157 synchronized (mActions) {
3158 mActions.add(handlerAction);
3159 }
3160 }
3161
3162 void removeCallbacks(Runnable action) {
3163 final HandlerAction handlerAction = new HandlerAction();
3164 handlerAction.action = action;
3165
3166 synchronized (mActions) {
3167 final ArrayList<HandlerAction> actions = mActions;
3168
3169 while (actions.remove(handlerAction)) {
3170 // Keep going
3171 }
3172 }
3173 }
3174
3175 void executeActions(Handler handler) {
3176 synchronized (mActions) {
3177 final ArrayList<HandlerAction> actions = mActions;
3178 final int count = actions.size();
3179
3180 for (int i = 0; i < count; i++) {
3181 final HandlerAction handlerAction = actions.get(i);
3182 handler.postDelayed(handlerAction.action, handlerAction.delay);
3183 }
3184
Romain Guy15df6702009-08-17 20:17:30 -07003185 actions.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003186 }
3187 }
3188
3189 private static class HandlerAction {
3190 Runnable action;
3191 long delay;
3192
3193 @Override
3194 public boolean equals(Object o) {
3195 if (this == o) return true;
3196 if (o == null || getClass() != o.getClass()) return false;
3197
3198 HandlerAction that = (HandlerAction) o;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003199 return !(action != null ? !action.equals(that.action) : that.action != null);
3200
3201 }
3202
3203 @Override
3204 public int hashCode() {
3205 int result = action != null ? action.hashCode() : 0;
3206 result = 31 * result + (int) (delay ^ (delay >>> 32));
3207 return result;
3208 }
3209 }
3210 }
3211
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003212 private static native void nativeShowFPS(Canvas canvas, int durationMillis);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003213}