blob: 0c12998c1b20ad922f6a17a2df15cb8f5f18b837 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.view;
18
Romain Guy812ccbe2010-06-01 14:07:24 -070019import android.content.pm.ApplicationInfo;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -070020import com.android.internal.view.BaseSurfaceHolder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080021import com.android.internal.view.IInputMethodCallback;
22import com.android.internal.view.IInputMethodSession;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -070023import com.android.internal.view.RootViewSurfaceTaker;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080024
25import android.graphics.Canvas;
26import android.graphics.PixelFormat;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080027import android.graphics.PorterDuff;
28import android.graphics.Rect;
29import android.graphics.Region;
30import android.os.*;
31import android.os.Process;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080032import android.util.AndroidRuntimeException;
33import android.util.Config;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -070034import android.util.DisplayMetrics;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080035import android.util.Log;
36import android.util.EventLog;
37import android.util.SparseArray;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080038import android.view.View.MeasureSpec;
svetoslavganov75986cf2009-05-14 22:28:01 -070039import android.view.accessibility.AccessibilityEvent;
40import android.view.accessibility.AccessibilityManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080041import android.view.inputmethod.InputConnection;
42import android.view.inputmethod.InputMethodManager;
43import android.widget.Scroller;
44import android.content.pm.PackageManager;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -070045import android.content.res.CompatibilityInfo;
Dianne Hackborne36d6e22010-02-17 19:46:25 -080046import android.content.res.Configuration;
Mitsuru Oshima38ed7d772009-07-21 14:39:34 -070047import android.content.res.Resources;
Dianne Hackborne36d6e22010-02-17 19:46:25 -080048import android.content.ComponentCallbacks;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080049import android.content.Context;
50import android.app.ActivityManagerNative;
51import android.Manifest;
52import android.media.AudioManager;
53
54import java.lang.ref.WeakReference;
55import java.io.IOException;
56import java.io.OutputStream;
57import java.util.ArrayList;
58
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080059/**
60 * The top of a view hierarchy, implementing the needed protocol between View
61 * and the WindowManager. This is for the most part an internal implementation
62 * detail of {@link WindowManagerImpl}.
63 *
64 * {@hide}
65 */
Romain Guy812ccbe2010-06-01 14:07:24 -070066@SuppressWarnings({"EmptyCatchBlock", "PointlessBooleanExpression"})
67public final class ViewRoot extends Handler implements ViewParent, View.AttachInfo.Callbacks {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080068 private static final String TAG = "ViewRoot";
69 private static final boolean DBG = false;
Mike Reedfd716532009-10-12 14:42:56 -040070 private static final boolean SHOW_FPS = false;
Romain Guy812ccbe2010-06-01 14:07:24 -070071 private static final boolean LOCAL_LOGV = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080072 /** @noinspection PointlessBooleanExpression*/
73 private static final boolean DEBUG_DRAW = false || LOCAL_LOGV;
74 private static final boolean DEBUG_LAYOUT = false || LOCAL_LOGV;
Christopher Tatefa9e7c02010-05-06 12:07:10 -070075 private static final boolean DEBUG_INPUT = true || LOCAL_LOGV;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080076 private static final boolean DEBUG_INPUT_RESIZE = false || LOCAL_LOGV;
77 private static final boolean DEBUG_ORIENTATION = false || LOCAL_LOGV;
78 private static final boolean DEBUG_TRACKBALL = false || LOCAL_LOGV;
79 private static final boolean DEBUG_IMF = false || LOCAL_LOGV;
Dianne Hackborn694f79b2010-03-17 19:44:59 -070080 private static final boolean DEBUG_CONFIGURATION = false || LOCAL_LOGV;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080081 private static final boolean WATCH_POINTER = false;
82
Michael Chan53071d62009-05-13 17:29:48 -070083 private static final boolean MEASURE_LATENCY = false;
84 private static LatencyTimer lt;
85
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080086 /**
87 * Maximum time we allow the user to roll the trackball enough to generate
88 * a key event, before resetting the counters.
89 */
90 static final int MAX_TRACKBALL_DELAY = 250;
91
92 static long sInstanceCount = 0;
93
94 static IWindowSession sWindowSession;
95
96 static final Object mStaticInit = new Object();
97 static boolean mInitialized = false;
98
99 static final ThreadLocal<RunQueue> sRunQueues = new ThreadLocal<RunQueue>();
100
Dianne Hackborn2a9094d2010-02-03 19:20:09 -0800101 static final ArrayList<Runnable> sFirstDrawHandlers = new ArrayList<Runnable>();
102 static boolean sFirstDrawComplete = false;
103
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800104 static final ArrayList<ComponentCallbacks> sConfigCallbacks
105 = new ArrayList<ComponentCallbacks>();
106
Romain Guy8506ab42009-06-11 17:35:47 -0700107 private static int sDrawTime;
Romain Guy13922e02009-05-12 17:56:14 -0700108
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800109 long mLastTrackballTime = 0;
110 final TrackballAxis mTrackballAxisX = new TrackballAxis();
111 final TrackballAxis mTrackballAxisY = new TrackballAxis();
112
113 final int[] mTmpLocation = new int[2];
Romain Guy8506ab42009-06-11 17:35:47 -0700114
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800115 final InputMethodCallback mInputMethodCallback;
116 final SparseArray<Object> mPendingEvents = new SparseArray<Object>();
117 int mPendingEventSeq = 0;
Romain Guy8506ab42009-06-11 17:35:47 -0700118
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800119 final Thread mThread;
120
121 final WindowLeaked mLocation;
122
123 final WindowManager.LayoutParams mWindowAttributes = new WindowManager.LayoutParams();
124
125 final W mWindow;
126
127 View mView;
128 View mFocusedView;
129 View mRealFocusedView; // this is not set to null in touch mode
130 int mViewVisibility;
131 boolean mAppVisible = true;
132
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700133 SurfaceHolder.Callback mSurfaceHolderCallback;
134 BaseSurfaceHolder mSurfaceHolder;
135 boolean mIsCreating;
136 boolean mDrawingAllowed;
137
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800138 final Region mTransparentRegion;
139 final Region mPreviousTransparentRegion;
140
141 int mWidth;
142 int mHeight;
143 Rect mDirty; // will be a graphics.Region soon
Romain Guybb93d552009-03-24 21:04:15 -0700144 boolean mIsAnimating;
Romain Guy8506ab42009-06-11 17:35:47 -0700145
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700146 CompatibilityInfo.Translator mTranslator;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800147
148 final View.AttachInfo mAttachInfo;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700149 InputChannel mInputChannel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800150
151 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
Carl Shapiro82fe5642010-02-24 00:14:23 -0800235 // For debug only
236 //++sInstanceCount;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800237
238 // Initialize the statics when this class is first instantiated. This is
239 // done here instead of in the static block because Zygote does not
240 // allow the spawning of threads.
Dianne Hackborn4c62fc02009-08-08 20:40:27 -0700241 getWindowSession(context.getMainLooper());
242
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800243 mThread = Thread.currentThread();
244 mLocation = new WindowLeaked(null);
245 mLocation.fillInStackTrace();
246 mWidth = -1;
247 mHeight = -1;
248 mDirty = new Rect();
249 mTempRect = new Rect();
250 mVisRect = new Rect();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800251 mWinFrame = new Rect();
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -0700252 mWindow = new W(this, context);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800253 mInputMethodCallback = new InputMethodCallback(this);
254 mViewVisibility = View.GONE;
255 mTransparentRegion = new Region();
256 mPreviousTransparentRegion = new Region();
257 mFirst = true; // true for the first time the view is added
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800258 mAdded = false;
259 mAttachInfo = new View.AttachInfo(sWindowSession, mWindow, this, this);
260 mViewConfiguration = ViewConfiguration.get(context);
Dianne Hackborn11ea3342009-07-22 21:48:55 -0700261 mDensity = context.getResources().getDisplayMetrics().densityDpi;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800262 }
263
Carl Shapiro82fe5642010-02-24 00:14:23 -0800264 // For debug only
265 /*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800266 @Override
267 protected void finalize() throws Throwable {
268 super.finalize();
269 --sInstanceCount;
270 }
Carl Shapiro82fe5642010-02-24 00:14:23 -0800271 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800272
273 public static long getInstanceCount() {
274 return sInstanceCount;
275 }
276
Dianne Hackborn2a9094d2010-02-03 19:20:09 -0800277 public static void addFirstDrawHandler(Runnable callback) {
278 synchronized (sFirstDrawHandlers) {
279 if (!sFirstDrawComplete) {
280 sFirstDrawHandlers.add(callback);
281 }
282 }
283 }
284
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800285 public static void addConfigCallback(ComponentCallbacks callback) {
286 synchronized (sConfigCallbacks) {
287 sConfigCallbacks.add(callback);
288 }
289 }
290
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800291 // FIXME for perf testing only
292 private boolean mProfile = false;
293
294 /**
295 * Call this to profile the next traversal call.
296 * FIXME for perf testing only. Remove eventually
297 */
298 public void profile() {
299 mProfile = true;
300 }
301
302 /**
303 * Indicates whether we are in touch mode. Calling this method triggers an IPC
304 * call and should be avoided whenever possible.
305 *
306 * @return True, if the device is in touch mode, false otherwise.
307 *
308 * @hide
309 */
310 static boolean isInTouchMode() {
311 if (mInitialized) {
312 try {
313 return sWindowSession.getInTouchMode();
314 } catch (RemoteException e) {
315 }
316 }
317 return false;
318 }
319
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800320 /**
321 * We have one child
322 */
Romain Guye4d01122010-06-16 18:44:05 -0700323 public void setView(View view, WindowManager.LayoutParams attrs, View panelParentView) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800324 synchronized (this) {
325 if (mView == null) {
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700326 mView = view;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700327 mWindowAttributes.copyFrom(attrs);
Mitsuru Oshima1ecf5d22009-07-06 17:20:38 -0700328 attrs = mWindowAttributes;
Romain Guye4d01122010-06-16 18:44:05 -0700329
330 enableHardwareAcceleration(view, attrs);
331
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700332 if (view instanceof RootViewSurfaceTaker) {
333 mSurfaceHolderCallback =
334 ((RootViewSurfaceTaker)view).willYouTakeTheSurface();
335 if (mSurfaceHolderCallback != null) {
336 mSurfaceHolder = new TakenSurfaceHolder();
337 }
338 }
Mitsuru Oshima38ed7d772009-07-21 14:39:34 -0700339 Resources resources = mView.getContext().getResources();
340 CompatibilityInfo compatibilityInfo = resources.getCompatibilityInfo();
Mitsuru Oshima589cebe2009-07-22 20:38:58 -0700341 mTranslator = compatibilityInfo.getTranslator();
Mitsuru Oshima38ed7d772009-07-21 14:39:34 -0700342
343 if (mTranslator != null || !compatibilityInfo.supportsScreen()) {
Mitsuru Oshima240f8a72009-07-22 20:39:14 -0700344 mSurface.setCompatibleDisplayMetrics(resources.getDisplayMetrics(),
345 mTranslator);
Mitsuru Oshima38ed7d772009-07-21 14:39:34 -0700346 }
347
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -0700348 boolean restore = false;
Romain Guy35b38ce2009-10-07 13:38:55 -0700349 if (mTranslator != null) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -0700350 restore = true;
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700351 attrs.backup();
352 mTranslator.translateWindowLayout(attrs);
Mitsuru Oshima3d914922009-05-13 22:29:15 -0700353 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700354 if (DEBUG_LAYOUT) Log.d(TAG, "WindowLayout in setView:" + attrs);
355
Mitsuru Oshima1ecf5d22009-07-06 17:20:38 -0700356 if (!compatibilityInfo.supportsScreen()) {
357 attrs.flags |= WindowManager.LayoutParams.FLAG_COMPATIBLE_WINDOW;
358 }
359
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800360 mSoftInputMode = attrs.softInputMode;
361 mWindowAttributesChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800362 mAttachInfo.mRootView = view;
Romain Guy35b38ce2009-10-07 13:38:55 -0700363 mAttachInfo.mScalingRequired = mTranslator != null;
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700364 mAttachInfo.mApplicationScale =
365 mTranslator == null ? 1.0f : mTranslator.applicationScale;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800366 if (panelParentView != null) {
367 mAttachInfo.mPanelParentWindowToken
368 = panelParentView.getApplicationWindowToken();
369 }
370 mAdded = true;
371 int res; /* = WindowManagerImpl.ADD_OKAY; */
Romain Guy8506ab42009-06-11 17:35:47 -0700372
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800373 // Schedule the first layout -before- adding to the window
374 // manager, to make sure we do the relayout before receiving
375 // any other events from the system.
376 requestLayout();
Jeff Brown46b9ac02010-04-22 18:58:52 -0700377 mInputChannel = new InputChannel();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800378 try {
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700379 res = sWindowSession.add(mWindow, mWindowAttributes,
Jeff Brown46b9ac02010-04-22 18:58:52 -0700380 getHostVisibility(), mAttachInfo.mContentInsets,
381 mInputChannel);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800382 } catch (RemoteException e) {
383 mAdded = false;
384 mView = null;
385 mAttachInfo.mRootView = null;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700386 mInputChannel = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800387 unscheduleTraversals();
388 throw new RuntimeException("Adding window failed", e);
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700389 } finally {
390 if (restore) {
391 attrs.restore();
392 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800393 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700394
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700395 if (mTranslator != null) {
396 mTranslator.translateRectInScreenToAppWindow(mAttachInfo.mContentInsets);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700397 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800398 mPendingContentInsets.set(mAttachInfo.mContentInsets);
399 mPendingVisibleInsets.set(0, 0, 0, 0);
400 if (Config.LOGV) Log.v("ViewRoot", "Added window " + mWindow);
401 if (res < WindowManagerImpl.ADD_OKAY) {
402 mView = null;
403 mAttachInfo.mRootView = null;
404 mAdded = false;
405 unscheduleTraversals();
406 switch (res) {
407 case WindowManagerImpl.ADD_BAD_APP_TOKEN:
408 case WindowManagerImpl.ADD_BAD_SUBWINDOW_TOKEN:
409 throw new WindowManagerImpl.BadTokenException(
410 "Unable to add window -- token " + attrs.token
411 + " is not valid; is your activity running?");
412 case WindowManagerImpl.ADD_NOT_APP_TOKEN:
413 throw new WindowManagerImpl.BadTokenException(
414 "Unable to add window -- token " + attrs.token
415 + " is not for an application");
416 case WindowManagerImpl.ADD_APP_EXITING:
417 throw new WindowManagerImpl.BadTokenException(
418 "Unable to add window -- app for token " + attrs.token
419 + " is exiting");
420 case WindowManagerImpl.ADD_DUPLICATE_ADD:
421 throw new WindowManagerImpl.BadTokenException(
422 "Unable to add window -- window " + mWindow
423 + " has already been added");
424 case WindowManagerImpl.ADD_STARTING_NOT_NEEDED:
425 // Silently ignore -- we would have just removed it
426 // right away, anyway.
427 return;
428 case WindowManagerImpl.ADD_MULTIPLE_SINGLETON:
429 throw new WindowManagerImpl.BadTokenException(
430 "Unable to add window " + mWindow +
431 " -- another window of this type already exists");
432 case WindowManagerImpl.ADD_PERMISSION_DENIED:
433 throw new WindowManagerImpl.BadTokenException(
434 "Unable to add window " + mWindow +
435 " -- permission denied for this window type");
436 }
437 throw new RuntimeException(
438 "Unable to add window -- unknown error code " + res);
439 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700440
441 if (WindowManagerPolicy.ENABLE_NATIVE_INPUT_DISPATCH) {
442 InputQueue.registerInputChannel(mInputChannel, mInputHandler,
443 Looper.myQueue());
444 }
445
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800446 view.assignParent(this);
447 mAddedTouchMode = (res&WindowManagerImpl.ADD_FLAG_IN_TOUCH_MODE) != 0;
448 mAppVisible = (res&WindowManagerImpl.ADD_FLAG_APP_VISIBLE) != 0;
449 }
450 }
451 }
452
Romain Guye4d01122010-06-16 18:44:05 -0700453 private void enableHardwareAcceleration(View view, WindowManager.LayoutParams attrs) {
454 // Only enable hardware acceleration if we are not in the system process
455 // The window manager creates ViewRoots to display animated preview windows
456 // of launching apps and we don't want those to be hardware accelerated
457 if (Process.myUid() != Process.SYSTEM_UID) {
458 // Try to enable hardware acceleration if requested
459 if ((view.getContext().getApplicationInfo().flags &
460 ApplicationInfo.FLAG_HARDWARE_ACCELERATED) != 0) {
461 final boolean translucent = attrs.format != PixelFormat.OPAQUE;
462 mHwRenderer = HardwareRenderer.createGlRenderer(2, translucent);
463 }
464 }
465 }
466
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800467 public View getView() {
468 return mView;
469 }
470
471 final WindowLeaked getLocation() {
472 return mLocation;
473 }
474
475 void setLayoutParams(WindowManager.LayoutParams attrs, boolean newView) {
476 synchronized (this) {
The Android Open Source Project10592532009-03-18 17:39:46 -0700477 int oldSoftInputMode = mWindowAttributes.softInputMode;
Mitsuru Oshima5a2b91d2009-07-16 16:30:02 -0700478 // preserve compatible window flag if exists.
479 int compatibleWindowFlag =
480 mWindowAttributes.flags & WindowManager.LayoutParams.FLAG_COMPATIBLE_WINDOW;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800481 mWindowAttributes.copyFrom(attrs);
Mitsuru Oshima5a2b91d2009-07-16 16:30:02 -0700482 mWindowAttributes.flags |= compatibleWindowFlag;
483
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800484 if (newView) {
485 mSoftInputMode = attrs.softInputMode;
486 requestLayout();
487 }
The Android Open Source Project10592532009-03-18 17:39:46 -0700488 // Don't lose the mode we last auto-computed.
489 if ((attrs.softInputMode&WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST)
490 == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED) {
491 mWindowAttributes.softInputMode = (mWindowAttributes.softInputMode
492 & ~WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST)
493 | (oldSoftInputMode
494 & WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST);
495 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800496 mWindowAttributesChanged = true;
497 scheduleTraversals();
498 }
499 }
500
501 void handleAppVisibility(boolean visible) {
502 if (mAppVisible != visible) {
503 mAppVisible = visible;
504 scheduleTraversals();
505 }
506 }
507
508 void handleGetNewSurface() {
509 mNewSurfaceNeeded = true;
510 mFullRedrawNeeded = true;
511 scheduleTraversals();
512 }
513
514 /**
515 * {@inheritDoc}
516 */
517 public void requestLayout() {
518 checkThread();
519 mLayoutRequested = true;
520 scheduleTraversals();
521 }
522
523 /**
524 * {@inheritDoc}
525 */
526 public boolean isLayoutRequested() {
527 return mLayoutRequested;
528 }
529
530 public void invalidateChild(View child, Rect dirty) {
531 checkThread();
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700532 if (DEBUG_DRAW) Log.v(TAG, "Invalidate child: " + dirty);
533 if (mCurScrollY != 0 || mTranslator != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800534 mTempRect.set(dirty);
Romain Guy1e095972009-07-07 11:22:45 -0700535 dirty = mTempRect;
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700536 if (mCurScrollY != 0) {
Romain Guy1e095972009-07-07 11:22:45 -0700537 dirty.offset(0, -mCurScrollY);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700538 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700539 if (mTranslator != null) {
Romain Guy1e095972009-07-07 11:22:45 -0700540 mTranslator.translateRectInAppWindowToScreen(dirty);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700541 }
Romain Guy1e095972009-07-07 11:22:45 -0700542 if (mAttachInfo.mScalingRequired) {
543 dirty.inset(-1, -1);
544 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800545 }
546 mDirty.union(dirty);
547 if (!mWillDrawSoon) {
548 scheduleTraversals();
549 }
550 }
551
552 public ViewParent getParent() {
553 return null;
554 }
555
556 public ViewParent invalidateChildInParent(final int[] location, final Rect dirty) {
557 invalidateChild(null, dirty);
558 return null;
559 }
560
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700561 public boolean getChildVisibleRect(View child, Rect r, android.graphics.Point offset) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800562 if (child != mView) {
563 throw new RuntimeException("child is not mine, honest!");
564 }
565 // Note: don't apply scroll offset, because we want to know its
566 // visibility in the virtual canvas being given to the view hierarchy.
567 return r.intersect(0, 0, mWidth, mHeight);
568 }
569
570 public void bringChildToFront(View child) {
571 }
572
573 public void scheduleTraversals() {
574 if (!mTraversalScheduled) {
575 mTraversalScheduled = true;
576 sendEmptyMessage(DO_TRAVERSAL);
577 }
578 }
579
580 public void unscheduleTraversals() {
581 if (mTraversalScheduled) {
582 mTraversalScheduled = false;
583 removeMessages(DO_TRAVERSAL);
584 }
585 }
586
587 int getHostVisibility() {
588 return mAppVisible ? mView.getVisibility() : View.GONE;
589 }
Romain Guy8506ab42009-06-11 17:35:47 -0700590
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800591 private void performTraversals() {
592 // cache mView since it is used so much below...
593 final View host = mView;
594
595 if (DBG) {
596 System.out.println("======================================");
597 System.out.println("performTraversals");
598 host.debug();
599 }
600
601 if (host == null || !mAdded)
602 return;
603
604 mTraversalScheduled = false;
605 mWillDrawSoon = true;
606 boolean windowResizesToFitContent = false;
607 boolean fullRedrawNeeded = mFullRedrawNeeded;
608 boolean newSurface = false;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700609 boolean surfaceChanged = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800610 WindowManager.LayoutParams lp = mWindowAttributes;
611
612 int desiredWindowWidth;
613 int desiredWindowHeight;
614 int childWidthMeasureSpec;
615 int childHeightMeasureSpec;
616
617 final View.AttachInfo attachInfo = mAttachInfo;
618
619 final int viewVisibility = getHostVisibility();
620 boolean viewVisibilityChanged = mViewVisibility != viewVisibility
621 || mNewSurfaceNeeded;
622
623 WindowManager.LayoutParams params = null;
624 if (mWindowAttributesChanged) {
625 mWindowAttributesChanged = false;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700626 surfaceChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800627 params = lp;
628 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700629 Rect frame = mWinFrame;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800630 if (mFirst) {
631 fullRedrawNeeded = true;
632 mLayoutRequested = true;
633
Romain Guy8506ab42009-06-11 17:35:47 -0700634 DisplayMetrics packageMetrics =
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700635 mView.getContext().getResources().getDisplayMetrics();
636 desiredWindowWidth = packageMetrics.widthPixels;
637 desiredWindowHeight = packageMetrics.heightPixels;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800638
639 // For the very first time, tell the view hierarchy that it
640 // is attached to the window. Note that at this point the surface
641 // object is not initialized to its backing store, but soon it
642 // will be (assuming the window is visible).
643 attachInfo.mSurface = mSurface;
Romain Guy35b38ce2009-10-07 13:38:55 -0700644 attachInfo.mTranslucentWindow = lp.format != PixelFormat.OPAQUE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800645 attachInfo.mHasWindowFocus = false;
646 attachInfo.mWindowVisibility = viewVisibility;
647 attachInfo.mRecomputeGlobalAttributes = false;
648 attachInfo.mKeepScreenOn = false;
649 viewVisibilityChanged = false;
Dianne Hackborn694f79b2010-03-17 19:44:59 -0700650 mLastConfiguration.setTo(host.getResources().getConfiguration());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800651 host.dispatchAttachedToWindow(attachInfo, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800652 //Log.i(TAG, "Screen on initialized: " + attachInfo.mKeepScreenOn);
svetoslavganov75986cf2009-05-14 22:28:01 -0700653
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800654 } else {
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700655 desiredWindowWidth = frame.width();
656 desiredWindowHeight = frame.height();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800657 if (desiredWindowWidth != mWidth || desiredWindowHeight != mHeight) {
658 if (DEBUG_ORIENTATION) Log.v("ViewRoot",
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700659 "View " + host + " resized to: " + frame);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800660 fullRedrawNeeded = true;
661 mLayoutRequested = true;
662 windowResizesToFitContent = true;
663 }
664 }
665
666 if (viewVisibilityChanged) {
667 attachInfo.mWindowVisibility = viewVisibility;
668 host.dispatchWindowVisibilityChanged(viewVisibility);
669 if (viewVisibility != View.VISIBLE || mNewSurfaceNeeded) {
Romain Guy812ccbe2010-06-01 14:07:24 -0700670 if (mHwRenderer != null) {
Romain Guy2d614592010-06-09 18:21:37 -0700671 mHwRenderer.destroy();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800672 }
673 }
674 if (viewVisibility == View.GONE) {
675 // After making a window gone, we will count it as being
676 // shown for the first time the next time it gets focus.
677 mHasHadWindowFocus = false;
678 }
679 }
680
681 boolean insetsChanged = false;
Romain Guy8506ab42009-06-11 17:35:47 -0700682
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800683 if (mLayoutRequested) {
Romain Guy15df6702009-08-17 20:17:30 -0700684 // Execute enqueued actions on every layout in case a view that was detached
685 // enqueued an action after being detached
686 getRunQueue().executeActions(attachInfo.mHandler);
687
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800688 if (mFirst) {
689 host.fitSystemWindows(mAttachInfo.mContentInsets);
690 // make sure touch mode code executes by setting cached value
691 // to opposite of the added touch mode.
692 mAttachInfo.mInTouchMode = !mAddedTouchMode;
Romain Guy2d4cff62010-04-09 15:39:00 -0700693 ensureTouchModeLocally(mAddedTouchMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800694 } else {
695 if (!mAttachInfo.mContentInsets.equals(mPendingContentInsets)) {
696 mAttachInfo.mContentInsets.set(mPendingContentInsets);
697 host.fitSystemWindows(mAttachInfo.mContentInsets);
698 insetsChanged = true;
699 if (DEBUG_LAYOUT) Log.v(TAG, "Content insets changing to: "
700 + mAttachInfo.mContentInsets);
701 }
702 if (!mAttachInfo.mVisibleInsets.equals(mPendingVisibleInsets)) {
703 mAttachInfo.mVisibleInsets.set(mPendingVisibleInsets);
704 if (DEBUG_LAYOUT) Log.v(TAG, "Visible insets changing to: "
705 + mAttachInfo.mVisibleInsets);
706 }
707 if (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT
708 || lp.height == ViewGroup.LayoutParams.WRAP_CONTENT) {
709 windowResizesToFitContent = true;
710
Romain Guy8506ab42009-06-11 17:35:47 -0700711 DisplayMetrics packageMetrics =
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700712 mView.getContext().getResources().getDisplayMetrics();
713 desiredWindowWidth = packageMetrics.widthPixels;
714 desiredWindowHeight = packageMetrics.heightPixels;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800715 }
716 }
717
718 childWidthMeasureSpec = getRootMeasureSpec(desiredWindowWidth, lp.width);
719 childHeightMeasureSpec = getRootMeasureSpec(desiredWindowHeight, lp.height);
720
721 // Ask host how big it wants to be
722 if (DEBUG_ORIENTATION || DEBUG_LAYOUT) Log.v("ViewRoot",
723 "Measuring " + host + " in display " + desiredWindowWidth
724 + "x" + desiredWindowHeight + "...");
725 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
726
727 if (DBG) {
728 System.out.println("======================================");
729 System.out.println("performTraversals -- after measure");
730 host.debug();
731 }
732 }
733
734 if (attachInfo.mRecomputeGlobalAttributes) {
735 //Log.i(TAG, "Computing screen on!");
736 attachInfo.mRecomputeGlobalAttributes = false;
737 boolean oldVal = attachInfo.mKeepScreenOn;
738 attachInfo.mKeepScreenOn = false;
739 host.dispatchCollectViewAttributes(0);
740 if (attachInfo.mKeepScreenOn != oldVal) {
741 params = lp;
742 //Log.i(TAG, "Keep screen on changed: " + attachInfo.mKeepScreenOn);
743 }
744 }
745
746 if (mFirst || attachInfo.mViewVisibilityChanged) {
747 attachInfo.mViewVisibilityChanged = false;
748 int resizeMode = mSoftInputMode &
749 WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST;
750 // If we are in auto resize mode, then we need to determine
751 // what mode to use now.
752 if (resizeMode == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED) {
753 final int N = attachInfo.mScrollContainers.size();
754 for (int i=0; i<N; i++) {
755 if (attachInfo.mScrollContainers.get(i).isShown()) {
756 resizeMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE;
757 }
758 }
759 if (resizeMode == 0) {
760 resizeMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN;
761 }
762 if ((lp.softInputMode &
763 WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) != resizeMode) {
764 lp.softInputMode = (lp.softInputMode &
765 ~WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) |
766 resizeMode;
767 params = lp;
768 }
769 }
770 }
Romain Guy8506ab42009-06-11 17:35:47 -0700771
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800772 if (params != null && (host.mPrivateFlags & View.REQUEST_TRANSPARENT_REGIONS) != 0) {
773 if (!PixelFormat.formatHasAlpha(params.format)) {
774 params.format = PixelFormat.TRANSLUCENT;
775 }
776 }
777
778 boolean windowShouldResize = mLayoutRequested && windowResizesToFitContent
Romain Guy2e4f4262010-04-06 11:07:52 -0700779 && ((mWidth != host.mMeasuredWidth || mHeight != host.mMeasuredHeight)
780 || (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT &&
781 frame.width() < desiredWindowWidth && frame.width() != mWidth)
782 || (lp.height == ViewGroup.LayoutParams.WRAP_CONTENT &&
783 frame.height() < desiredWindowHeight && frame.height() != mHeight));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800784
785 final boolean computesInternalInsets =
786 attachInfo.mTreeObserver.hasComputeInternalInsetsListeners();
Romain Guy812ccbe2010-06-01 14:07:24 -0700787
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800788 boolean insetsPending = false;
789 int relayoutResult = 0;
Romain Guy812ccbe2010-06-01 14:07:24 -0700790
791 if (mFirst || windowShouldResize || insetsChanged ||
792 viewVisibilityChanged || params != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800793
794 if (viewVisibility == View.VISIBLE) {
795 // If this window is giving internal insets to the window
796 // manager, and it is being added or changing its visibility,
797 // then we want to first give the window manager "fake"
798 // insets to cause it to effectively ignore the content of
799 // the window during layout. This avoids it briefly causing
800 // other windows to resize/move based on the raw frame of the
801 // window, waiting until we can finish laying out this window
802 // and get back to the window manager with the ultimately
803 // computed insets.
Romain Guy812ccbe2010-06-01 14:07:24 -0700804 insetsPending = computesInternalInsets && (mFirst || viewVisibilityChanged);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800805 }
806
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700807 if (mSurfaceHolder != null) {
808 mSurfaceHolder.mSurfaceLock.lock();
809 mDrawingAllowed = true;
810 lp.format = mSurfaceHolder.getRequestedFormat();
811 lp.type = mSurfaceHolder.getRequestedType();
812 }
Romain Guy812ccbe2010-06-01 14:07:24 -0700813
814 boolean hwIntialized = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800815 boolean contentInsetsChanged = false;
Romain Guy13922e02009-05-12 17:56:14 -0700816 boolean visibleInsetsChanged;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700817 boolean hadSurface = mSurface.isValid();
Romain Guy812ccbe2010-06-01 14:07:24 -0700818
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800819 try {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800820 int fl = 0;
821 if (params != null) {
822 fl = params.flags;
823 if (attachInfo.mKeepScreenOn) {
824 params.flags |= WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
825 }
826 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700827 if (DEBUG_LAYOUT) {
828 Log.i(TAG, "host=w:" + host.mMeasuredWidth + ", h:" +
829 host.mMeasuredHeight + ", params=" + params);
830 }
831 relayoutResult = relayoutWindow(params, viewVisibility, insetsPending);
832
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800833 if (params != null) {
834 params.flags = fl;
835 }
836
837 if (DEBUG_LAYOUT) Log.v(TAG, "relayout: frame=" + frame.toShortString()
838 + " content=" + mPendingContentInsets.toShortString()
839 + " visible=" + mPendingVisibleInsets.toShortString()
840 + " surface=" + mSurface);
Romain Guy8506ab42009-06-11 17:35:47 -0700841
Dianne Hackborn694f79b2010-03-17 19:44:59 -0700842 if (mPendingConfiguration.seq != 0) {
843 if (DEBUG_CONFIGURATION) Log.v(TAG, "Visible with new config: "
844 + mPendingConfiguration);
845 updateConfiguration(mPendingConfiguration, !mFirst);
846 mPendingConfiguration.seq = 0;
847 }
848
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800849 contentInsetsChanged = !mPendingContentInsets.equals(
850 mAttachInfo.mContentInsets);
851 visibleInsetsChanged = !mPendingVisibleInsets.equals(
852 mAttachInfo.mVisibleInsets);
853 if (contentInsetsChanged) {
854 mAttachInfo.mContentInsets.set(mPendingContentInsets);
855 host.fitSystemWindows(mAttachInfo.mContentInsets);
856 if (DEBUG_LAYOUT) Log.v(TAG, "Content insets changing to: "
857 + mAttachInfo.mContentInsets);
858 }
859 if (visibleInsetsChanged) {
860 mAttachInfo.mVisibleInsets.set(mPendingVisibleInsets);
861 if (DEBUG_LAYOUT) Log.v(TAG, "Visible insets changing to: "
862 + mAttachInfo.mVisibleInsets);
863 }
864
865 if (!hadSurface) {
866 if (mSurface.isValid()) {
867 // If we are creating a new surface, then we need to
868 // completely redraw it. Also, when we get to the
869 // point of drawing it we will hold off and schedule
870 // a new traversal instead. This is so we can tell the
871 // window manager about all of the windows being displayed
872 // before actually drawing them, so it can display then
873 // all at once.
874 newSurface = true;
875 fullRedrawNeeded = true;
Jack Palevich61a6e682009-10-09 17:37:50 -0700876 mPreviousTransparentRegion.setEmpty();
Romain Guy8506ab42009-06-11 17:35:47 -0700877
Romain Guy812ccbe2010-06-01 14:07:24 -0700878 if (mHwRenderer != null) {
Romain Guy2d614592010-06-09 18:21:37 -0700879 hwIntialized = mHwRenderer.initialize(mHolder);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800880 }
881 }
882 } else if (!mSurface.isValid()) {
883 // If the surface has been removed, then reset the scroll
884 // positions.
885 mLastScrolledFocus = null;
886 mScrollY = mCurScrollY = 0;
887 if (mScroller != null) {
888 mScroller.abortAnimation();
889 }
890 }
891 } catch (RemoteException e) {
892 }
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700893
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800894 if (DEBUG_ORIENTATION) Log.v(
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700895 "ViewRoot", "Relayout returned: frame=" + frame + ", surface=" + mSurface);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800896
897 attachInfo.mWindowLeft = frame.left;
898 attachInfo.mWindowTop = frame.top;
899
900 // !!FIXME!! This next section handles the case where we did not get the
901 // window size we asked for. We should avoid this by getting a maximum size from
902 // the window session beforehand.
903 mWidth = frame.width();
904 mHeight = frame.height();
905
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700906 if (mSurfaceHolder != null) {
907 // The app owns the surface; tell it about what is going on.
908 if (mSurface.isValid()) {
909 // XXX .copyFrom() doesn't work!
910 //mSurfaceHolder.mSurface.copyFrom(mSurface);
911 mSurfaceHolder.mSurface = mSurface;
912 }
913 mSurfaceHolder.mSurfaceLock.unlock();
914 if (mSurface.isValid()) {
915 if (!hadSurface) {
916 mSurfaceHolder.ungetCallbacks();
917
918 mIsCreating = true;
919 mSurfaceHolderCallback.surfaceCreated(mSurfaceHolder);
920 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
921 if (callbacks != null) {
922 for (SurfaceHolder.Callback c : callbacks) {
923 c.surfaceCreated(mSurfaceHolder);
924 }
925 }
926 surfaceChanged = true;
927 }
928 if (surfaceChanged) {
929 mSurfaceHolderCallback.surfaceChanged(mSurfaceHolder,
930 lp.format, mWidth, mHeight);
931 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
932 if (callbacks != null) {
933 for (SurfaceHolder.Callback c : callbacks) {
934 c.surfaceChanged(mSurfaceHolder, lp.format,
935 mWidth, mHeight);
936 }
937 }
938 }
939 mIsCreating = false;
940 } else if (hadSurface) {
941 mSurfaceHolder.ungetCallbacks();
942 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
943 mSurfaceHolderCallback.surfaceDestroyed(mSurfaceHolder);
944 if (callbacks != null) {
945 for (SurfaceHolder.Callback c : callbacks) {
946 c.surfaceDestroyed(mSurfaceHolder);
947 }
948 }
949 mSurfaceHolder.mSurfaceLock.lock();
950 // Make surface invalid.
951 //mSurfaceHolder.mSurface.copyFrom(mSurface);
952 mSurfaceHolder.mSurface = new Surface();
953 mSurfaceHolder.mSurfaceLock.unlock();
954 }
955 }
956
Romain Guy812ccbe2010-06-01 14:07:24 -0700957 if (hwIntialized) {
Romain Guy2d614592010-06-09 18:21:37 -0700958 mHwRenderer.setup(mWidth, mHeight, mAttachInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800959 }
960
961 boolean focusChangedDueToTouchMode = ensureTouchModeLocally(
Romain Guy2d4cff62010-04-09 15:39:00 -0700962 (relayoutResult&WindowManagerImpl.RELAYOUT_IN_TOUCH_MODE) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800963 if (focusChangedDueToTouchMode || mWidth != host.mMeasuredWidth
964 || mHeight != host.mMeasuredHeight || contentInsetsChanged) {
965 childWidthMeasureSpec = getRootMeasureSpec(mWidth, lp.width);
966 childHeightMeasureSpec = getRootMeasureSpec(mHeight, lp.height);
967
968 if (DEBUG_LAYOUT) Log.v(TAG, "Ooops, something changed! mWidth="
969 + mWidth + " measuredWidth=" + host.mMeasuredWidth
970 + " mHeight=" + mHeight
971 + " measuredHeight" + host.mMeasuredHeight
972 + " coveredInsetsChanged=" + contentInsetsChanged);
Romain Guy8506ab42009-06-11 17:35:47 -0700973
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800974 // Ask host how big it wants to be
975 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
976
977 // Implementation of weights from WindowManager.LayoutParams
978 // We just grow the dimensions as needed and re-measure if
979 // needs be
980 int width = host.mMeasuredWidth;
981 int height = host.mMeasuredHeight;
982 boolean measureAgain = false;
983
984 if (lp.horizontalWeight > 0.0f) {
985 width += (int) ((mWidth - width) * lp.horizontalWeight);
986 childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(width,
987 MeasureSpec.EXACTLY);
988 measureAgain = true;
989 }
990 if (lp.verticalWeight > 0.0f) {
991 height += (int) ((mHeight - height) * lp.verticalWeight);
992 childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(height,
993 MeasureSpec.EXACTLY);
994 measureAgain = true;
995 }
996
997 if (measureAgain) {
998 if (DEBUG_LAYOUT) Log.v(TAG,
999 "And hey let's measure once more: width=" + width
1000 + " height=" + height);
1001 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
1002 }
1003
1004 mLayoutRequested = true;
1005 }
1006 }
1007
1008 final boolean didLayout = mLayoutRequested;
1009 boolean triggerGlobalLayoutListener = didLayout
1010 || attachInfo.mRecomputeGlobalAttributes;
1011 if (didLayout) {
1012 mLayoutRequested = false;
1013 mScrollMayChange = true;
1014 if (DEBUG_ORIENTATION || DEBUG_LAYOUT) Log.v(
1015 "ViewRoot", "Laying out " + host + " to (" +
1016 host.mMeasuredWidth + ", " + host.mMeasuredHeight + ")");
Romain Guy13922e02009-05-12 17:56:14 -07001017 long startTime = 0L;
1018 if (Config.DEBUG && ViewDebug.profileLayout) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001019 startTime = SystemClock.elapsedRealtime();
1020 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001021 host.layout(0, 0, host.mMeasuredWidth, host.mMeasuredHeight);
1022
Romain Guy13922e02009-05-12 17:56:14 -07001023 if (Config.DEBUG && ViewDebug.consistencyCheckEnabled) {
1024 if (!host.dispatchConsistencyCheck(ViewDebug.CONSISTENCY_LAYOUT)) {
1025 throw new IllegalStateException("The view hierarchy is an inconsistent state,"
1026 + "please refer to the logs with the tag "
1027 + ViewDebug.CONSISTENCY_LOG_TAG + " for more infomation.");
1028 }
1029 }
1030
1031 if (Config.DEBUG && ViewDebug.profileLayout) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001032 EventLog.writeEvent(60001, SystemClock.elapsedRealtime() - startTime);
1033 }
1034
1035 // By this point all views have been sized and positionned
1036 // We can compute the transparent area
1037
1038 if ((host.mPrivateFlags & View.REQUEST_TRANSPARENT_REGIONS) != 0) {
1039 // start out transparent
1040 // TODO: AVOID THAT CALL BY CACHING THE RESULT?
1041 host.getLocationInWindow(mTmpLocation);
1042 mTransparentRegion.set(mTmpLocation[0], mTmpLocation[1],
1043 mTmpLocation[0] + host.mRight - host.mLeft,
1044 mTmpLocation[1] + host.mBottom - host.mTop);
1045
1046 host.gatherTransparentRegion(mTransparentRegion);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001047 if (mTranslator != null) {
1048 mTranslator.translateRegionInWindowToScreen(mTransparentRegion);
1049 }
1050
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001051 if (!mTransparentRegion.equals(mPreviousTransparentRegion)) {
1052 mPreviousTransparentRegion.set(mTransparentRegion);
1053 // reconfigure window manager
1054 try {
1055 sWindowSession.setTransparentRegion(mWindow, mTransparentRegion);
1056 } catch (RemoteException e) {
1057 }
1058 }
1059 }
1060
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001061 if (DBG) {
1062 System.out.println("======================================");
1063 System.out.println("performTraversals -- after setFrame");
1064 host.debug();
1065 }
1066 }
1067
1068 if (triggerGlobalLayoutListener) {
1069 attachInfo.mRecomputeGlobalAttributes = false;
1070 attachInfo.mTreeObserver.dispatchOnGlobalLayout();
1071 }
1072
1073 if (computesInternalInsets) {
1074 ViewTreeObserver.InternalInsetsInfo insets = attachInfo.mGivenInternalInsets;
1075 final Rect givenContent = attachInfo.mGivenInternalInsets.contentInsets;
1076 final Rect givenVisible = attachInfo.mGivenInternalInsets.visibleInsets;
1077 givenContent.left = givenContent.top = givenContent.right
1078 = givenContent.bottom = givenVisible.left = givenVisible.top
1079 = givenVisible.right = givenVisible.bottom = 0;
1080 attachInfo.mTreeObserver.dispatchOnComputeInternalInsets(insets);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001081 Rect contentInsets = insets.contentInsets;
1082 Rect visibleInsets = insets.visibleInsets;
1083 if (mTranslator != null) {
1084 contentInsets = mTranslator.getTranslatedContentInsets(contentInsets);
1085 visibleInsets = mTranslator.getTranslatedVisbileInsets(visibleInsets);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001086 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001087 if (insetsPending || !mLastGivenInsets.equals(insets)) {
1088 mLastGivenInsets.set(insets);
1089 try {
1090 sWindowSession.setInsets(mWindow, insets.mTouchableInsets,
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001091 contentInsets, visibleInsets);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001092 } catch (RemoteException e) {
1093 }
1094 }
1095 }
Romain Guy8506ab42009-06-11 17:35:47 -07001096
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001097 if (mFirst) {
1098 // handle first focus request
1099 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: mView.hasFocus()="
1100 + mView.hasFocus());
1101 if (mView != null) {
1102 if (!mView.hasFocus()) {
1103 mView.requestFocus(View.FOCUS_FORWARD);
1104 mFocusedView = mRealFocusedView = mView.findFocus();
1105 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: requested focused view="
1106 + mFocusedView);
1107 } else {
1108 mRealFocusedView = mView.findFocus();
1109 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: existing focused view="
1110 + mRealFocusedView);
1111 }
1112 }
1113 }
1114
1115 mFirst = false;
1116 mWillDrawSoon = false;
1117 mNewSurfaceNeeded = false;
1118 mViewVisibility = viewVisibility;
1119
1120 if (mAttachInfo.mHasWindowFocus) {
1121 final boolean imTarget = WindowManager.LayoutParams
1122 .mayUseInputMethod(mWindowAttributes.flags);
1123 if (imTarget != mLastWasImTarget) {
1124 mLastWasImTarget = imTarget;
1125 InputMethodManager imm = InputMethodManager.peekInstance();
1126 if (imm != null && imTarget) {
1127 imm.startGettingWindowFocus(mView);
1128 imm.onWindowFocus(mView, mView.findFocus(),
1129 mWindowAttributes.softInputMode,
1130 !mHasHadWindowFocus, mWindowAttributes.flags);
1131 }
1132 }
1133 }
Romain Guy8506ab42009-06-11 17:35:47 -07001134
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001135 boolean cancelDraw = attachInfo.mTreeObserver.dispatchOnPreDraw();
1136
1137 if (!cancelDraw && !newSurface) {
1138 mFullRedrawNeeded = false;
1139 draw(fullRedrawNeeded);
1140
1141 if ((relayoutResult&WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0
1142 || mReportNextDraw) {
1143 if (LOCAL_LOGV) {
1144 Log.v("ViewRoot", "FINISHED DRAWING: " + mWindowAttributes.getTitle());
1145 }
1146 mReportNextDraw = false;
1147 try {
1148 sWindowSession.finishDrawing(mWindow);
1149 } catch (RemoteException e) {
1150 }
1151 }
1152 } else {
1153 // We were supposed to report when we are done drawing. Since we canceled the
1154 // draw, remember it here.
1155 if ((relayoutResult&WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0) {
1156 mReportNextDraw = true;
1157 }
1158 if (fullRedrawNeeded) {
1159 mFullRedrawNeeded = true;
1160 }
1161 // Try again
1162 scheduleTraversals();
1163 }
1164 }
1165
1166 public void requestTransparentRegion(View child) {
1167 // the test below should not fail unless someone is messing with us
1168 checkThread();
1169 if (mView == child) {
1170 mView.mPrivateFlags |= View.REQUEST_TRANSPARENT_REGIONS;
1171 // Need to make sure we re-evaluate the window attributes next
1172 // time around, to ensure the window has the correct format.
1173 mWindowAttributesChanged = true;
1174 }
1175 }
1176
1177 /**
1178 * Figures out the measure spec for the root view in a window based on it's
1179 * layout params.
1180 *
1181 * @param windowSize
1182 * The available width or height of the window
1183 *
1184 * @param rootDimension
1185 * The layout params for one dimension (width or height) of the
1186 * window.
1187 *
1188 * @return The measure spec to use to measure the root view.
1189 */
1190 private int getRootMeasureSpec(int windowSize, int rootDimension) {
1191 int measureSpec;
1192 switch (rootDimension) {
1193
Romain Guy980a9382010-01-08 15:06:28 -08001194 case ViewGroup.LayoutParams.MATCH_PARENT:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001195 // Window can't resize. Force root view to be windowSize.
1196 measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.EXACTLY);
1197 break;
1198 case ViewGroup.LayoutParams.WRAP_CONTENT:
1199 // Window can resize. Set max size for root view.
1200 measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.AT_MOST);
1201 break;
1202 default:
1203 // Window wants to be an exact size. Force root view to be that size.
1204 measureSpec = MeasureSpec.makeMeasureSpec(rootDimension, MeasureSpec.EXACTLY);
1205 break;
1206 }
1207 return measureSpec;
1208 }
1209
1210 private void draw(boolean fullRedrawNeeded) {
1211 Surface surface = mSurface;
1212 if (surface == null || !surface.isValid()) {
1213 return;
1214 }
1215
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001216 if (!sFirstDrawComplete) {
1217 synchronized (sFirstDrawHandlers) {
1218 sFirstDrawComplete = true;
Romain Guy812ccbe2010-06-01 14:07:24 -07001219 final int count = sFirstDrawHandlers.size();
1220 for (int i = 0; i< count; i++) {
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001221 post(sFirstDrawHandlers.get(i));
1222 }
1223 }
1224 }
1225
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001226 scrollToRectOrFocus(null, false);
1227
1228 if (mAttachInfo.mViewScrollChanged) {
1229 mAttachInfo.mViewScrollChanged = false;
1230 mAttachInfo.mTreeObserver.dispatchOnScrollChanged();
1231 }
Romain Guy8506ab42009-06-11 17:35:47 -07001232
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001233 int yoff;
Romain Guy5bcdff42009-05-14 21:27:18 -07001234 final boolean scrolling = mScroller != null && mScroller.computeScrollOffset();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001235 if (scrolling) {
1236 yoff = mScroller.getCurrY();
1237 } else {
1238 yoff = mScrollY;
1239 }
1240 if (mCurScrollY != yoff) {
1241 mCurScrollY = yoff;
1242 fullRedrawNeeded = true;
1243 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001244 float appScale = mAttachInfo.mApplicationScale;
1245 boolean scalingRequired = mAttachInfo.mScalingRequired;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001246
1247 Rect dirty = mDirty;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001248 if (mSurfaceHolder != null) {
1249 // The app owns the surface, we won't draw.
1250 dirty.setEmpty();
1251 return;
1252 }
1253
Romain Guy2d614592010-06-09 18:21:37 -07001254 if (mHwRenderer != null && mHwRenderer.isEnabled()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001255 if (!dirty.isEmpty()) {
Romain Guy2d614592010-06-09 18:21:37 -07001256 mHwRenderer.draw(mView, mAttachInfo, mTranslator, yoff, scalingRequired);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001257 }
Romain Guy812ccbe2010-06-01 14:07:24 -07001258
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001259 if (scrolling) {
1260 mFullRedrawNeeded = true;
1261 scheduleTraversals();
1262 }
Romain Guy812ccbe2010-06-01 14:07:24 -07001263
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001264 return;
1265 }
1266
Romain Guy5bcdff42009-05-14 21:27:18 -07001267 if (fullRedrawNeeded) {
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001268 mAttachInfo.mIgnoreDirtyState = true;
Mitsuru Oshima61324e52009-07-21 15:40:36 -07001269 dirty.union(0, 0, (int) (mWidth * appScale + 0.5f), (int) (mHeight * appScale + 0.5f));
Romain Guy5bcdff42009-05-14 21:27:18 -07001270 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001271
1272 if (DEBUG_ORIENTATION || DEBUG_DRAW) {
1273 Log.v("ViewRoot", "Draw " + mView + "/"
1274 + mWindowAttributes.getTitle()
1275 + ": dirty={" + dirty.left + "," + dirty.top
1276 + "," + dirty.right + "," + dirty.bottom + "} surface="
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001277 + surface + " surface.isValid()=" + surface.isValid() + ", appScale:" +
1278 appScale + ", width=" + mWidth + ", height=" + mHeight);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001279 }
1280
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001281 if (!dirty.isEmpty() || mIsAnimating) {
1282 Canvas canvas;
1283 try {
1284 int left = dirty.left;
1285 int top = dirty.top;
1286 int right = dirty.right;
1287 int bottom = dirty.bottom;
1288 canvas = surface.lockCanvas(dirty);
Romain Guy5bcdff42009-05-14 21:27:18 -07001289
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001290 if (left != dirty.left || top != dirty.top || right != dirty.right ||
1291 bottom != dirty.bottom) {
1292 mAttachInfo.mIgnoreDirtyState = true;
1293 }
1294
1295 // TODO: Do this in native
1296 canvas.setDensity(mDensity);
1297 } catch (Surface.OutOfResourcesException e) {
1298 Log.e("ViewRoot", "OutOfResourcesException locking surface", e);
1299 // TODO: we should ask the window manager to do something!
1300 // for now we just do nothing
1301 return;
1302 } catch (IllegalArgumentException e) {
1303 Log.e("ViewRoot", "IllegalArgumentException locking surface", e);
1304 // TODO: we should ask the window manager to do something!
1305 // for now we just do nothing
1306 return;
Romain Guy5bcdff42009-05-14 21:27:18 -07001307 }
1308
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001309 try {
1310 if (!dirty.isEmpty() || mIsAnimating) {
1311 long startTime = 0L;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001312
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001313 if (DEBUG_ORIENTATION || DEBUG_DRAW) {
1314 Log.v("ViewRoot", "Surface " + surface + " drawing to bitmap w="
1315 + canvas.getWidth() + ", h=" + canvas.getHeight());
1316 //canvas.drawARGB(255, 255, 0, 0);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001317 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001318
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001319 if (Config.DEBUG && ViewDebug.profileDrawing) {
1320 startTime = SystemClock.elapsedRealtime();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001321 }
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001322
1323 // If this bitmap's format includes an alpha channel, we
1324 // need to clear it before drawing so that the child will
1325 // properly re-composite its drawing on a transparent
1326 // background. This automatically respects the clip/dirty region
1327 // or
1328 // If we are applying an offset, we need to clear the area
1329 // where the offset doesn't appear to avoid having garbage
1330 // left in the blank areas.
1331 if (!canvas.isOpaque() || yoff != 0) {
1332 canvas.drawColor(0, PorterDuff.Mode.CLEAR);
1333 }
1334
1335 dirty.setEmpty();
1336 mIsAnimating = false;
1337 mAttachInfo.mDrawingTime = SystemClock.uptimeMillis();
1338 mView.mPrivateFlags |= View.DRAWN;
1339
1340 if (DEBUG_DRAW) {
1341 Context cxt = mView.getContext();
1342 Log.i(TAG, "Drawing: package:" + cxt.getPackageName() +
1343 ", metrics=" + cxt.getResources().getDisplayMetrics() +
1344 ", compatibilityInfo=" + cxt.getResources().getCompatibilityInfo());
1345 }
1346 int saveCount = canvas.save(Canvas.MATRIX_SAVE_FLAG);
1347 try {
1348 canvas.translate(0, -yoff);
1349 if (mTranslator != null) {
1350 mTranslator.translateCanvas(canvas);
1351 }
1352 canvas.setScreenDensity(scalingRequired
1353 ? DisplayMetrics.DENSITY_DEVICE : 0);
1354 mView.draw(canvas);
1355 } finally {
1356 mAttachInfo.mIgnoreDirtyState = false;
1357 canvas.restoreToCount(saveCount);
1358 }
1359
1360 if (Config.DEBUG && ViewDebug.consistencyCheckEnabled) {
1361 mView.dispatchConsistencyCheck(ViewDebug.CONSISTENCY_DRAWING);
1362 }
1363
1364 if (SHOW_FPS || Config.DEBUG && ViewDebug.showFps) {
1365 int now = (int)SystemClock.elapsedRealtime();
1366 if (sDrawTime != 0) {
1367 nativeShowFPS(canvas, now - sDrawTime);
1368 }
1369 sDrawTime = now;
1370 }
1371
1372 if (Config.DEBUG && ViewDebug.profileDrawing) {
1373 EventLog.writeEvent(60000, SystemClock.elapsedRealtime() - startTime);
1374 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001375 }
1376
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001377 } finally {
1378 surface.unlockCanvasAndPost(canvas);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001379 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001380 }
1381
1382 if (LOCAL_LOGV) {
1383 Log.v("ViewRoot", "Surface " + surface + " unlockCanvasAndPost");
1384 }
Romain Guy8506ab42009-06-11 17:35:47 -07001385
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001386 if (scrolling) {
1387 mFullRedrawNeeded = true;
1388 scheduleTraversals();
1389 }
1390 }
1391
1392 boolean scrollToRectOrFocus(Rect rectangle, boolean immediate) {
1393 final View.AttachInfo attachInfo = mAttachInfo;
1394 final Rect ci = attachInfo.mContentInsets;
1395 final Rect vi = attachInfo.mVisibleInsets;
1396 int scrollY = 0;
1397 boolean handled = false;
Romain Guy8506ab42009-06-11 17:35:47 -07001398
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001399 if (vi.left > ci.left || vi.top > ci.top
1400 || vi.right > ci.right || vi.bottom > ci.bottom) {
1401 // We'll assume that we aren't going to change the scroll
1402 // offset, since we want to avoid that unless it is actually
1403 // going to make the focus visible... otherwise we scroll
1404 // all over the place.
1405 scrollY = mScrollY;
1406 // We can be called for two different situations: during a draw,
1407 // to update the scroll position if the focus has changed (in which
1408 // case 'rectangle' is null), or in response to a
1409 // requestChildRectangleOnScreen() call (in which case 'rectangle'
1410 // is non-null and we just want to scroll to whatever that
1411 // rectangle is).
1412 View focus = mRealFocusedView;
Romain Guye8b16522009-07-14 13:06:42 -07001413
1414 // When in touch mode, focus points to the previously focused view,
1415 // which may have been removed from the view hierarchy. The following
Joe Onoratob71193b2009-11-24 18:34:42 -05001416 // line checks whether the view is still in our hierarchy.
1417 if (focus == null || focus.mAttachInfo != mAttachInfo) {
Romain Guye8b16522009-07-14 13:06:42 -07001418 mRealFocusedView = null;
1419 return false;
1420 }
1421
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001422 if (focus != mLastScrolledFocus) {
1423 // If the focus has changed, then ignore any requests to scroll
1424 // to a rectangle; first we want to make sure the entire focus
1425 // view is visible.
1426 rectangle = null;
1427 }
1428 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Eval scroll: focus=" + focus
1429 + " rectangle=" + rectangle + " ci=" + ci
1430 + " vi=" + vi);
1431 if (focus == mLastScrolledFocus && !mScrollMayChange
1432 && rectangle == null) {
1433 // Optimization: if the focus hasn't changed since last
1434 // time, and no layout has happened, then just leave things
1435 // as they are.
1436 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Keeping scroll y="
1437 + mScrollY + " vi=" + vi.toShortString());
1438 } else if (focus != null) {
1439 // We need to determine if the currently focused view is
1440 // within the visible part of the window and, if not, apply
1441 // a pan so it can be seen.
1442 mLastScrolledFocus = focus;
1443 mScrollMayChange = false;
1444 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Need to scroll?");
1445 // Try to find the rectangle from the focus view.
1446 if (focus.getGlobalVisibleRect(mVisRect, null)) {
1447 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Root w="
1448 + mView.getWidth() + " h=" + mView.getHeight()
1449 + " ci=" + ci.toShortString()
1450 + " vi=" + vi.toShortString());
1451 if (rectangle == null) {
1452 focus.getFocusedRect(mTempRect);
1453 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Focus " + focus
1454 + ": focusRect=" + mTempRect.toShortString());
Dianne Hackborn1c6a8942010-03-23 16:34:20 -07001455 if (mView instanceof ViewGroup) {
1456 ((ViewGroup) mView).offsetDescendantRectToMyCoords(
1457 focus, mTempRect);
1458 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001459 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1460 "Focus in window: focusRect="
1461 + mTempRect.toShortString()
1462 + " visRect=" + mVisRect.toShortString());
1463 } else {
1464 mTempRect.set(rectangle);
1465 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1466 "Request scroll to rect: "
1467 + mTempRect.toShortString()
1468 + " visRect=" + mVisRect.toShortString());
1469 }
1470 if (mTempRect.intersect(mVisRect)) {
1471 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1472 "Focus window visible rect: "
1473 + mTempRect.toShortString());
1474 if (mTempRect.height() >
1475 (mView.getHeight()-vi.top-vi.bottom)) {
1476 // If the focus simply is not going to fit, then
1477 // best is probably just to leave things as-is.
1478 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1479 "Too tall; leaving scrollY=" + scrollY);
1480 } else if ((mTempRect.top-scrollY) < vi.top) {
1481 scrollY -= vi.top - (mTempRect.top-scrollY);
1482 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1483 "Top covered; scrollY=" + scrollY);
1484 } else if ((mTempRect.bottom-scrollY)
1485 > (mView.getHeight()-vi.bottom)) {
1486 scrollY += (mTempRect.bottom-scrollY)
1487 - (mView.getHeight()-vi.bottom);
1488 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1489 "Bottom covered; scrollY=" + scrollY);
1490 }
1491 handled = true;
1492 }
1493 }
1494 }
1495 }
Romain Guy8506ab42009-06-11 17:35:47 -07001496
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001497 if (scrollY != mScrollY) {
1498 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Pan scroll changed: old="
1499 + mScrollY + " , new=" + scrollY);
1500 if (!immediate) {
1501 if (mScroller == null) {
1502 mScroller = new Scroller(mView.getContext());
1503 }
1504 mScroller.startScroll(0, mScrollY, 0, scrollY-mScrollY);
1505 } else if (mScroller != null) {
1506 mScroller.abortAnimation();
1507 }
1508 mScrollY = scrollY;
1509 }
Romain Guy8506ab42009-06-11 17:35:47 -07001510
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001511 return handled;
1512 }
Romain Guy8506ab42009-06-11 17:35:47 -07001513
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001514 public void requestChildFocus(View child, View focused) {
1515 checkThread();
1516 if (mFocusedView != focused) {
1517 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(mFocusedView, focused);
1518 scheduleTraversals();
1519 }
1520 mFocusedView = mRealFocusedView = focused;
1521 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Request child focus: focus now "
1522 + mFocusedView);
1523 }
1524
1525 public void clearChildFocus(View child) {
1526 checkThread();
1527
1528 View oldFocus = mFocusedView;
1529
1530 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Clearing child focus");
1531 mFocusedView = mRealFocusedView = null;
1532 if (mView != null && !mView.hasFocus()) {
1533 // If a view gets the focus, the listener will be invoked from requestChildFocus()
1534 if (!mView.requestFocus(View.FOCUS_FORWARD)) {
1535 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
1536 }
1537 } else if (oldFocus != null) {
1538 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
1539 }
1540 }
1541
1542
1543 public void focusableViewAvailable(View v) {
1544 checkThread();
1545
1546 if (mView != null && !mView.hasFocus()) {
1547 v.requestFocus();
1548 } else {
1549 // the one case where will transfer focus away from the current one
1550 // is if the current view is a view group that prefers to give focus
1551 // to its children first AND the view is a descendant of it.
1552 mFocusedView = mView.findFocus();
1553 boolean descendantsHaveDibsOnFocus =
1554 (mFocusedView instanceof ViewGroup) &&
1555 (((ViewGroup) mFocusedView).getDescendantFocusability() ==
1556 ViewGroup.FOCUS_AFTER_DESCENDANTS);
1557 if (descendantsHaveDibsOnFocus && isViewDescendantOf(v, mFocusedView)) {
1558 // If a view gets the focus, the listener will be invoked from requestChildFocus()
1559 v.requestFocus();
1560 }
1561 }
1562 }
1563
1564 public void recomputeViewAttributes(View child) {
1565 checkThread();
1566 if (mView == child) {
1567 mAttachInfo.mRecomputeGlobalAttributes = true;
1568 if (!mWillDrawSoon) {
1569 scheduleTraversals();
1570 }
1571 }
1572 }
1573
1574 void dispatchDetachedFromWindow() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001575 if (mView != null) {
1576 mView.dispatchDetachedFromWindow();
1577 }
1578
1579 mView = null;
1580 mAttachInfo.mRootView = null;
Mathias Agopian5583dc62009-07-09 16:28:11 -07001581 mAttachInfo.mSurface = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001582
Romain Guy812ccbe2010-06-01 14:07:24 -07001583 if (mHwRenderer != null) {
Romain Guy2d614592010-06-09 18:21:37 -07001584 mHwRenderer.destroy();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001585 }
Dianne Hackborn0586a1b2009-09-06 21:08:27 -07001586 mSurface.release();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001587
Jeff Brown46b9ac02010-04-22 18:58:52 -07001588 if (WindowManagerPolicy.ENABLE_NATIVE_INPUT_DISPATCH) {
1589 if (mInputChannel != null) {
1590 InputQueue.unregisterInputChannel(mInputChannel);
1591 mInputChannel.dispose();
1592 mInputChannel = null;
1593 }
1594 }
1595
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001596 try {
1597 sWindowSession.remove(mWindow);
1598 } catch (RemoteException e) {
1599 }
1600 }
Romain Guy8506ab42009-06-11 17:35:47 -07001601
Dianne Hackborn694f79b2010-03-17 19:44:59 -07001602 void updateConfiguration(Configuration config, boolean force) {
1603 if (DEBUG_CONFIGURATION) Log.v(TAG,
1604 "Applying new config to window "
1605 + mWindowAttributes.getTitle()
1606 + ": " + config);
1607 synchronized (sConfigCallbacks) {
1608 for (int i=sConfigCallbacks.size()-1; i>=0; i--) {
1609 sConfigCallbacks.get(i).onConfigurationChanged(config);
1610 }
1611 }
1612 if (mView != null) {
1613 // At this point the resources have been updated to
1614 // have the most recent config, whatever that is. Use
1615 // the on in them which may be newer.
1616 if (mView != null) {
1617 config = mView.getResources().getConfiguration();
1618 }
1619 if (force || mLastConfiguration.diff(config) != 0) {
1620 mLastConfiguration.setTo(config);
1621 mView.dispatchConfigurationChanged(config);
1622 }
1623 }
1624 }
1625
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001626 /**
1627 * Return true if child is an ancestor of parent, (or equal to the parent).
1628 */
1629 private static boolean isViewDescendantOf(View child, View parent) {
1630 if (child == parent) {
1631 return true;
1632 }
1633
1634 final ViewParent theParent = child.getParent();
1635 return (theParent instanceof ViewGroup) && isViewDescendantOf((View) theParent, parent);
1636 }
1637
Romain Guycdb86672010-03-18 18:54:50 -07001638 private static void forceLayout(View view) {
1639 view.forceLayout();
1640 if (view instanceof ViewGroup) {
1641 ViewGroup group = (ViewGroup) view;
1642 final int count = group.getChildCount();
1643 for (int i = 0; i < count; i++) {
1644 forceLayout(group.getChildAt(i));
1645 }
1646 }
1647 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001648
1649 public final static int DO_TRAVERSAL = 1000;
1650 public final static int DIE = 1001;
1651 public final static int RESIZED = 1002;
1652 public final static int RESIZED_REPORT = 1003;
1653 public final static int WINDOW_FOCUS_CHANGED = 1004;
1654 public final static int DISPATCH_KEY = 1005;
1655 public final static int DISPATCH_POINTER = 1006;
1656 public final static int DISPATCH_TRACKBALL = 1007;
1657 public final static int DISPATCH_APP_VISIBILITY = 1008;
1658 public final static int DISPATCH_GET_NEW_SURFACE = 1009;
1659 public final static int FINISHED_EVENT = 1010;
1660 public final static int DISPATCH_KEY_FROM_IME = 1011;
1661 public final static int FINISH_INPUT_CONNECTION = 1012;
1662 public final static int CHECK_FOCUS = 1013;
Dianne Hackbornffa42482009-09-23 22:20:11 -07001663 public final static int CLOSE_SYSTEM_DIALOGS = 1014;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001664
1665 @Override
1666 public void handleMessage(Message msg) {
1667 switch (msg.what) {
1668 case View.AttachInfo.INVALIDATE_MSG:
1669 ((View) msg.obj).invalidate();
1670 break;
1671 case View.AttachInfo.INVALIDATE_RECT_MSG:
1672 final View.AttachInfo.InvalidateInfo info = (View.AttachInfo.InvalidateInfo) msg.obj;
1673 info.target.invalidate(info.left, info.top, info.right, info.bottom);
1674 info.release();
1675 break;
1676 case DO_TRAVERSAL:
1677 if (mProfile) {
1678 Debug.startMethodTracing("ViewRoot");
1679 }
1680
1681 performTraversals();
1682
1683 if (mProfile) {
1684 Debug.stopMethodTracing();
1685 mProfile = false;
1686 }
1687 break;
1688 case FINISHED_EVENT:
1689 handleFinishedEvent(msg.arg1, msg.arg2 != 0);
1690 break;
1691 case DISPATCH_KEY:
1692 if (LOCAL_LOGV) Log.v(
1693 "ViewRoot", "Dispatching key "
1694 + msg.obj + " to " + mView);
1695 deliverKeyEvent((KeyEvent)msg.obj, true);
1696 break;
The Android Open Source Project10592532009-03-18 17:39:46 -07001697 case DISPATCH_POINTER: {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001698 MotionEvent event = (MotionEvent)msg.obj;
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07001699 boolean callWhenDone = msg.arg1 != 0;
1700
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001701 if (event == null) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07001702 long timeBeforeGettingEvents;
1703 if (MEASURE_LATENCY) {
1704 timeBeforeGettingEvents = System.nanoTime();
1705 }
Michael Chan53071d62009-05-13 17:29:48 -07001706
Jeff Brown46b9ac02010-04-22 18:58:52 -07001707 event = getPendingPointerMotionEvent();
Michael Chan53071d62009-05-13 17:29:48 -07001708
Jeff Brown46b9ac02010-04-22 18:58:52 -07001709 if (MEASURE_LATENCY && event != null) {
Jeff Brown8e03b752010-06-13 19:16:55 -07001710 lt.sample("9 Client got events ",
1711 System.nanoTime() - event.getEventTimeNano());
1712 lt.sample("8 Client getting events ",
1713 timeBeforeGettingEvents - event.getEventTimeNano());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001714 }
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07001715 callWhenDone = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001716 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001717 if (event != null && mTranslator != null) {
1718 mTranslator.translateEventInScreenToAppWindow(event);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001719 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001720 try {
1721 boolean handled;
1722 if (mView != null && mAdded && event != null) {
1723
1724 // enter touch mode on the down
1725 boolean isDown = event.getAction() == MotionEvent.ACTION_DOWN;
1726 if (isDown) {
1727 ensureTouchMode(true);
1728 }
1729 if(Config.LOGV) {
1730 captureMotionLog("captureDispatchPointer", event);
1731 }
Dianne Hackbornddca3ee2009-07-23 19:01:31 -07001732 if (mCurScrollY != 0) {
1733 event.offsetLocation(0, mCurScrollY);
1734 }
Michael Chan53071d62009-05-13 17:29:48 -07001735 if (MEASURE_LATENCY) {
Romain Guy812ccbe2010-06-01 14:07:24 -07001736 lt.sample("A Dispatching TouchEvents",
1737 System.nanoTime() - event.getEventTimeNano());
Michael Chan53071d62009-05-13 17:29:48 -07001738 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001739 handled = mView.dispatchTouchEvent(event);
Michael Chan53071d62009-05-13 17:29:48 -07001740 if (MEASURE_LATENCY) {
Romain Guy812ccbe2010-06-01 14:07:24 -07001741 lt.sample("B Dispatched TouchEvents ",
1742 System.nanoTime() - event.getEventTimeNano());
Michael Chan53071d62009-05-13 17:29:48 -07001743 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001744 if (!handled && isDown) {
1745 int edgeSlop = mViewConfiguration.getScaledEdgeSlop();
1746
1747 final int edgeFlags = event.getEdgeFlags();
1748 int direction = View.FOCUS_UP;
1749 int x = (int)event.getX();
1750 int y = (int)event.getY();
1751 final int[] deltas = new int[2];
1752
1753 if ((edgeFlags & MotionEvent.EDGE_TOP) != 0) {
1754 direction = View.FOCUS_DOWN;
1755 if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
1756 deltas[0] = edgeSlop;
1757 x += edgeSlop;
1758 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
1759 deltas[0] = -edgeSlop;
1760 x -= edgeSlop;
1761 }
1762 } else if ((edgeFlags & MotionEvent.EDGE_BOTTOM) != 0) {
1763 direction = View.FOCUS_UP;
1764 if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
1765 deltas[0] = edgeSlop;
1766 x += edgeSlop;
1767 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
1768 deltas[0] = -edgeSlop;
1769 x -= edgeSlop;
1770 }
1771 } else if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
1772 direction = View.FOCUS_RIGHT;
1773 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
1774 direction = View.FOCUS_LEFT;
1775 }
1776
1777 if (edgeFlags != 0 && mView instanceof ViewGroup) {
1778 View nearest = FocusFinder.getInstance().findNearestTouchable(
1779 ((ViewGroup) mView), x, y, direction, deltas);
1780 if (nearest != null) {
1781 event.offsetLocation(deltas[0], deltas[1]);
1782 event.setEdgeFlags(0);
1783 mView.dispatchTouchEvent(event);
1784 }
1785 }
1786 }
1787 }
1788 } finally {
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07001789 if (callWhenDone) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07001790 finishMotionEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001791 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07001792 recycleMotionEvent(event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001793 if (LOCAL_LOGV || WATCH_POINTER) Log.i(TAG, "Done dispatching!");
1794 // Let the exception fall through -- the looper will catch
1795 // it and take care of the bad app for us.
1796 }
The Android Open Source Project10592532009-03-18 17:39:46 -07001797 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001798 case DISPATCH_TRACKBALL:
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07001799 deliverTrackballEvent((MotionEvent)msg.obj, msg.arg1 != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001800 break;
1801 case DISPATCH_APP_VISIBILITY:
1802 handleAppVisibility(msg.arg1 != 0);
1803 break;
1804 case DISPATCH_GET_NEW_SURFACE:
1805 handleGetNewSurface();
1806 break;
1807 case RESIZED:
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001808 ResizedInfo ri = (ResizedInfo)msg.obj;
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001809
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001810 if (mWinFrame.width() == msg.arg1 && mWinFrame.height() == msg.arg2
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001811 && mPendingContentInsets.equals(ri.coveredInsets)
Dianne Hackbornd49258f2010-03-26 00:44:29 -07001812 && mPendingVisibleInsets.equals(ri.visibleInsets)
1813 && ((ResizedInfo)msg.obj).newConfig == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001814 break;
1815 }
1816 // fall through...
1817 case RESIZED_REPORT:
1818 if (mAdded) {
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001819 Configuration config = ((ResizedInfo)msg.obj).newConfig;
1820 if (config != null) {
Dianne Hackborn694f79b2010-03-17 19:44:59 -07001821 updateConfiguration(config, false);
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001822 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001823 mWinFrame.left = 0;
1824 mWinFrame.right = msg.arg1;
1825 mWinFrame.top = 0;
1826 mWinFrame.bottom = msg.arg2;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001827 mPendingContentInsets.set(((ResizedInfo)msg.obj).coveredInsets);
1828 mPendingVisibleInsets.set(((ResizedInfo)msg.obj).visibleInsets);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001829 if (msg.what == RESIZED_REPORT) {
1830 mReportNextDraw = true;
1831 }
Romain Guycdb86672010-03-18 18:54:50 -07001832
1833 if (mView != null) {
1834 forceLayout(mView);
1835 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001836 requestLayout();
1837 }
1838 break;
1839 case WINDOW_FOCUS_CHANGED: {
1840 if (mAdded) {
1841 boolean hasWindowFocus = msg.arg1 != 0;
1842 mAttachInfo.mHasWindowFocus = hasWindowFocus;
1843 if (hasWindowFocus) {
1844 boolean inTouchMode = msg.arg2 != 0;
Romain Guy2d4cff62010-04-09 15:39:00 -07001845 ensureTouchModeLocally(inTouchMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001846
Romain Guy812ccbe2010-06-01 14:07:24 -07001847 if (mHwRenderer != null) {
Romain Guy2d614592010-06-09 18:21:37 -07001848 mHwRenderer.initializeIfNeeded(mWidth, mHeight, mAttachInfo, mHolder);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001849 }
1850 }
Romain Guy8506ab42009-06-11 17:35:47 -07001851
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001852 mLastWasImTarget = WindowManager.LayoutParams
1853 .mayUseInputMethod(mWindowAttributes.flags);
Romain Guy8506ab42009-06-11 17:35:47 -07001854
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001855 InputMethodManager imm = InputMethodManager.peekInstance();
1856 if (mView != null) {
1857 if (hasWindowFocus && imm != null && mLastWasImTarget) {
1858 imm.startGettingWindowFocus(mView);
1859 }
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07001860 mAttachInfo.mKeyDispatchState.reset();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001861 mView.dispatchWindowFocusChanged(hasWindowFocus);
1862 }
svetoslavganov75986cf2009-05-14 22:28:01 -07001863
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001864 // Note: must be done after the focus change callbacks,
1865 // so all of the view state is set up correctly.
1866 if (hasWindowFocus) {
1867 if (imm != null && mLastWasImTarget) {
1868 imm.onWindowFocus(mView, mView.findFocus(),
1869 mWindowAttributes.softInputMode,
1870 !mHasHadWindowFocus, mWindowAttributes.flags);
1871 }
1872 // Clear the forward bit. We can just do this directly, since
1873 // the window manager doesn't care about it.
1874 mWindowAttributes.softInputMode &=
1875 ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
1876 ((WindowManager.LayoutParams)mView.getLayoutParams())
1877 .softInputMode &=
1878 ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
1879 mHasHadWindowFocus = true;
1880 }
svetoslavganov75986cf2009-05-14 22:28:01 -07001881
1882 if (hasWindowFocus && mView != null) {
1883 sendAccessibilityEvents();
1884 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001885 }
1886 } break;
1887 case DIE:
Dianne Hackborn94d69142009-09-28 22:14:42 -07001888 doDie();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001889 break;
The Android Open Source Project10592532009-03-18 17:39:46 -07001890 case DISPATCH_KEY_FROM_IME: {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001891 if (LOCAL_LOGV) Log.v(
1892 "ViewRoot", "Dispatching key "
1893 + msg.obj + " from IME to " + mView);
The Android Open Source Project10592532009-03-18 17:39:46 -07001894 KeyEvent event = (KeyEvent)msg.obj;
1895 if ((event.getFlags()&KeyEvent.FLAG_FROM_SYSTEM) != 0) {
1896 // The IME is trying to say this event is from the
1897 // system! Bad bad bad!
Romain Guy812ccbe2010-06-01 14:07:24 -07001898 event = KeyEvent.changeFlags(event, event.getFlags() & ~KeyEvent.FLAG_FROM_SYSTEM);
The Android Open Source Project10592532009-03-18 17:39:46 -07001899 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001900 deliverKeyEventToViewHierarchy((KeyEvent)msg.obj, false);
The Android Open Source Project10592532009-03-18 17:39:46 -07001901 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001902 case FINISH_INPUT_CONNECTION: {
1903 InputMethodManager imm = InputMethodManager.peekInstance();
1904 if (imm != null) {
1905 imm.reportFinishInputConnection((InputConnection)msg.obj);
1906 }
1907 } break;
1908 case CHECK_FOCUS: {
1909 InputMethodManager imm = InputMethodManager.peekInstance();
1910 if (imm != null) {
1911 imm.checkFocus();
1912 }
1913 } break;
Dianne Hackbornffa42482009-09-23 22:20:11 -07001914 case CLOSE_SYSTEM_DIALOGS: {
1915 if (mView != null) {
1916 mView.onCloseSystemDialogs((String)msg.obj);
1917 }
1918 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001919 }
1920 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07001921
1922 private void finishKeyEvent(KeyEvent event) {
1923 if (WindowManagerPolicy.ENABLE_NATIVE_INPUT_DISPATCH) {
1924 if (mFinishedCallback != null) {
1925 mFinishedCallback.run();
1926 mFinishedCallback = null;
1927 }
1928 } else {
1929 try {
1930 sWindowSession.finishKey(mWindow);
1931 } catch (RemoteException e) {
1932 }
1933 }
1934 }
1935
1936 private void finishMotionEvent() {
1937 if (WindowManagerPolicy.ENABLE_NATIVE_INPUT_DISPATCH) {
1938 throw new IllegalStateException("Should not be reachable with native input dispatch.");
1939 }
1940
1941 try {
1942 sWindowSession.finishKey(mWindow);
1943 } catch (RemoteException e) {
1944 }
1945 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001946
Jeff Brown46b9ac02010-04-22 18:58:52 -07001947 private void recycleMotionEvent(MotionEvent event) {
1948 if (event != null) {
1949 event.recycle();
1950 }
1951 }
1952
1953 private MotionEvent getPendingPointerMotionEvent() {
1954 if (WindowManagerPolicy.ENABLE_NATIVE_INPUT_DISPATCH) {
1955 throw new IllegalStateException("Should not be reachable with native input dispatch.");
1956 }
1957
1958 try {
1959 return sWindowSession.getPendingPointerMove(mWindow);
1960 } catch (RemoteException e) {
1961 return null;
1962 }
1963 }
1964
1965 private MotionEvent getPendingTrackballMotionEvent() {
1966 if (WindowManagerPolicy.ENABLE_NATIVE_INPUT_DISPATCH) {
1967 throw new IllegalStateException("Should not be reachable with native input dispatch.");
1968 }
1969
1970 try {
1971 return sWindowSession.getPendingTrackballMove(mWindow);
1972 } catch (RemoteException e) {
1973 return null;
1974 }
1975 }
1976
1977
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001978 /**
1979 * Something in the current window tells us we need to change the touch mode. For
1980 * example, we are not in touch mode, and the user touches the screen.
1981 *
1982 * If the touch mode has changed, tell the window manager, and handle it locally.
1983 *
1984 * @param inTouchMode Whether we want to be in touch mode.
1985 * @return True if the touch mode changed and focus changed was changed as a result
1986 */
1987 boolean ensureTouchMode(boolean inTouchMode) {
1988 if (DBG) Log.d("touchmode", "ensureTouchMode(" + inTouchMode + "), current "
1989 + "touch mode is " + mAttachInfo.mInTouchMode);
1990 if (mAttachInfo.mInTouchMode == inTouchMode) return false;
1991
1992 // tell the window manager
1993 try {
1994 sWindowSession.setInTouchMode(inTouchMode);
1995 } catch (RemoteException e) {
1996 throw new RuntimeException(e);
1997 }
1998
1999 // handle the change
Romain Guy2d4cff62010-04-09 15:39:00 -07002000 return ensureTouchModeLocally(inTouchMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002001 }
2002
2003 /**
2004 * Ensure that the touch mode for this window is set, and if it is changing,
2005 * take the appropriate action.
2006 * @param inTouchMode Whether we want to be in touch mode.
2007 * @return True if the touch mode changed and focus changed was changed as a result
2008 */
Romain Guy2d4cff62010-04-09 15:39:00 -07002009 private boolean ensureTouchModeLocally(boolean inTouchMode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002010 if (DBG) Log.d("touchmode", "ensureTouchModeLocally(" + inTouchMode + "), current "
2011 + "touch mode is " + mAttachInfo.mInTouchMode);
2012
2013 if (mAttachInfo.mInTouchMode == inTouchMode) return false;
2014
2015 mAttachInfo.mInTouchMode = inTouchMode;
2016 mAttachInfo.mTreeObserver.dispatchOnTouchModeChanged(inTouchMode);
2017
Romain Guy2d4cff62010-04-09 15:39:00 -07002018 return (inTouchMode) ? enterTouchMode() : leaveTouchMode();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002019 }
2020
2021 private boolean enterTouchMode() {
2022 if (mView != null) {
2023 if (mView.hasFocus()) {
2024 // note: not relying on mFocusedView here because this could
2025 // be when the window is first being added, and mFocused isn't
2026 // set yet.
2027 final View focused = mView.findFocus();
2028 if (focused != null && !focused.isFocusableInTouchMode()) {
2029
2030 final ViewGroup ancestorToTakeFocus =
2031 findAncestorToTakeFocusInTouchMode(focused);
2032 if (ancestorToTakeFocus != null) {
2033 // there is an ancestor that wants focus after its descendants that
2034 // is focusable in touch mode.. give it focus
2035 return ancestorToTakeFocus.requestFocus();
2036 } else {
2037 // nothing appropriate to have focus in touch mode, clear it out
2038 mView.unFocus();
2039 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(focused, null);
2040 mFocusedView = null;
2041 return true;
2042 }
2043 }
2044 }
2045 }
2046 return false;
2047 }
2048
2049
2050 /**
2051 * Find an ancestor of focused that wants focus after its descendants and is
2052 * focusable in touch mode.
2053 * @param focused The currently focused view.
2054 * @return An appropriate view, or null if no such view exists.
2055 */
2056 private ViewGroup findAncestorToTakeFocusInTouchMode(View focused) {
2057 ViewParent parent = focused.getParent();
2058 while (parent instanceof ViewGroup) {
2059 final ViewGroup vgParent = (ViewGroup) parent;
2060 if (vgParent.getDescendantFocusability() == ViewGroup.FOCUS_AFTER_DESCENDANTS
2061 && vgParent.isFocusableInTouchMode()) {
2062 return vgParent;
2063 }
2064 if (vgParent.isRootNamespace()) {
2065 return null;
2066 } else {
2067 parent = vgParent.getParent();
2068 }
2069 }
2070 return null;
2071 }
2072
2073 private boolean leaveTouchMode() {
2074 if (mView != null) {
2075 if (mView.hasFocus()) {
2076 // i learned the hard way to not trust mFocusedView :)
2077 mFocusedView = mView.findFocus();
2078 if (!(mFocusedView instanceof ViewGroup)) {
2079 // some view has focus, let it keep it
2080 return false;
2081 } else if (((ViewGroup)mFocusedView).getDescendantFocusability() !=
2082 ViewGroup.FOCUS_AFTER_DESCENDANTS) {
2083 // some view group has focus, and doesn't prefer its children
2084 // over itself for focus, so let them keep it.
2085 return false;
2086 }
2087 }
2088
2089 // find the best view to give focus to in this brave new non-touch-mode
2090 // world
2091 final View focused = focusSearch(null, View.FOCUS_DOWN);
2092 if (focused != null) {
2093 return focused.requestFocus(View.FOCUS_DOWN);
2094 }
2095 }
2096 return false;
2097 }
2098
2099
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07002100 private void deliverTrackballEvent(MotionEvent event, boolean callWhenDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002101 if (event == null) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002102 event = getPendingTrackballMotionEvent();
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07002103 callWhenDone = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002104 }
2105
2106 if (DEBUG_TRACKBALL) Log.v(TAG, "Motion event:" + event);
2107
2108 boolean handled = false;
2109 try {
2110 if (event == null) {
2111 handled = true;
2112 } else if (mView != null && mAdded) {
2113 handled = mView.dispatchTrackballEvent(event);
2114 if (!handled) {
2115 // we could do something here, like changing the focus
2116 // or something?
2117 }
2118 }
2119 } finally {
2120 if (handled) {
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07002121 if (callWhenDone) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002122 finishMotionEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002123 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002124 recycleMotionEvent(event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002125 // If we reach this, we delivered a trackball event to mView and
2126 // mView consumed it. Because we will not translate the trackball
2127 // event into a key event, touch mode will not exit, so we exit
2128 // touch mode here.
2129 ensureTouchMode(false);
2130 //noinspection ReturnInsideFinallyBlock
2131 return;
2132 }
2133 // Let the exception fall through -- the looper will catch
2134 // it and take care of the bad app for us.
2135 }
2136
2137 final TrackballAxis x = mTrackballAxisX;
2138 final TrackballAxis y = mTrackballAxisY;
2139
2140 long curTime = SystemClock.uptimeMillis();
2141 if ((mLastTrackballTime+MAX_TRACKBALL_DELAY) < curTime) {
2142 // It has been too long since the last movement,
2143 // so restart at the beginning.
2144 x.reset(0);
2145 y.reset(0);
2146 mLastTrackballTime = curTime;
2147 }
2148
2149 try {
2150 final int action = event.getAction();
2151 final int metastate = event.getMetaState();
2152 switch (action) {
2153 case MotionEvent.ACTION_DOWN:
2154 x.reset(2);
2155 y.reset(2);
2156 deliverKeyEvent(new KeyEvent(curTime, curTime,
2157 KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_CENTER,
2158 0, metastate), false);
2159 break;
2160 case MotionEvent.ACTION_UP:
2161 x.reset(2);
2162 y.reset(2);
2163 deliverKeyEvent(new KeyEvent(curTime, curTime,
2164 KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_CENTER,
2165 0, metastate), false);
2166 break;
2167 }
2168
2169 if (DEBUG_TRACKBALL) Log.v(TAG, "TB X=" + x.position + " step="
2170 + x.step + " dir=" + x.dir + " acc=" + x.acceleration
2171 + " move=" + event.getX()
2172 + " / Y=" + y.position + " step="
2173 + y.step + " dir=" + y.dir + " acc=" + y.acceleration
2174 + " move=" + event.getY());
2175 final float xOff = x.collect(event.getX(), event.getEventTime(), "X");
2176 final float yOff = y.collect(event.getY(), event.getEventTime(), "Y");
2177
2178 // Generate DPAD events based on the trackball movement.
2179 // We pick the axis that has moved the most as the direction of
2180 // the DPAD. When we generate DPAD events for one axis, then the
2181 // other axis is reset -- we don't want to perform DPAD jumps due
2182 // to slight movements in the trackball when making major movements
2183 // along the other axis.
2184 int keycode = 0;
2185 int movement = 0;
2186 float accel = 1;
2187 if (xOff > yOff) {
2188 movement = x.generate((2/event.getXPrecision()));
2189 if (movement != 0) {
2190 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_RIGHT
2191 : KeyEvent.KEYCODE_DPAD_LEFT;
2192 accel = x.acceleration;
2193 y.reset(2);
2194 }
2195 } else if (yOff > 0) {
2196 movement = y.generate((2/event.getYPrecision()));
2197 if (movement != 0) {
2198 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_DOWN
2199 : KeyEvent.KEYCODE_DPAD_UP;
2200 accel = y.acceleration;
2201 x.reset(2);
2202 }
2203 }
2204
2205 if (keycode != 0) {
2206 if (movement < 0) movement = -movement;
2207 int accelMovement = (int)(movement * accel);
2208 if (DEBUG_TRACKBALL) Log.v(TAG, "Move: movement=" + movement
2209 + " accelMovement=" + accelMovement
2210 + " accel=" + accel);
2211 if (accelMovement > movement) {
2212 if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: "
2213 + keycode);
2214 movement--;
2215 deliverKeyEvent(new KeyEvent(curTime, curTime,
2216 KeyEvent.ACTION_MULTIPLE, keycode,
2217 accelMovement-movement, metastate), false);
2218 }
2219 while (movement > 0) {
2220 if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: "
2221 + keycode);
2222 movement--;
2223 curTime = SystemClock.uptimeMillis();
2224 deliverKeyEvent(new KeyEvent(curTime, curTime,
2225 KeyEvent.ACTION_DOWN, keycode, 0, event.getMetaState()), false);
2226 deliverKeyEvent(new KeyEvent(curTime, curTime,
2227 KeyEvent.ACTION_UP, keycode, 0, metastate), false);
2228 }
2229 mLastTrackballTime = curTime;
2230 }
2231 } finally {
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07002232 if (callWhenDone) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002233 finishMotionEvent();
2234 recycleMotionEvent(event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002235 }
2236 // Let the exception fall through -- the looper will catch
2237 // it and take care of the bad app for us.
2238 }
2239 }
2240
2241 /**
2242 * @param keyCode The key code
2243 * @return True if the key is directional.
2244 */
2245 static boolean isDirectional(int keyCode) {
2246 switch (keyCode) {
2247 case KeyEvent.KEYCODE_DPAD_LEFT:
2248 case KeyEvent.KEYCODE_DPAD_RIGHT:
2249 case KeyEvent.KEYCODE_DPAD_UP:
2250 case KeyEvent.KEYCODE_DPAD_DOWN:
2251 return true;
2252 }
2253 return false;
2254 }
2255
2256 /**
2257 * Returns true if this key is a keyboard key.
2258 * @param keyEvent The key event.
2259 * @return whether this key is a keyboard key.
2260 */
2261 private static boolean isKeyboardKey(KeyEvent keyEvent) {
2262 final int convertedKey = keyEvent.getUnicodeChar();
2263 return convertedKey > 0;
2264 }
2265
2266
2267
2268 /**
2269 * See if the key event means we should leave touch mode (and leave touch
2270 * mode if so).
2271 * @param event The key event.
2272 * @return Whether this key event should be consumed (meaning the act of
2273 * leaving touch mode alone is considered the event).
2274 */
2275 private boolean checkForLeavingTouchModeAndConsume(KeyEvent event) {
Adam Powell51a6bee2010-03-15 14:07:28 -07002276 final int action = event.getAction();
2277 if (action != KeyEvent.ACTION_DOWN && action != KeyEvent.ACTION_MULTIPLE) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002278 return false;
2279 }
2280 if ((event.getFlags()&KeyEvent.FLAG_KEEP_TOUCH_MODE) != 0) {
2281 return false;
2282 }
2283
2284 // only relevant if we are in touch mode
2285 if (!mAttachInfo.mInTouchMode) {
2286 return false;
2287 }
2288
2289 // if something like an edit text has focus and the user is typing,
2290 // leave touch mode
2291 //
2292 // note: the condition of not being a keyboard key is kind of a hacky
2293 // approximation of whether we think the focused view will want the
2294 // key; if we knew for sure whether the focused view would consume
2295 // the event, that would be better.
2296 if (isKeyboardKey(event) && mView != null && mView.hasFocus()) {
2297 mFocusedView = mView.findFocus();
2298 if ((mFocusedView instanceof ViewGroup)
2299 && ((ViewGroup) mFocusedView).getDescendantFocusability() ==
2300 ViewGroup.FOCUS_AFTER_DESCENDANTS) {
2301 // something has focus, but is holding it weakly as a container
2302 return false;
2303 }
2304 if (ensureTouchMode(false)) {
2305 throw new IllegalStateException("should not have changed focus "
2306 + "when leaving touch mode while a view has focus.");
2307 }
2308 return false;
2309 }
2310
2311 if (isDirectional(event.getKeyCode())) {
2312 // no view has focus, so we leave touch mode (and find something
2313 // to give focus to). the event is consumed if we were able to
2314 // find something to give focus to.
2315 return ensureTouchMode(false);
2316 }
2317 return false;
2318 }
2319
2320 /**
Romain Guy8506ab42009-06-11 17:35:47 -07002321 * log motion events
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002322 */
2323 private static void captureMotionLog(String subTag, MotionEvent ev) {
Romain Guy8506ab42009-06-11 17:35:47 -07002324 //check dynamic switch
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002325 if (ev == null ||
2326 SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_EVENT, 0) == 0) {
2327 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002328 }
Romain Guy8506ab42009-06-11 17:35:47 -07002329
2330 StringBuilder sb = new StringBuilder(subTag + ": ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002331 sb.append(ev.getDownTime()).append(',');
2332 sb.append(ev.getEventTime()).append(',');
2333 sb.append(ev.getAction()).append(',');
Romain Guy8506ab42009-06-11 17:35:47 -07002334 sb.append(ev.getX()).append(',');
2335 sb.append(ev.getY()).append(',');
2336 sb.append(ev.getPressure()).append(',');
2337 sb.append(ev.getSize()).append(',');
2338 sb.append(ev.getMetaState()).append(',');
2339 sb.append(ev.getXPrecision()).append(',');
2340 sb.append(ev.getYPrecision()).append(',');
2341 sb.append(ev.getDeviceId()).append(',');
2342 sb.append(ev.getEdgeFlags());
2343 Log.d(TAG, sb.toString());
2344 }
2345 /**
2346 * log motion events
2347 */
2348 private static void captureKeyLog(String subTag, KeyEvent ev) {
2349 //check dynamic switch
2350 if (ev == null ||
2351 SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_EVENT, 0) == 0) {
2352 return;
2353 }
2354 StringBuilder sb = new StringBuilder(subTag + ": ");
2355 sb.append(ev.getDownTime()).append(',');
2356 sb.append(ev.getEventTime()).append(',');
2357 sb.append(ev.getAction()).append(',');
2358 sb.append(ev.getKeyCode()).append(',');
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002359 sb.append(ev.getRepeatCount()).append(',');
2360 sb.append(ev.getMetaState()).append(',');
2361 sb.append(ev.getDeviceId()).append(',');
2362 sb.append(ev.getScanCode());
Romain Guy8506ab42009-06-11 17:35:47 -07002363 Log.d(TAG, sb.toString());
2364 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002365
2366 int enqueuePendingEvent(Object event, boolean sendDone) {
2367 int seq = mPendingEventSeq+1;
2368 if (seq < 0) seq = 0;
2369 mPendingEventSeq = seq;
2370 mPendingEvents.put(seq, event);
2371 return sendDone ? seq : -seq;
2372 }
2373
2374 Object retrievePendingEvent(int seq) {
2375 if (seq < 0) seq = -seq;
2376 Object event = mPendingEvents.get(seq);
2377 if (event != null) {
2378 mPendingEvents.remove(seq);
2379 }
2380 return event;
2381 }
Romain Guy8506ab42009-06-11 17:35:47 -07002382
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002383 private void deliverKeyEvent(KeyEvent event, boolean sendDone) {
2384 // If mView is null, we just consume the key event because it doesn't
2385 // make sense to do anything else with it.
Romain Guy812ccbe2010-06-01 14:07:24 -07002386 boolean handled = mView == null || mView.dispatchKeyEventPreIme(event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002387 if (handled) {
2388 if (sendDone) {
2389 if (LOCAL_LOGV) Log.v(
2390 "ViewRoot", "Telling window manager key is finished");
Jeff Brown46b9ac02010-04-22 18:58:52 -07002391 finishKeyEvent(event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002392 }
2393 return;
2394 }
2395 // If it is possible for this window to interact with the input
2396 // method window, then we want to first dispatch our key events
2397 // to the input method.
2398 if (mLastWasImTarget) {
2399 InputMethodManager imm = InputMethodManager.peekInstance();
2400 if (imm != null && mView != null) {
2401 int seq = enqueuePendingEvent(event, sendDone);
2402 if (DEBUG_IMF) Log.v(TAG, "Sending key event to IME: seq="
2403 + seq + " event=" + event);
2404 imm.dispatchKeyEvent(mView.getContext(), seq, event,
2405 mInputMethodCallback);
2406 return;
2407 }
2408 }
2409 deliverKeyEventToViewHierarchy(event, sendDone);
2410 }
2411
2412 void handleFinishedEvent(int seq, boolean handled) {
2413 final KeyEvent event = (KeyEvent)retrievePendingEvent(seq);
2414 if (DEBUG_IMF) Log.v(TAG, "IME finished event: seq=" + seq
2415 + " handled=" + handled + " event=" + event);
2416 if (event != null) {
2417 final boolean sendDone = seq >= 0;
2418 if (!handled) {
2419 deliverKeyEventToViewHierarchy(event, sendDone);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002420 } else if (sendDone) {
2421 if (LOCAL_LOGV) Log.v(
2422 "ViewRoot", "Telling window manager key is finished");
Jeff Brown46b9ac02010-04-22 18:58:52 -07002423 finishKeyEvent(event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002424 } else {
2425 Log.w("ViewRoot", "handleFinishedEvent(seq=" + seq
2426 + " handled=" + handled + " ev=" + event
2427 + ") neither delivering nor finishing key");
2428 }
2429 }
2430 }
Romain Guy8506ab42009-06-11 17:35:47 -07002431
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002432 private void deliverKeyEventToViewHierarchy(KeyEvent event, boolean sendDone) {
2433 try {
2434 if (mView != null && mAdded) {
2435 final int action = event.getAction();
2436 boolean isDown = (action == KeyEvent.ACTION_DOWN);
2437
2438 if (checkForLeavingTouchModeAndConsume(event)) {
2439 return;
Romain Guy8506ab42009-06-11 17:35:47 -07002440 }
2441
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002442 if (Config.LOGV) {
2443 captureKeyLog("captureDispatchKeyEvent", event);
2444 }
2445 boolean keyHandled = mView.dispatchKeyEvent(event);
2446
2447 if (!keyHandled && isDown) {
2448 int direction = 0;
2449 switch (event.getKeyCode()) {
2450 case KeyEvent.KEYCODE_DPAD_LEFT:
2451 direction = View.FOCUS_LEFT;
2452 break;
2453 case KeyEvent.KEYCODE_DPAD_RIGHT:
2454 direction = View.FOCUS_RIGHT;
2455 break;
2456 case KeyEvent.KEYCODE_DPAD_UP:
2457 direction = View.FOCUS_UP;
2458 break;
2459 case KeyEvent.KEYCODE_DPAD_DOWN:
2460 direction = View.FOCUS_DOWN;
2461 break;
2462 }
2463
2464 if (direction != 0) {
2465
2466 View focused = mView != null ? mView.findFocus() : null;
2467 if (focused != null) {
2468 View v = focused.focusSearch(direction);
2469 boolean focusPassed = false;
2470 if (v != null && v != focused) {
2471 // do the math the get the interesting rect
2472 // of previous focused into the coord system of
2473 // newly focused view
2474 focused.getFocusedRect(mTempRect);
Dianne Hackborn1c6a8942010-03-23 16:34:20 -07002475 if (mView instanceof ViewGroup) {
2476 ((ViewGroup) mView).offsetDescendantRectToMyCoords(
2477 focused, mTempRect);
2478 ((ViewGroup) mView).offsetRectIntoDescendantCoords(
2479 v, mTempRect);
2480 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002481 focusPassed = v.requestFocus(direction, mTempRect);
2482 }
2483
2484 if (!focusPassed) {
2485 mView.dispatchUnhandledMove(focused, direction);
2486 } else {
2487 playSoundEffect(SoundEffectConstants.getContantForFocusDirection(direction));
2488 }
2489 }
2490 }
2491 }
2492 }
2493
2494 } finally {
2495 if (sendDone) {
2496 if (LOCAL_LOGV) Log.v(
2497 "ViewRoot", "Telling window manager key is finished");
Jeff Brown46b9ac02010-04-22 18:58:52 -07002498 finishKeyEvent(event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002499 }
2500 // Let the exception fall through -- the looper will catch
2501 // it and take care of the bad app for us.
2502 }
2503 }
2504
2505 private AudioManager getAudioManager() {
2506 if (mView == null) {
2507 throw new IllegalStateException("getAudioManager called when there is no mView");
2508 }
2509 if (mAudioManager == null) {
2510 mAudioManager = (AudioManager) mView.getContext().getSystemService(Context.AUDIO_SERVICE);
2511 }
2512 return mAudioManager;
2513 }
2514
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002515 private int relayoutWindow(WindowManager.LayoutParams params, int viewVisibility,
2516 boolean insetsPending) throws RemoteException {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002517
2518 float appScale = mAttachInfo.mApplicationScale;
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002519 boolean restore = false;
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002520 if (params != null && mTranslator != null) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07002521 restore = true;
2522 params.backup();
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002523 mTranslator.translateWindowLayout(params);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002524 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002525 if (params != null) {
2526 if (DBG) Log.d(TAG, "WindowLayout in layoutWindow:" + params);
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002527 }
Dianne Hackborn694f79b2010-03-17 19:44:59 -07002528 mPendingConfiguration.seq = 0;
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002529 int relayoutResult = sWindowSession.relayout(
2530 mWindow, params,
Mitsuru Oshima61324e52009-07-21 15:40:36 -07002531 (int) (mView.mMeasuredWidth * appScale + 0.5f),
2532 (int) (mView.mMeasuredHeight * appScale + 0.5f),
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002533 viewVisibility, insetsPending, mWinFrame,
Dianne Hackborn694f79b2010-03-17 19:44:59 -07002534 mPendingContentInsets, mPendingVisibleInsets,
2535 mPendingConfiguration, mSurface);
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002536 if (restore) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07002537 params.restore();
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002538 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002539
2540 if (mTranslator != null) {
2541 mTranslator.translateRectInScreenToAppWinFrame(mWinFrame);
2542 mTranslator.translateRectInScreenToAppWindow(mPendingContentInsets);
2543 mTranslator.translateRectInScreenToAppWindow(mPendingVisibleInsets);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002544 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002545 return relayoutResult;
2546 }
Romain Guy8506ab42009-06-11 17:35:47 -07002547
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002548 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002549 * {@inheritDoc}
2550 */
2551 public void playSoundEffect(int effectId) {
2552 checkThread();
2553
Jean-Michel Trivi13b18fd2010-05-05 09:18:15 -07002554 try {
2555 final AudioManager audioManager = getAudioManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002556
Jean-Michel Trivi13b18fd2010-05-05 09:18:15 -07002557 switch (effectId) {
2558 case SoundEffectConstants.CLICK:
2559 audioManager.playSoundEffect(AudioManager.FX_KEY_CLICK);
2560 return;
2561 case SoundEffectConstants.NAVIGATION_DOWN:
2562 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_DOWN);
2563 return;
2564 case SoundEffectConstants.NAVIGATION_LEFT:
2565 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_LEFT);
2566 return;
2567 case SoundEffectConstants.NAVIGATION_RIGHT:
2568 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_RIGHT);
2569 return;
2570 case SoundEffectConstants.NAVIGATION_UP:
2571 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_UP);
2572 return;
2573 default:
2574 throw new IllegalArgumentException("unknown effect id " + effectId +
2575 " not defined in " + SoundEffectConstants.class.getCanonicalName());
2576 }
2577 } catch (IllegalStateException e) {
2578 // Exception thrown by getAudioManager() when mView is null
2579 Log.e(TAG, "FATAL EXCEPTION when attempting to play sound effect: " + e);
2580 e.printStackTrace();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002581 }
2582 }
2583
2584 /**
2585 * {@inheritDoc}
2586 */
2587 public boolean performHapticFeedback(int effectId, boolean always) {
2588 try {
2589 return sWindowSession.performHapticFeedback(mWindow, effectId, always);
2590 } catch (RemoteException e) {
2591 return false;
2592 }
2593 }
2594
2595 /**
2596 * {@inheritDoc}
2597 */
2598 public View focusSearch(View focused, int direction) {
2599 checkThread();
2600 if (!(mView instanceof ViewGroup)) {
2601 return null;
2602 }
2603 return FocusFinder.getInstance().findNextFocus((ViewGroup) mView, focused, direction);
2604 }
2605
2606 public void debug() {
2607 mView.debug();
2608 }
2609
2610 public void die(boolean immediate) {
Dianne Hackborn94d69142009-09-28 22:14:42 -07002611 if (immediate) {
2612 doDie();
2613 } else {
2614 sendEmptyMessage(DIE);
2615 }
2616 }
2617
2618 void doDie() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002619 checkThread();
Romain Guy812ccbe2010-06-01 14:07:24 -07002620 if (LOCAL_LOGV) Log.v("ViewRoot", "DIE in " + this + " of " + mSurface);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002621 synchronized (this) {
2622 if (mAdded && !mFirst) {
2623 int viewVisibility = mView.getVisibility();
2624 boolean viewVisibilityChanged = mViewVisibility != viewVisibility;
2625 if (mWindowAttributesChanged || viewVisibilityChanged) {
2626 // If layout params have been changed, first give them
2627 // to the window manager to make sure it has the correct
2628 // animation info.
2629 try {
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002630 if ((relayoutWindow(mWindowAttributes, viewVisibility, false)
2631 & WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002632 sWindowSession.finishDrawing(mWindow);
2633 }
2634 } catch (RemoteException e) {
2635 }
2636 }
2637
Dianne Hackborn0586a1b2009-09-06 21:08:27 -07002638 mSurface.release();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002639 }
2640 if (mAdded) {
2641 mAdded = false;
Dianne Hackborn94d69142009-09-28 22:14:42 -07002642 dispatchDetachedFromWindow();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002643 }
2644 }
2645 }
2646
2647 public void dispatchFinishedEvent(int seq, boolean handled) {
2648 Message msg = obtainMessage(FINISHED_EVENT);
2649 msg.arg1 = seq;
2650 msg.arg2 = handled ? 1 : 0;
2651 sendMessage(msg);
2652 }
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002653
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002654 public void dispatchResized(int w, int h, Rect coveredInsets,
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002655 Rect visibleInsets, boolean reportDraw, Configuration newConfig) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002656 if (DEBUG_LAYOUT) Log.v(TAG, "Resizing " + this + ": w=" + w
2657 + " h=" + h + " coveredInsets=" + coveredInsets.toShortString()
2658 + " visibleInsets=" + visibleInsets.toShortString()
2659 + " reportDraw=" + reportDraw);
2660 Message msg = obtainMessage(reportDraw ? RESIZED_REPORT :RESIZED);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002661 if (mTranslator != null) {
2662 mTranslator.translateRectInScreenToAppWindow(coveredInsets);
2663 mTranslator.translateRectInScreenToAppWindow(visibleInsets);
2664 w *= mTranslator.applicationInvertedScale;
2665 h *= mTranslator.applicationInvertedScale;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002666 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002667 msg.arg1 = w;
2668 msg.arg2 = h;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002669 ResizedInfo ri = new ResizedInfo();
2670 ri.coveredInsets = new Rect(coveredInsets);
2671 ri.visibleInsets = new Rect(visibleInsets);
2672 ri.newConfig = newConfig;
2673 msg.obj = ri;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002674 sendMessage(msg);
2675 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002676
2677 private Runnable mFinishedCallback;
2678
2679 private final InputHandler mInputHandler = new InputHandler() {
2680 public void handleKey(KeyEvent event, Runnable finishedCallback) {
2681 mFinishedCallback = finishedCallback;
2682
2683 if (event.getAction() == KeyEvent.ACTION_DOWN) {
2684 //noinspection ConstantConditions
2685 if (false && event.getKeyCode() == KeyEvent.KEYCODE_CAMERA) {
2686 if (Config.LOGD) Log.d("keydisp",
2687 "===================================================");
2688 if (Config.LOGD) Log.d("keydisp", "Focused view Hierarchy is:");
2689 debug();
2690
2691 if (Config.LOGD) Log.d("keydisp",
2692 "===================================================");
2693 }
2694 }
2695
2696 Message msg = obtainMessage(DISPATCH_KEY);
2697 msg.obj = event;
2698
2699 if (LOCAL_LOGV) Log.v(
2700 "ViewRoot", "sending key " + event + " to " + mView);
2701
2702 sendMessageAtTime(msg, event.getEventTime());
2703 }
2704
2705 public void handleTouch(MotionEvent event, Runnable finishedCallback) {
2706 finishedCallback.run();
2707
2708 Message msg = obtainMessage(DISPATCH_POINTER);
2709 msg.obj = event;
2710 msg.arg1 = 0;
2711 sendMessageAtTime(msg, event.getEventTime());
2712 }
2713
2714 public void handleTrackball(MotionEvent event, Runnable finishedCallback) {
2715 finishedCallback.run();
2716
2717 Message msg = obtainMessage(DISPATCH_TRACKBALL);
2718 msg.obj = event;
2719 msg.arg1 = 0;
2720 sendMessageAtTime(msg, event.getEventTime());
2721 }
2722 };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002723
2724 public void dispatchKey(KeyEvent event) {
2725 if (event.getAction() == KeyEvent.ACTION_DOWN) {
2726 //noinspection ConstantConditions
2727 if (false && event.getKeyCode() == KeyEvent.KEYCODE_CAMERA) {
Romain Guy812ccbe2010-06-01 14:07:24 -07002728 if (DBG) Log.d("keydisp", "===================================================");
2729 if (DBG) Log.d("keydisp", "Focused view Hierarchy is:");
2730
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002731 debug();
2732
Romain Guy812ccbe2010-06-01 14:07:24 -07002733 if (DBG) Log.d("keydisp", "===================================================");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002734 }
2735 }
2736
2737 Message msg = obtainMessage(DISPATCH_KEY);
2738 msg.obj = event;
2739
2740 if (LOCAL_LOGV) Log.v(
2741 "ViewRoot", "sending key " + event + " to " + mView);
2742
2743 sendMessageAtTime(msg, event.getEventTime());
2744 }
2745
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07002746 public void dispatchPointer(MotionEvent event, long eventTime,
2747 boolean callWhenDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002748 Message msg = obtainMessage(DISPATCH_POINTER);
2749 msg.obj = event;
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07002750 msg.arg1 = callWhenDone ? 1 : 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002751 sendMessageAtTime(msg, eventTime);
2752 }
2753
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07002754 public void dispatchTrackball(MotionEvent event, long eventTime,
2755 boolean callWhenDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002756 Message msg = obtainMessage(DISPATCH_TRACKBALL);
2757 msg.obj = event;
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07002758 msg.arg1 = callWhenDone ? 1 : 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002759 sendMessageAtTime(msg, eventTime);
2760 }
2761
2762 public void dispatchAppVisibility(boolean visible) {
2763 Message msg = obtainMessage(DISPATCH_APP_VISIBILITY);
2764 msg.arg1 = visible ? 1 : 0;
2765 sendMessage(msg);
2766 }
2767
2768 public void dispatchGetNewSurface() {
2769 Message msg = obtainMessage(DISPATCH_GET_NEW_SURFACE);
2770 sendMessage(msg);
2771 }
2772
2773 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
2774 Message msg = Message.obtain();
2775 msg.what = WINDOW_FOCUS_CHANGED;
2776 msg.arg1 = hasFocus ? 1 : 0;
2777 msg.arg2 = inTouchMode ? 1 : 0;
2778 sendMessage(msg);
2779 }
2780
Dianne Hackbornffa42482009-09-23 22:20:11 -07002781 public void dispatchCloseSystemDialogs(String reason) {
2782 Message msg = Message.obtain();
2783 msg.what = CLOSE_SYSTEM_DIALOGS;
2784 msg.obj = reason;
2785 sendMessage(msg);
2786 }
2787
svetoslavganov75986cf2009-05-14 22:28:01 -07002788 /**
2789 * The window is getting focus so if there is anything focused/selected
2790 * send an {@link AccessibilityEvent} to announce that.
2791 */
2792 private void sendAccessibilityEvents() {
2793 if (!AccessibilityManager.getInstance(mView.getContext()).isEnabled()) {
2794 return;
2795 }
2796 mView.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
2797 View focusedView = mView.findFocus();
2798 if (focusedView != null && focusedView != mView) {
2799 focusedView.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
2800 }
2801 }
2802
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002803 public boolean showContextMenuForChild(View originalView) {
2804 return false;
2805 }
2806
2807 public void createContextMenu(ContextMenu menu) {
2808 }
2809
2810 public void childDrawableStateChanged(View child) {
2811 }
2812
2813 protected Rect getWindowFrame() {
2814 return mWinFrame;
2815 }
2816
2817 void checkThread() {
2818 if (mThread != Thread.currentThread()) {
2819 throw new CalledFromWrongThreadException(
2820 "Only the original thread that created a view hierarchy can touch its views.");
2821 }
2822 }
2823
2824 public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
2825 // ViewRoot never intercepts touch event, so this can be a no-op
2826 }
2827
2828 public boolean requestChildRectangleOnScreen(View child, Rect rectangle,
2829 boolean immediate) {
2830 return scrollToRectOrFocus(rectangle, immediate);
2831 }
Romain Guy8506ab42009-06-11 17:35:47 -07002832
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07002833 class TakenSurfaceHolder extends BaseSurfaceHolder {
2834 @Override
2835 public boolean onAllowLockCanvas() {
2836 return mDrawingAllowed;
2837 }
2838
2839 @Override
2840 public void onRelayoutContainer() {
2841 // Not currently interesting -- from changing between fixed and layout size.
2842 }
2843
2844 public void setFormat(int format) {
2845 ((RootViewSurfaceTaker)mView).setSurfaceFormat(format);
2846 }
2847
2848 public void setType(int type) {
2849 ((RootViewSurfaceTaker)mView).setSurfaceType(type);
2850 }
2851
2852 @Override
2853 public void onUpdateSurface() {
2854 // We take care of format and type changes on our own.
2855 throw new IllegalStateException("Shouldn't be here");
2856 }
2857
2858 public boolean isCreating() {
2859 return mIsCreating;
2860 }
2861
2862 @Override
2863 public void setFixedSize(int width, int height) {
2864 throw new UnsupportedOperationException(
2865 "Currently only support sizing from layout");
2866 }
2867
2868 public void setKeepScreenOn(boolean screenOn) {
2869 ((RootViewSurfaceTaker)mView).setSurfaceKeepScreenOn(screenOn);
2870 }
2871 }
2872
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002873 static class InputMethodCallback extends IInputMethodCallback.Stub {
2874 private WeakReference<ViewRoot> mViewRoot;
2875
2876 public InputMethodCallback(ViewRoot viewRoot) {
2877 mViewRoot = new WeakReference<ViewRoot>(viewRoot);
2878 }
Romain Guy8506ab42009-06-11 17:35:47 -07002879
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002880 public void finishedEvent(int seq, boolean handled) {
2881 final ViewRoot viewRoot = mViewRoot.get();
2882 if (viewRoot != null) {
2883 viewRoot.dispatchFinishedEvent(seq, handled);
2884 }
2885 }
2886
2887 public void sessionCreated(IInputMethodSession session) throws RemoteException {
2888 // Stub -- not for use in the client.
2889 }
2890 }
Romain Guy8506ab42009-06-11 17:35:47 -07002891
Jeff Brown46b9ac02010-04-22 18:58:52 -07002892 class EventCompletion extends Handler {
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002893 final IWindow mWindow;
2894 final KeyEvent mKeyEvent;
2895 final boolean mIsPointer;
2896 final MotionEvent mMotionEvent;
Romain Guy8506ab42009-06-11 17:35:47 -07002897
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002898 EventCompletion(Looper looper, IWindow window, KeyEvent key,
2899 boolean isPointer, MotionEvent motion) {
2900 super(looper);
2901 mWindow = window;
2902 mKeyEvent = key;
2903 mIsPointer = isPointer;
2904 mMotionEvent = motion;
2905 sendEmptyMessage(0);
2906 }
Romain Guy8506ab42009-06-11 17:35:47 -07002907
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002908 @Override
2909 public void handleMessage(Message msg) {
2910 if (mKeyEvent != null) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002911 finishKeyEvent(mKeyEvent);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002912 } else if (mIsPointer) {
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002913 boolean didFinish;
2914 MotionEvent event = mMotionEvent;
2915 if (event == null) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002916 event = getPendingPointerMotionEvent();
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002917 didFinish = true;
2918 } else {
2919 didFinish = event.getAction() == MotionEvent.ACTION_OUTSIDE;
2920 }
2921 if (!didFinish) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002922 finishMotionEvent();
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002923 }
2924 } else {
2925 MotionEvent event = mMotionEvent;
2926 if (event == null) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002927 event = getPendingTrackballMotionEvent();
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002928 } else {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002929 finishMotionEvent();
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002930 }
2931 }
2932 }
2933 }
Romain Guy8506ab42009-06-11 17:35:47 -07002934
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002935 static class W extends IWindow.Stub {
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002936 private final WeakReference<ViewRoot> mViewRoot;
2937 private final Looper mMainLooper;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002938
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002939 public W(ViewRoot viewRoot, Context context) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002940 mViewRoot = new WeakReference<ViewRoot>(viewRoot);
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002941 mMainLooper = context.getMainLooper();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002942 }
2943
2944 public void resized(int w, int h, Rect coveredInsets,
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002945 Rect visibleInsets, boolean reportDraw, Configuration newConfig) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002946 final ViewRoot viewRoot = mViewRoot.get();
2947 if (viewRoot != null) {
2948 viewRoot.dispatchResized(w, h, coveredInsets,
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002949 visibleInsets, reportDraw, newConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002950 }
2951 }
2952
2953 public void dispatchKey(KeyEvent event) {
2954 final ViewRoot viewRoot = mViewRoot.get();
2955 if (viewRoot != null) {
2956 viewRoot.dispatchKey(event);
2957 } else {
2958 Log.w("ViewRoot.W", "Key event " + event + " but no ViewRoot available!");
Jeff Brown46b9ac02010-04-22 18:58:52 -07002959 viewRoot.new EventCompletion(mMainLooper, this, event, false, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002960 }
2961 }
2962
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07002963 public void dispatchPointer(MotionEvent event, long eventTime,
2964 boolean callWhenDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002965 final ViewRoot viewRoot = mViewRoot.get();
Michael Chan53071d62009-05-13 17:29:48 -07002966 if (viewRoot != null) {
2967 if (MEASURE_LATENCY) {
2968 // Note: eventTime is in milliseconds
2969 ViewRoot.lt.sample("* ViewRoot b4 dispatchPtr", System.nanoTime() - eventTime * 1000000);
2970 }
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07002971 viewRoot.dispatchPointer(event, eventTime, callWhenDone);
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002972 } else {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002973 viewRoot.new EventCompletion(mMainLooper, this, null, true, event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002974 }
2975 }
2976
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07002977 public void dispatchTrackball(MotionEvent event, long eventTime,
2978 boolean callWhenDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002979 final ViewRoot viewRoot = mViewRoot.get();
2980 if (viewRoot != null) {
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07002981 viewRoot.dispatchTrackball(event, eventTime, callWhenDone);
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002982 } else {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002983 viewRoot.new EventCompletion(mMainLooper, this, null, false, event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002984 }
2985 }
2986
2987 public void dispatchAppVisibility(boolean visible) {
2988 final ViewRoot viewRoot = mViewRoot.get();
2989 if (viewRoot != null) {
2990 viewRoot.dispatchAppVisibility(visible);
2991 }
2992 }
2993
2994 public void dispatchGetNewSurface() {
2995 final ViewRoot viewRoot = mViewRoot.get();
2996 if (viewRoot != null) {
2997 viewRoot.dispatchGetNewSurface();
2998 }
2999 }
3000
3001 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
3002 final ViewRoot viewRoot = mViewRoot.get();
3003 if (viewRoot != null) {
3004 viewRoot.windowFocusChanged(hasFocus, inTouchMode);
3005 }
3006 }
3007
3008 private static int checkCallingPermission(String permission) {
3009 if (!Process.supportsProcesses()) {
3010 return PackageManager.PERMISSION_GRANTED;
3011 }
3012
3013 try {
3014 return ActivityManagerNative.getDefault().checkPermission(
3015 permission, Binder.getCallingPid(), Binder.getCallingUid());
3016 } catch (RemoteException e) {
3017 return PackageManager.PERMISSION_DENIED;
3018 }
3019 }
3020
3021 public void executeCommand(String command, String parameters, ParcelFileDescriptor out) {
3022 final ViewRoot viewRoot = mViewRoot.get();
3023 if (viewRoot != null) {
3024 final View view = viewRoot.mView;
3025 if (view != null) {
3026 if (checkCallingPermission(Manifest.permission.DUMP) !=
3027 PackageManager.PERMISSION_GRANTED) {
3028 throw new SecurityException("Insufficient permissions to invoke"
3029 + " executeCommand() from pid=" + Binder.getCallingPid()
3030 + ", uid=" + Binder.getCallingUid());
3031 }
3032
3033 OutputStream clientStream = null;
3034 try {
3035 clientStream = new ParcelFileDescriptor.AutoCloseOutputStream(out);
3036 ViewDebug.dispatchCommand(view, command, parameters, clientStream);
3037 } catch (IOException e) {
3038 e.printStackTrace();
3039 } finally {
3040 if (clientStream != null) {
3041 try {
3042 clientStream.close();
3043 } catch (IOException e) {
3044 e.printStackTrace();
3045 }
3046 }
3047 }
3048 }
3049 }
3050 }
Dianne Hackborn72c82ab2009-08-11 21:13:54 -07003051
Dianne Hackbornffa42482009-09-23 22:20:11 -07003052 public void closeSystemDialogs(String reason) {
3053 final ViewRoot viewRoot = mViewRoot.get();
3054 if (viewRoot != null) {
3055 viewRoot.dispatchCloseSystemDialogs(reason);
3056 }
3057 }
3058
Marco Nelissenbf6956b2009-11-09 15:21:13 -08003059 public void dispatchWallpaperOffsets(float x, float y, float xStep, float yStep,
3060 boolean sync) {
Dianne Hackborn19382ac2009-09-11 21:13:37 -07003061 if (sync) {
3062 try {
3063 sWindowSession.wallpaperOffsetsComplete(asBinder());
3064 } catch (RemoteException e) {
3065 }
3066 }
Dianne Hackborn72c82ab2009-08-11 21:13:54 -07003067 }
Dianne Hackborn75804932009-10-20 20:15:20 -07003068
3069 public void dispatchWallpaperCommand(String action, int x, int y,
3070 int z, Bundle extras, boolean sync) {
3071 if (sync) {
3072 try {
3073 sWindowSession.wallpaperCommandComplete(asBinder(), null);
3074 } catch (RemoteException e) {
3075 }
3076 }
3077 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003078 }
3079
3080 /**
3081 * Maintains state information for a single trackball axis, generating
3082 * discrete (DPAD) movements based on raw trackball motion.
3083 */
3084 static final class TrackballAxis {
3085 /**
3086 * The maximum amount of acceleration we will apply.
3087 */
3088 static final float MAX_ACCELERATION = 20;
Romain Guy8506ab42009-06-11 17:35:47 -07003089
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003090 /**
3091 * The maximum amount of time (in milliseconds) between events in order
3092 * for us to consider the user to be doing fast trackball movements,
3093 * and thus apply an acceleration.
3094 */
3095 static final long FAST_MOVE_TIME = 150;
Romain Guy8506ab42009-06-11 17:35:47 -07003096
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003097 /**
3098 * Scaling factor to the time (in milliseconds) between events to how
3099 * much to multiple/divide the current acceleration. When movement
3100 * is < FAST_MOVE_TIME this multiplies the acceleration; when >
3101 * FAST_MOVE_TIME it divides it.
3102 */
3103 static final float ACCEL_MOVE_SCALING_FACTOR = (1.0f/40);
Romain Guy8506ab42009-06-11 17:35:47 -07003104
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003105 float position;
3106 float absPosition;
3107 float acceleration = 1;
3108 long lastMoveTime = 0;
3109 int step;
3110 int dir;
3111 int nonAccelMovement;
3112
3113 void reset(int _step) {
3114 position = 0;
3115 acceleration = 1;
3116 lastMoveTime = 0;
3117 step = _step;
3118 dir = 0;
3119 }
3120
3121 /**
3122 * Add trackball movement into the state. If the direction of movement
3123 * has been reversed, the state is reset before adding the
3124 * movement (so that you don't have to compensate for any previously
3125 * collected movement before see the result of the movement in the
3126 * new direction).
3127 *
3128 * @return Returns the absolute value of the amount of movement
3129 * collected so far.
3130 */
3131 float collect(float off, long time, String axis) {
3132 long normTime;
3133 if (off > 0) {
3134 normTime = (long)(off * FAST_MOVE_TIME);
3135 if (dir < 0) {
3136 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to positive!");
3137 position = 0;
3138 step = 0;
3139 acceleration = 1;
3140 lastMoveTime = 0;
3141 }
3142 dir = 1;
3143 } else if (off < 0) {
3144 normTime = (long)((-off) * FAST_MOVE_TIME);
3145 if (dir > 0) {
3146 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to negative!");
3147 position = 0;
3148 step = 0;
3149 acceleration = 1;
3150 lastMoveTime = 0;
3151 }
3152 dir = -1;
3153 } else {
3154 normTime = 0;
3155 }
Romain Guy8506ab42009-06-11 17:35:47 -07003156
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003157 // The number of milliseconds between each movement that is
3158 // considered "normal" and will not result in any acceleration
3159 // or deceleration, scaled by the offset we have here.
3160 if (normTime > 0) {
3161 long delta = time - lastMoveTime;
3162 lastMoveTime = time;
3163 float acc = acceleration;
3164 if (delta < normTime) {
3165 // The user is scrolling rapidly, so increase acceleration.
3166 float scale = (normTime-delta) * ACCEL_MOVE_SCALING_FACTOR;
3167 if (scale > 1) acc *= scale;
3168 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " accelerate: off="
3169 + off + " normTime=" + normTime + " delta=" + delta
3170 + " scale=" + scale + " acc=" + acc);
3171 acceleration = acc < MAX_ACCELERATION ? acc : MAX_ACCELERATION;
3172 } else {
3173 // The user is scrolling slowly, so decrease acceleration.
3174 float scale = (delta-normTime) * ACCEL_MOVE_SCALING_FACTOR;
3175 if (scale > 1) acc /= scale;
3176 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " deccelerate: off="
3177 + off + " normTime=" + normTime + " delta=" + delta
3178 + " scale=" + scale + " acc=" + acc);
3179 acceleration = acc > 1 ? acc : 1;
3180 }
3181 }
3182 position += off;
3183 return (absPosition = Math.abs(position));
3184 }
3185
3186 /**
3187 * Generate the number of discrete movement events appropriate for
3188 * the currently collected trackball movement.
3189 *
3190 * @param precision The minimum movement required to generate the
3191 * first discrete movement.
3192 *
3193 * @return Returns the number of discrete movements, either positive
3194 * or negative, or 0 if there is not enough trackball movement yet
3195 * for a discrete movement.
3196 */
3197 int generate(float precision) {
3198 int movement = 0;
3199 nonAccelMovement = 0;
3200 do {
3201 final int dir = position >= 0 ? 1 : -1;
3202 switch (step) {
3203 // If we are going to execute the first step, then we want
3204 // to do this as soon as possible instead of waiting for
3205 // a full movement, in order to make things look responsive.
3206 case 0:
3207 if (absPosition < precision) {
3208 return movement;
3209 }
3210 movement += dir;
3211 nonAccelMovement += dir;
3212 step = 1;
3213 break;
3214 // If we have generated the first movement, then we need
3215 // to wait for the second complete trackball motion before
3216 // generating the second discrete movement.
3217 case 1:
3218 if (absPosition < 2) {
3219 return movement;
3220 }
3221 movement += dir;
3222 nonAccelMovement += dir;
3223 position += dir > 0 ? -2 : 2;
3224 absPosition = Math.abs(position);
3225 step = 2;
3226 break;
3227 // After the first two, we generate discrete movements
3228 // consistently with the trackball, applying an acceleration
3229 // if the trackball is moving quickly. This is a simple
3230 // acceleration on top of what we already compute based
3231 // on how quickly the wheel is being turned, to apply
3232 // a longer increasing acceleration to continuous movement
3233 // in one direction.
3234 default:
3235 if (absPosition < 1) {
3236 return movement;
3237 }
3238 movement += dir;
3239 position += dir >= 0 ? -1 : 1;
3240 absPosition = Math.abs(position);
3241 float acc = acceleration;
3242 acc *= 1.1f;
3243 acceleration = acc < MAX_ACCELERATION ? acc : acceleration;
3244 break;
3245 }
3246 } while (true);
3247 }
3248 }
3249
3250 public static final class CalledFromWrongThreadException extends AndroidRuntimeException {
3251 public CalledFromWrongThreadException(String msg) {
3252 super(msg);
3253 }
3254 }
3255
3256 private SurfaceHolder mHolder = new SurfaceHolder() {
3257 // we only need a SurfaceHolder for opengl. it would be nice
3258 // to implement everything else though, especially the callback
3259 // support (opengl doesn't make use of it right now, but eventually
3260 // will).
3261 public Surface getSurface() {
3262 return mSurface;
3263 }
3264
3265 public boolean isCreating() {
3266 return false;
3267 }
3268
3269 public void addCallback(Callback callback) {
3270 }
3271
3272 public void removeCallback(Callback callback) {
3273 }
3274
3275 public void setFixedSize(int width, int height) {
3276 }
3277
3278 public void setSizeFromLayout() {
3279 }
3280
3281 public void setFormat(int format) {
3282 }
3283
3284 public void setType(int type) {
3285 }
3286
3287 public void setKeepScreenOn(boolean screenOn) {
3288 }
3289
3290 public Canvas lockCanvas() {
3291 return null;
3292 }
3293
3294 public Canvas lockCanvas(Rect dirty) {
3295 return null;
3296 }
3297
3298 public void unlockCanvasAndPost(Canvas canvas) {
3299 }
3300 public Rect getSurfaceFrame() {
3301 return null;
3302 }
3303 };
3304
3305 static RunQueue getRunQueue() {
3306 RunQueue rq = sRunQueues.get();
3307 if (rq != null) {
3308 return rq;
3309 }
3310 rq = new RunQueue();
3311 sRunQueues.set(rq);
3312 return rq;
3313 }
Romain Guy8506ab42009-06-11 17:35:47 -07003314
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003315 /**
3316 * @hide
3317 */
3318 static final class RunQueue {
3319 private final ArrayList<HandlerAction> mActions = new ArrayList<HandlerAction>();
3320
3321 void post(Runnable action) {
3322 postDelayed(action, 0);
3323 }
3324
3325 void postDelayed(Runnable action, long delayMillis) {
3326 HandlerAction handlerAction = new HandlerAction();
3327 handlerAction.action = action;
3328 handlerAction.delay = delayMillis;
3329
3330 synchronized (mActions) {
3331 mActions.add(handlerAction);
3332 }
3333 }
3334
3335 void removeCallbacks(Runnable action) {
3336 final HandlerAction handlerAction = new HandlerAction();
3337 handlerAction.action = action;
3338
3339 synchronized (mActions) {
3340 final ArrayList<HandlerAction> actions = mActions;
3341
3342 while (actions.remove(handlerAction)) {
3343 // Keep going
3344 }
3345 }
3346 }
3347
3348 void executeActions(Handler handler) {
3349 synchronized (mActions) {
3350 final ArrayList<HandlerAction> actions = mActions;
3351 final int count = actions.size();
3352
3353 for (int i = 0; i < count; i++) {
3354 final HandlerAction handlerAction = actions.get(i);
3355 handler.postDelayed(handlerAction.action, handlerAction.delay);
3356 }
3357
Romain Guy15df6702009-08-17 20:17:30 -07003358 actions.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003359 }
3360 }
3361
3362 private static class HandlerAction {
3363 Runnable action;
3364 long delay;
3365
3366 @Override
3367 public boolean equals(Object o) {
3368 if (this == o) return true;
3369 if (o == null || getClass() != o.getClass()) return false;
3370
3371 HandlerAction that = (HandlerAction) o;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003372 return !(action != null ? !action.equals(that.action) : that.action != null);
3373
3374 }
3375
3376 @Override
3377 public int hashCode() {
3378 int result = action != null ? action.hashCode() : 0;
3379 result = 31 * result + (int) (delay ^ (delay >>> 32));
3380 return result;
3381 }
3382 }
3383 }
3384
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003385 private static native void nativeShowFPS(Canvas canvas, int durationMillis);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003386}