blob: 8abbf58f0118b4a9975851af9cc04449f9211bb2 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.view;
18
Dianne Hackborndc8a7f62010-05-10 11:29:34 -070019import com.android.internal.view.BaseSurfaceHolder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080020import com.android.internal.view.IInputMethodCallback;
21import com.android.internal.view.IInputMethodSession;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -070022import com.android.internal.view.RootViewSurfaceTaker;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080023
24import android.graphics.Canvas;
25import android.graphics.PixelFormat;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080026import android.graphics.PorterDuff;
27import android.graphics.Rect;
28import android.graphics.Region;
29import android.os.*;
30import android.os.Process;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080031import android.util.AndroidRuntimeException;
32import android.util.Config;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -070033import android.util.DisplayMetrics;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080034import android.util.Log;
35import android.util.EventLog;
36import android.util.SparseArray;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080037import android.view.View.MeasureSpec;
svetoslavganov75986cf2009-05-14 22:28:01 -070038import android.view.accessibility.AccessibilityEvent;
39import android.view.accessibility.AccessibilityManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080040import android.view.inputmethod.InputConnection;
41import android.view.inputmethod.InputMethodManager;
42import android.widget.Scroller;
43import android.content.pm.PackageManager;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -070044import android.content.res.CompatibilityInfo;
Dianne Hackborne36d6e22010-02-17 19:46:25 -080045import android.content.res.Configuration;
Mitsuru Oshima38ed7d772009-07-21 14:39:34 -070046import android.content.res.Resources;
Dianne Hackborne36d6e22010-02-17 19:46:25 -080047import android.content.ComponentCallbacks;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080048import android.content.Context;
49import android.app.ActivityManagerNative;
50import android.Manifest;
51import android.media.AudioManager;
52
53import java.lang.ref.WeakReference;
54import java.io.IOException;
55import java.io.OutputStream;
56import java.util.ArrayList;
57
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080058/**
59 * The top of a view hierarchy, implementing the needed protocol between View
60 * and the WindowManager. This is for the most part an internal implementation
61 * detail of {@link WindowManagerImpl}.
62 *
63 * {@hide}
64 */
Romain Guy812ccbe2010-06-01 14:07:24 -070065@SuppressWarnings({"EmptyCatchBlock", "PointlessBooleanExpression"})
66public final class ViewRoot extends Handler implements ViewParent, View.AttachInfo.Callbacks {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080067 private static final String TAG = "ViewRoot";
68 private static final boolean DBG = false;
Mike Reedfd716532009-10-12 14:42:56 -040069 private static final boolean SHOW_FPS = false;
Romain Guy812ccbe2010-06-01 14:07:24 -070070 private static final boolean LOCAL_LOGV = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080071 /** @noinspection PointlessBooleanExpression*/
72 private static final boolean DEBUG_DRAW = false || LOCAL_LOGV;
73 private static final boolean DEBUG_LAYOUT = false || LOCAL_LOGV;
Christopher Tatefa9e7c02010-05-06 12:07:10 -070074 private static final boolean DEBUG_INPUT = true || LOCAL_LOGV;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080075 private static final boolean DEBUG_INPUT_RESIZE = false || LOCAL_LOGV;
76 private static final boolean DEBUG_ORIENTATION = false || LOCAL_LOGV;
77 private static final boolean DEBUG_TRACKBALL = false || LOCAL_LOGV;
78 private static final boolean DEBUG_IMF = false || LOCAL_LOGV;
Dianne Hackborn694f79b2010-03-17 19:44:59 -070079 private static final boolean DEBUG_CONFIGURATION = false || LOCAL_LOGV;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080080 private static final boolean WATCH_POINTER = false;
81
Michael Chan53071d62009-05-13 17:29:48 -070082 private static final boolean MEASURE_LATENCY = false;
83 private static LatencyTimer lt;
84
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080085 /**
86 * Maximum time we allow the user to roll the trackball enough to generate
87 * a key event, before resetting the counters.
88 */
89 static final int MAX_TRACKBALL_DELAY = 250;
90
91 static long sInstanceCount = 0;
92
93 static IWindowSession sWindowSession;
94
95 static final Object mStaticInit = new Object();
96 static boolean mInitialized = false;
97
98 static final ThreadLocal<RunQueue> sRunQueues = new ThreadLocal<RunQueue>();
99
Dianne Hackborn2a9094d2010-02-03 19:20:09 -0800100 static final ArrayList<Runnable> sFirstDrawHandlers = new ArrayList<Runnable>();
101 static boolean sFirstDrawComplete = false;
102
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800103 static final ArrayList<ComponentCallbacks> sConfigCallbacks
104 = new ArrayList<ComponentCallbacks>();
105
Romain Guy8506ab42009-06-11 17:35:47 -0700106 private static int sDrawTime;
Romain Guy13922e02009-05-12 17:56:14 -0700107
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800108 long mLastTrackballTime = 0;
109 final TrackballAxis mTrackballAxisX = new TrackballAxis();
110 final TrackballAxis mTrackballAxisY = new TrackballAxis();
111
112 final int[] mTmpLocation = new int[2];
Romain Guy8506ab42009-06-11 17:35:47 -0700113
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800114 final InputMethodCallback mInputMethodCallback;
115 final SparseArray<Object> mPendingEvents = new SparseArray<Object>();
116 int mPendingEventSeq = 0;
Romain Guy8506ab42009-06-11 17:35:47 -0700117
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800118 final Thread mThread;
119
120 final WindowLeaked mLocation;
121
122 final WindowManager.LayoutParams mWindowAttributes = new WindowManager.LayoutParams();
123
124 final W mWindow;
125
126 View mView;
127 View mFocusedView;
128 View mRealFocusedView; // this is not set to null in touch mode
129 int mViewVisibility;
130 boolean mAppVisible = true;
131
Dianne Hackbornd76b67c2010-07-13 17:48:30 -0700132 SurfaceHolder.Callback2 mSurfaceHolderCallback;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700133 BaseSurfaceHolder mSurfaceHolder;
134 boolean mIsCreating;
135 boolean mDrawingAllowed;
136
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800137 final Region mTransparentRegion;
138 final Region mPreviousTransparentRegion;
139
140 int mWidth;
141 int mHeight;
142 Rect mDirty; // will be a graphics.Region soon
Romain Guybb93d552009-03-24 21:04:15 -0700143 boolean mIsAnimating;
Romain Guy8506ab42009-06-11 17:35:47 -0700144
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700145 CompatibilityInfo.Translator mTranslator;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800146
147 final View.AttachInfo mAttachInfo;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700148 InputChannel mInputChannel;
Dianne Hackborn1e4b9f32010-06-23 14:10:57 -0700149 InputQueue.Callback mInputQueueCallback;
150 InputQueue mInputQueue;
Dianne Hackborna95e4cb2010-06-18 18:09:33 -0700151
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800152 final Rect mTempRect; // used in the transaction to not thrash the heap.
153 final Rect mVisRect; // used to retrieve visible rect of focused view.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800154
155 boolean mTraversalScheduled;
156 boolean mWillDrawSoon;
157 boolean mLayoutRequested;
158 boolean mFirst;
159 boolean mReportNextDraw;
160 boolean mFullRedrawNeeded;
161 boolean mNewSurfaceNeeded;
162 boolean mHasHadWindowFocus;
163 boolean mLastWasImTarget;
164
165 boolean mWindowAttributesChanged = false;
166
167 // These can be accessed by any thread, must be protected with a lock.
Mathias Agopian5583dc62009-07-09 16:28:11 -0700168 // Surface can never be reassigned or cleared (use Surface.clear()).
169 private final Surface mSurface = new Surface();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800170
171 boolean mAdded;
172 boolean mAddedTouchMode;
173
174 /*package*/ int mAddNesting;
175
176 // These are accessed by multiple threads.
177 final Rect mWinFrame; // frame given by window manager.
178
179 final Rect mPendingVisibleInsets = new Rect();
180 final Rect mPendingContentInsets = new Rect();
181 final ViewTreeObserver.InternalInsetsInfo mLastGivenInsets
182 = new ViewTreeObserver.InternalInsetsInfo();
183
Dianne Hackborn694f79b2010-03-17 19:44:59 -0700184 final Configuration mLastConfiguration = new Configuration();
185 final Configuration mPendingConfiguration = new Configuration();
186
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800187 class ResizedInfo {
188 Rect coveredInsets;
189 Rect visibleInsets;
190 Configuration newConfig;
191 }
192
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800193 boolean mScrollMayChange;
194 int mSoftInputMode;
195 View mLastScrolledFocus;
196 int mScrollY;
197 int mCurScrollY;
198 Scroller mScroller;
Romain Guy8506ab42009-06-11 17:35:47 -0700199
Romain Guy812ccbe2010-06-01 14:07:24 -0700200 HardwareRenderer mHwRenderer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800201
Romain Guy8506ab42009-06-11 17:35:47 -0700202 final ViewConfiguration mViewConfiguration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800203
204 /**
205 * see {@link #playSoundEffect(int)}
206 */
207 AudioManager mAudioManager;
208
Dianne Hackborn11ea3342009-07-22 21:48:55 -0700209 private final int mDensity;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700210
Dianne Hackborn4c62fc02009-08-08 20:40:27 -0700211 public static IWindowSession getWindowSession(Looper mainLooper) {
212 synchronized (mStaticInit) {
213 if (!mInitialized) {
214 try {
215 InputMethodManager imm = InputMethodManager.getInstance(mainLooper);
216 sWindowSession = IWindowManager.Stub.asInterface(
217 ServiceManager.getService("window"))
218 .openSession(imm.getClient(), imm.getInputContext());
219 mInitialized = true;
220 } catch (RemoteException e) {
221 }
222 }
223 return sWindowSession;
224 }
225 }
226
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800227 public ViewRoot(Context context) {
228 super();
229
Romain Guy812ccbe2010-06-01 14:07:24 -0700230 if (MEASURE_LATENCY) {
231 if (lt == null) {
232 lt = new LatencyTimer(100, 1000);
233 }
Michael Chan53071d62009-05-13 17:29:48 -0700234 }
235
Carl Shapiro82fe5642010-02-24 00:14:23 -0800236 // For debug only
237 //++sInstanceCount;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800238
239 // Initialize the statics when this class is first instantiated. This is
240 // done here instead of in the static block because Zygote does not
241 // allow the spawning of threads.
Dianne Hackborn4c62fc02009-08-08 20:40:27 -0700242 getWindowSession(context.getMainLooper());
243
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800244 mThread = Thread.currentThread();
245 mLocation = new WindowLeaked(null);
246 mLocation.fillInStackTrace();
247 mWidth = -1;
248 mHeight = -1;
249 mDirty = new Rect();
250 mTempRect = new Rect();
251 mVisRect = new Rect();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800252 mWinFrame = new Rect();
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -0700253 mWindow = new W(this, context);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800254 mInputMethodCallback = new InputMethodCallback(this);
255 mViewVisibility = View.GONE;
256 mTransparentRegion = new Region();
257 mPreviousTransparentRegion = new Region();
258 mFirst = true; // true for the first time the view is added
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800259 mAdded = false;
260 mAttachInfo = new View.AttachInfo(sWindowSession, mWindow, this, this);
261 mViewConfiguration = ViewConfiguration.get(context);
Dianne Hackborn11ea3342009-07-22 21:48:55 -0700262 mDensity = context.getResources().getDisplayMetrics().densityDpi;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800263 }
264
Carl Shapiro82fe5642010-02-24 00:14:23 -0800265 // For debug only
266 /*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800267 @Override
268 protected void finalize() throws Throwable {
269 super.finalize();
270 --sInstanceCount;
271 }
Carl Shapiro82fe5642010-02-24 00:14:23 -0800272 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800273
274 public static long getInstanceCount() {
275 return sInstanceCount;
276 }
277
Dianne Hackborn2a9094d2010-02-03 19:20:09 -0800278 public static void addFirstDrawHandler(Runnable callback) {
279 synchronized (sFirstDrawHandlers) {
280 if (!sFirstDrawComplete) {
281 sFirstDrawHandlers.add(callback);
282 }
283 }
284 }
285
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800286 public static void addConfigCallback(ComponentCallbacks callback) {
287 synchronized (sConfigCallbacks) {
288 sConfigCallbacks.add(callback);
289 }
290 }
291
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800292 // FIXME for perf testing only
293 private boolean mProfile = false;
294
295 /**
296 * Call this to profile the next traversal call.
297 * FIXME for perf testing only. Remove eventually
298 */
299 public void profile() {
300 mProfile = true;
301 }
302
303 /**
304 * Indicates whether we are in touch mode. Calling this method triggers an IPC
305 * call and should be avoided whenever possible.
306 *
307 * @return True, if the device is in touch mode, false otherwise.
308 *
309 * @hide
310 */
311 static boolean isInTouchMode() {
312 if (mInitialized) {
313 try {
314 return sWindowSession.getInTouchMode();
315 } catch (RemoteException e) {
316 }
317 }
318 return false;
319 }
320
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800321 /**
322 * We have one child
323 */
Romain Guye4d01122010-06-16 18:44:05 -0700324 public void setView(View view, WindowManager.LayoutParams attrs, View panelParentView) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800325 synchronized (this) {
326 if (mView == null) {
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700327 mView = view;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700328 mWindowAttributes.copyFrom(attrs);
Mitsuru Oshima1ecf5d22009-07-06 17:20:38 -0700329 attrs = mWindowAttributes;
Romain Guye4d01122010-06-16 18:44:05 -0700330
Romain Guy529b60a2010-08-03 18:05:47 -0700331 enableHardwareAcceleration(attrs);
Romain Guye4d01122010-06-16 18:44:05 -0700332
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700333 if (view instanceof RootViewSurfaceTaker) {
334 mSurfaceHolderCallback =
335 ((RootViewSurfaceTaker)view).willYouTakeTheSurface();
336 if (mSurfaceHolderCallback != null) {
337 mSurfaceHolder = new TakenSurfaceHolder();
Dianne Hackborn289b9b62010-07-09 11:44:11 -0700338 mSurfaceHolder.setFormat(PixelFormat.UNKNOWN);
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700339 }
340 }
Mitsuru Oshima38ed7d772009-07-21 14:39:34 -0700341 Resources resources = mView.getContext().getResources();
342 CompatibilityInfo compatibilityInfo = resources.getCompatibilityInfo();
Mitsuru Oshima589cebe2009-07-22 20:38:58 -0700343 mTranslator = compatibilityInfo.getTranslator();
Mitsuru Oshima38ed7d772009-07-21 14:39:34 -0700344
345 if (mTranslator != null || !compatibilityInfo.supportsScreen()) {
Mitsuru Oshima240f8a72009-07-22 20:39:14 -0700346 mSurface.setCompatibleDisplayMetrics(resources.getDisplayMetrics(),
347 mTranslator);
Mitsuru Oshima38ed7d772009-07-21 14:39:34 -0700348 }
349
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -0700350 boolean restore = false;
Romain Guy35b38ce2009-10-07 13:38:55 -0700351 if (mTranslator != null) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -0700352 restore = true;
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700353 attrs.backup();
354 mTranslator.translateWindowLayout(attrs);
Mitsuru Oshima3d914922009-05-13 22:29:15 -0700355 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700356 if (DEBUG_LAYOUT) Log.d(TAG, "WindowLayout in setView:" + attrs);
357
Mitsuru Oshima1ecf5d22009-07-06 17:20:38 -0700358 if (!compatibilityInfo.supportsScreen()) {
359 attrs.flags |= WindowManager.LayoutParams.FLAG_COMPATIBLE_WINDOW;
360 }
361
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800362 mSoftInputMode = attrs.softInputMode;
363 mWindowAttributesChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800364 mAttachInfo.mRootView = view;
Romain Guy35b38ce2009-10-07 13:38:55 -0700365 mAttachInfo.mScalingRequired = mTranslator != null;
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700366 mAttachInfo.mApplicationScale =
367 mTranslator == null ? 1.0f : mTranslator.applicationScale;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800368 if (panelParentView != null) {
369 mAttachInfo.mPanelParentWindowToken
370 = panelParentView.getApplicationWindowToken();
371 }
372 mAdded = true;
373 int res; /* = WindowManagerImpl.ADD_OKAY; */
Romain Guy8506ab42009-06-11 17:35:47 -0700374
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800375 // Schedule the first layout -before- adding to the window
376 // manager, to make sure we do the relayout before receiving
377 // any other events from the system.
378 requestLayout();
Jeff Brown46b9ac02010-04-22 18:58:52 -0700379 mInputChannel = new InputChannel();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800380 try {
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700381 res = sWindowSession.add(mWindow, mWindowAttributes,
Jeff Brown46b9ac02010-04-22 18:58:52 -0700382 getHostVisibility(), mAttachInfo.mContentInsets,
383 mInputChannel);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800384 } catch (RemoteException e) {
385 mAdded = false;
386 mView = null;
387 mAttachInfo.mRootView = null;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700388 mInputChannel = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800389 unscheduleTraversals();
390 throw new RuntimeException("Adding window failed", e);
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700391 } finally {
392 if (restore) {
393 attrs.restore();
394 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800395 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700396
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700397 if (mTranslator != null) {
398 mTranslator.translateRectInScreenToAppWindow(mAttachInfo.mContentInsets);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700399 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800400 mPendingContentInsets.set(mAttachInfo.mContentInsets);
401 mPendingVisibleInsets.set(0, 0, 0, 0);
Jeff Brownc5ed5912010-07-14 18:48:53 -0700402 if (Config.LOGV) Log.v(TAG, "Added window " + mWindow);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800403 if (res < WindowManagerImpl.ADD_OKAY) {
404 mView = null;
405 mAttachInfo.mRootView = null;
406 mAdded = false;
407 unscheduleTraversals();
408 switch (res) {
409 case WindowManagerImpl.ADD_BAD_APP_TOKEN:
410 case WindowManagerImpl.ADD_BAD_SUBWINDOW_TOKEN:
411 throw new WindowManagerImpl.BadTokenException(
412 "Unable to add window -- token " + attrs.token
413 + " is not valid; is your activity running?");
414 case WindowManagerImpl.ADD_NOT_APP_TOKEN:
415 throw new WindowManagerImpl.BadTokenException(
416 "Unable to add window -- token " + attrs.token
417 + " is not for an application");
418 case WindowManagerImpl.ADD_APP_EXITING:
419 throw new WindowManagerImpl.BadTokenException(
420 "Unable to add window -- app for token " + attrs.token
421 + " is exiting");
422 case WindowManagerImpl.ADD_DUPLICATE_ADD:
423 throw new WindowManagerImpl.BadTokenException(
424 "Unable to add window -- window " + mWindow
425 + " has already been added");
426 case WindowManagerImpl.ADD_STARTING_NOT_NEEDED:
427 // Silently ignore -- we would have just removed it
428 // right away, anyway.
429 return;
430 case WindowManagerImpl.ADD_MULTIPLE_SINGLETON:
431 throw new WindowManagerImpl.BadTokenException(
432 "Unable to add window " + mWindow +
433 " -- another window of this type already exists");
434 case WindowManagerImpl.ADD_PERMISSION_DENIED:
435 throw new WindowManagerImpl.BadTokenException(
436 "Unable to add window " + mWindow +
437 " -- permission denied for this window type");
438 }
439 throw new RuntimeException(
440 "Unable to add window -- unknown error code " + res);
441 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700442
Jeff Brown00fa7bd2010-07-02 15:37:36 -0700443 if (view instanceof RootViewSurfaceTaker) {
444 mInputQueueCallback =
445 ((RootViewSurfaceTaker)view).willYouTakeTheInputQueue();
446 }
447 if (mInputQueueCallback != null) {
448 mInputQueue = new InputQueue(mInputChannel);
449 mInputQueueCallback.onInputQueueCreated(mInputQueue);
450 } else {
451 InputQueue.registerInputChannel(mInputChannel, mInputHandler,
452 Looper.myQueue());
Jeff Brown46b9ac02010-04-22 18:58:52 -0700453 }
454
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800455 view.assignParent(this);
456 mAddedTouchMode = (res&WindowManagerImpl.ADD_FLAG_IN_TOUCH_MODE) != 0;
457 mAppVisible = (res&WindowManagerImpl.ADD_FLAG_APP_VISIBLE) != 0;
458 }
459 }
460 }
461
Romain Guy529b60a2010-08-03 18:05:47 -0700462 private void enableHardwareAcceleration(WindowManager.LayoutParams attrs) {
Romain Guye4d01122010-06-16 18:44:05 -0700463 // Only enable hardware acceleration if we are not in the system process
464 // The window manager creates ViewRoots to display animated preview windows
465 // of launching apps and we don't want those to be hardware accelerated
466 if (Process.myUid() != Process.SYSTEM_UID) {
467 // Try to enable hardware acceleration if requested
Romain Guy529b60a2010-08-03 18:05:47 -0700468 if (attrs != null &&
469 (attrs.flags & WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED) != 0) {
Romain Guye4d01122010-06-16 18:44:05 -0700470 final boolean translucent = attrs.format != PixelFormat.OPAQUE;
471 mHwRenderer = HardwareRenderer.createGlRenderer(2, translucent);
472 }
473 }
474 }
475
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800476 public View getView() {
477 return mView;
478 }
479
480 final WindowLeaked getLocation() {
481 return mLocation;
482 }
483
484 void setLayoutParams(WindowManager.LayoutParams attrs, boolean newView) {
485 synchronized (this) {
The Android Open Source Project10592532009-03-18 17:39:46 -0700486 int oldSoftInputMode = mWindowAttributes.softInputMode;
Mitsuru Oshima5a2b91d2009-07-16 16:30:02 -0700487 // preserve compatible window flag if exists.
488 int compatibleWindowFlag =
489 mWindowAttributes.flags & WindowManager.LayoutParams.FLAG_COMPATIBLE_WINDOW;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800490 mWindowAttributes.copyFrom(attrs);
Mitsuru Oshima5a2b91d2009-07-16 16:30:02 -0700491 mWindowAttributes.flags |= compatibleWindowFlag;
492
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800493 if (newView) {
494 mSoftInputMode = attrs.softInputMode;
495 requestLayout();
496 }
The Android Open Source Project10592532009-03-18 17:39:46 -0700497 // Don't lose the mode we last auto-computed.
498 if ((attrs.softInputMode&WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST)
499 == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED) {
500 mWindowAttributes.softInputMode = (mWindowAttributes.softInputMode
501 & ~WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST)
502 | (oldSoftInputMode
503 & WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST);
504 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800505 mWindowAttributesChanged = true;
506 scheduleTraversals();
507 }
508 }
509
510 void handleAppVisibility(boolean visible) {
511 if (mAppVisible != visible) {
512 mAppVisible = visible;
513 scheduleTraversals();
514 }
515 }
516
517 void handleGetNewSurface() {
518 mNewSurfaceNeeded = true;
519 mFullRedrawNeeded = true;
520 scheduleTraversals();
521 }
522
523 /**
524 * {@inheritDoc}
525 */
526 public void requestLayout() {
527 checkThread();
528 mLayoutRequested = true;
529 scheduleTraversals();
530 }
531
532 /**
533 * {@inheritDoc}
534 */
535 public boolean isLayoutRequested() {
536 return mLayoutRequested;
537 }
538
539 public void invalidateChild(View child, Rect dirty) {
540 checkThread();
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700541 if (DEBUG_DRAW) Log.v(TAG, "Invalidate child: " + dirty);
542 if (mCurScrollY != 0 || mTranslator != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800543 mTempRect.set(dirty);
Romain Guy1e095972009-07-07 11:22:45 -0700544 dirty = mTempRect;
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700545 if (mCurScrollY != 0) {
Romain Guy1e095972009-07-07 11:22:45 -0700546 dirty.offset(0, -mCurScrollY);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700547 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700548 if (mTranslator != null) {
Romain Guy1e095972009-07-07 11:22:45 -0700549 mTranslator.translateRectInAppWindowToScreen(dirty);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700550 }
Romain Guy1e095972009-07-07 11:22:45 -0700551 if (mAttachInfo.mScalingRequired) {
552 dirty.inset(-1, -1);
553 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800554 }
555 mDirty.union(dirty);
556 if (!mWillDrawSoon) {
557 scheduleTraversals();
558 }
559 }
560
561 public ViewParent getParent() {
562 return null;
563 }
564
565 public ViewParent invalidateChildInParent(final int[] location, final Rect dirty) {
566 invalidateChild(null, dirty);
567 return null;
568 }
569
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700570 public boolean getChildVisibleRect(View child, Rect r, android.graphics.Point offset) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800571 if (child != mView) {
572 throw new RuntimeException("child is not mine, honest!");
573 }
574 // Note: don't apply scroll offset, because we want to know its
575 // visibility in the virtual canvas being given to the view hierarchy.
576 return r.intersect(0, 0, mWidth, mHeight);
577 }
578
579 public void bringChildToFront(View child) {
580 }
581
582 public void scheduleTraversals() {
583 if (!mTraversalScheduled) {
584 mTraversalScheduled = true;
585 sendEmptyMessage(DO_TRAVERSAL);
586 }
587 }
588
589 public void unscheduleTraversals() {
590 if (mTraversalScheduled) {
591 mTraversalScheduled = false;
592 removeMessages(DO_TRAVERSAL);
593 }
594 }
595
596 int getHostVisibility() {
597 return mAppVisible ? mView.getVisibility() : View.GONE;
598 }
Romain Guy8506ab42009-06-11 17:35:47 -0700599
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800600 private void performTraversals() {
601 // cache mView since it is used so much below...
602 final View host = mView;
603
604 if (DBG) {
605 System.out.println("======================================");
606 System.out.println("performTraversals");
607 host.debug();
608 }
609
610 if (host == null || !mAdded)
611 return;
612
613 mTraversalScheduled = false;
614 mWillDrawSoon = true;
615 boolean windowResizesToFitContent = false;
616 boolean fullRedrawNeeded = mFullRedrawNeeded;
617 boolean newSurface = false;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700618 boolean surfaceChanged = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800619 WindowManager.LayoutParams lp = mWindowAttributes;
620
621 int desiredWindowWidth;
622 int desiredWindowHeight;
623 int childWidthMeasureSpec;
624 int childHeightMeasureSpec;
625
626 final View.AttachInfo attachInfo = mAttachInfo;
627
628 final int viewVisibility = getHostVisibility();
629 boolean viewVisibilityChanged = mViewVisibility != viewVisibility
630 || mNewSurfaceNeeded;
631
632 WindowManager.LayoutParams params = null;
633 if (mWindowAttributesChanged) {
634 mWindowAttributesChanged = false;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700635 surfaceChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800636 params = lp;
637 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700638 Rect frame = mWinFrame;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800639 if (mFirst) {
640 fullRedrawNeeded = true;
641 mLayoutRequested = true;
642
Romain Guy8506ab42009-06-11 17:35:47 -0700643 DisplayMetrics packageMetrics =
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700644 mView.getContext().getResources().getDisplayMetrics();
645 desiredWindowWidth = packageMetrics.widthPixels;
646 desiredWindowHeight = packageMetrics.heightPixels;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800647
648 // For the very first time, tell the view hierarchy that it
649 // is attached to the window. Note that at this point the surface
650 // object is not initialized to its backing store, but soon it
651 // will be (assuming the window is visible).
652 attachInfo.mSurface = mSurface;
Dianne Hackborn289b9b62010-07-09 11:44:11 -0700653 attachInfo.mTranslucentWindow = PixelFormat.formatHasAlpha(lp.format);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800654 attachInfo.mHasWindowFocus = false;
655 attachInfo.mWindowVisibility = viewVisibility;
656 attachInfo.mRecomputeGlobalAttributes = false;
657 attachInfo.mKeepScreenOn = false;
658 viewVisibilityChanged = false;
Dianne Hackborn694f79b2010-03-17 19:44:59 -0700659 mLastConfiguration.setTo(host.getResources().getConfiguration());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800660 host.dispatchAttachedToWindow(attachInfo, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800661 //Log.i(TAG, "Screen on initialized: " + attachInfo.mKeepScreenOn);
svetoslavganov75986cf2009-05-14 22:28:01 -0700662
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800663 } else {
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700664 desiredWindowWidth = frame.width();
665 desiredWindowHeight = frame.height();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800666 if (desiredWindowWidth != mWidth || desiredWindowHeight != mHeight) {
Jeff Brownc5ed5912010-07-14 18:48:53 -0700667 if (DEBUG_ORIENTATION) Log.v(TAG,
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700668 "View " + host + " resized to: " + frame);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800669 fullRedrawNeeded = true;
670 mLayoutRequested = true;
671 windowResizesToFitContent = true;
672 }
673 }
674
675 if (viewVisibilityChanged) {
676 attachInfo.mWindowVisibility = viewVisibility;
677 host.dispatchWindowVisibilityChanged(viewVisibility);
678 if (viewVisibility != View.VISIBLE || mNewSurfaceNeeded) {
Romain Guy812ccbe2010-06-01 14:07:24 -0700679 if (mHwRenderer != null) {
Romain Guy2d614592010-06-09 18:21:37 -0700680 mHwRenderer.destroy();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800681 }
682 }
683 if (viewVisibility == View.GONE) {
684 // After making a window gone, we will count it as being
685 // shown for the first time the next time it gets focus.
686 mHasHadWindowFocus = false;
687 }
688 }
689
690 boolean insetsChanged = false;
Romain Guy8506ab42009-06-11 17:35:47 -0700691
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800692 if (mLayoutRequested) {
Romain Guy15df6702009-08-17 20:17:30 -0700693 // Execute enqueued actions on every layout in case a view that was detached
694 // enqueued an action after being detached
695 getRunQueue().executeActions(attachInfo.mHandler);
696
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800697 if (mFirst) {
698 host.fitSystemWindows(mAttachInfo.mContentInsets);
699 // make sure touch mode code executes by setting cached value
700 // to opposite of the added touch mode.
701 mAttachInfo.mInTouchMode = !mAddedTouchMode;
Romain Guy2d4cff62010-04-09 15:39:00 -0700702 ensureTouchModeLocally(mAddedTouchMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800703 } else {
704 if (!mAttachInfo.mContentInsets.equals(mPendingContentInsets)) {
705 mAttachInfo.mContentInsets.set(mPendingContentInsets);
706 host.fitSystemWindows(mAttachInfo.mContentInsets);
707 insetsChanged = true;
708 if (DEBUG_LAYOUT) Log.v(TAG, "Content insets changing to: "
709 + mAttachInfo.mContentInsets);
710 }
711 if (!mAttachInfo.mVisibleInsets.equals(mPendingVisibleInsets)) {
712 mAttachInfo.mVisibleInsets.set(mPendingVisibleInsets);
713 if (DEBUG_LAYOUT) Log.v(TAG, "Visible insets changing to: "
714 + mAttachInfo.mVisibleInsets);
715 }
716 if (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT
717 || lp.height == ViewGroup.LayoutParams.WRAP_CONTENT) {
718 windowResizesToFitContent = true;
719
Romain Guy8506ab42009-06-11 17:35:47 -0700720 DisplayMetrics packageMetrics =
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700721 mView.getContext().getResources().getDisplayMetrics();
722 desiredWindowWidth = packageMetrics.widthPixels;
723 desiredWindowHeight = packageMetrics.heightPixels;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800724 }
725 }
726
727 childWidthMeasureSpec = getRootMeasureSpec(desiredWindowWidth, lp.width);
728 childHeightMeasureSpec = getRootMeasureSpec(desiredWindowHeight, lp.height);
729
730 // Ask host how big it wants to be
Jeff Brownc5ed5912010-07-14 18:48:53 -0700731 if (DEBUG_ORIENTATION || DEBUG_LAYOUT) Log.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800732 "Measuring " + host + " in display " + desiredWindowWidth
733 + "x" + desiredWindowHeight + "...");
734 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
735
736 if (DBG) {
737 System.out.println("======================================");
738 System.out.println("performTraversals -- after measure");
739 host.debug();
740 }
741 }
742
743 if (attachInfo.mRecomputeGlobalAttributes) {
744 //Log.i(TAG, "Computing screen on!");
745 attachInfo.mRecomputeGlobalAttributes = false;
746 boolean oldVal = attachInfo.mKeepScreenOn;
747 attachInfo.mKeepScreenOn = false;
748 host.dispatchCollectViewAttributes(0);
749 if (attachInfo.mKeepScreenOn != oldVal) {
750 params = lp;
751 //Log.i(TAG, "Keep screen on changed: " + attachInfo.mKeepScreenOn);
752 }
753 }
754
755 if (mFirst || attachInfo.mViewVisibilityChanged) {
756 attachInfo.mViewVisibilityChanged = false;
757 int resizeMode = mSoftInputMode &
758 WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST;
759 // If we are in auto resize mode, then we need to determine
760 // what mode to use now.
761 if (resizeMode == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED) {
762 final int N = attachInfo.mScrollContainers.size();
763 for (int i=0; i<N; i++) {
764 if (attachInfo.mScrollContainers.get(i).isShown()) {
765 resizeMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE;
766 }
767 }
768 if (resizeMode == 0) {
769 resizeMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN;
770 }
771 if ((lp.softInputMode &
772 WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) != resizeMode) {
773 lp.softInputMode = (lp.softInputMode &
774 ~WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) |
775 resizeMode;
776 params = lp;
777 }
778 }
779 }
Romain Guy8506ab42009-06-11 17:35:47 -0700780
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800781 if (params != null && (host.mPrivateFlags & View.REQUEST_TRANSPARENT_REGIONS) != 0) {
782 if (!PixelFormat.formatHasAlpha(params.format)) {
783 params.format = PixelFormat.TRANSLUCENT;
784 }
785 }
786
787 boolean windowShouldResize = mLayoutRequested && windowResizesToFitContent
Romain Guy2e4f4262010-04-06 11:07:52 -0700788 && ((mWidth != host.mMeasuredWidth || mHeight != host.mMeasuredHeight)
789 || (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT &&
790 frame.width() < desiredWindowWidth && frame.width() != mWidth)
791 || (lp.height == ViewGroup.LayoutParams.WRAP_CONTENT &&
792 frame.height() < desiredWindowHeight && frame.height() != mHeight));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800793
794 final boolean computesInternalInsets =
795 attachInfo.mTreeObserver.hasComputeInternalInsetsListeners();
Romain Guy812ccbe2010-06-01 14:07:24 -0700796
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800797 boolean insetsPending = false;
798 int relayoutResult = 0;
Romain Guy812ccbe2010-06-01 14:07:24 -0700799
800 if (mFirst || windowShouldResize || insetsChanged ||
801 viewVisibilityChanged || params != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800802
803 if (viewVisibility == View.VISIBLE) {
804 // If this window is giving internal insets to the window
805 // manager, and it is being added or changing its visibility,
806 // then we want to first give the window manager "fake"
807 // insets to cause it to effectively ignore the content of
808 // the window during layout. This avoids it briefly causing
809 // other windows to resize/move based on the raw frame of the
810 // window, waiting until we can finish laying out this window
811 // and get back to the window manager with the ultimately
812 // computed insets.
Romain Guy812ccbe2010-06-01 14:07:24 -0700813 insetsPending = computesInternalInsets && (mFirst || viewVisibilityChanged);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800814 }
815
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700816 if (mSurfaceHolder != null) {
817 mSurfaceHolder.mSurfaceLock.lock();
818 mDrawingAllowed = true;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700819 }
Romain Guy812ccbe2010-06-01 14:07:24 -0700820
821 boolean hwIntialized = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800822 boolean contentInsetsChanged = false;
Romain Guy13922e02009-05-12 17:56:14 -0700823 boolean visibleInsetsChanged;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700824 boolean hadSurface = mSurface.isValid();
Romain Guy812ccbe2010-06-01 14:07:24 -0700825
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800826 try {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800827 int fl = 0;
828 if (params != null) {
829 fl = params.flags;
830 if (attachInfo.mKeepScreenOn) {
831 params.flags |= WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
832 }
833 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700834 if (DEBUG_LAYOUT) {
835 Log.i(TAG, "host=w:" + host.mMeasuredWidth + ", h:" +
836 host.mMeasuredHeight + ", params=" + params);
837 }
838 relayoutResult = relayoutWindow(params, viewVisibility, insetsPending);
839
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800840 if (params != null) {
841 params.flags = fl;
842 }
843
844 if (DEBUG_LAYOUT) Log.v(TAG, "relayout: frame=" + frame.toShortString()
845 + " content=" + mPendingContentInsets.toShortString()
846 + " visible=" + mPendingVisibleInsets.toShortString()
847 + " surface=" + mSurface);
Romain Guy8506ab42009-06-11 17:35:47 -0700848
Dianne Hackborn694f79b2010-03-17 19:44:59 -0700849 if (mPendingConfiguration.seq != 0) {
850 if (DEBUG_CONFIGURATION) Log.v(TAG, "Visible with new config: "
851 + mPendingConfiguration);
852 updateConfiguration(mPendingConfiguration, !mFirst);
853 mPendingConfiguration.seq = 0;
854 }
855
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800856 contentInsetsChanged = !mPendingContentInsets.equals(
857 mAttachInfo.mContentInsets);
858 visibleInsetsChanged = !mPendingVisibleInsets.equals(
859 mAttachInfo.mVisibleInsets);
860 if (contentInsetsChanged) {
861 mAttachInfo.mContentInsets.set(mPendingContentInsets);
862 host.fitSystemWindows(mAttachInfo.mContentInsets);
863 if (DEBUG_LAYOUT) Log.v(TAG, "Content insets changing to: "
864 + mAttachInfo.mContentInsets);
865 }
866 if (visibleInsetsChanged) {
867 mAttachInfo.mVisibleInsets.set(mPendingVisibleInsets);
868 if (DEBUG_LAYOUT) Log.v(TAG, "Visible insets changing to: "
869 + mAttachInfo.mVisibleInsets);
870 }
871
872 if (!hadSurface) {
873 if (mSurface.isValid()) {
874 // If we are creating a new surface, then we need to
875 // completely redraw it. Also, when we get to the
876 // point of drawing it we will hold off and schedule
877 // a new traversal instead. This is so we can tell the
878 // window manager about all of the windows being displayed
879 // before actually drawing them, so it can display then
880 // all at once.
881 newSurface = true;
882 fullRedrawNeeded = true;
Jack Palevich61a6e682009-10-09 17:37:50 -0700883 mPreviousTransparentRegion.setEmpty();
Romain Guy8506ab42009-06-11 17:35:47 -0700884
Romain Guy812ccbe2010-06-01 14:07:24 -0700885 if (mHwRenderer != null) {
Romain Guy2d614592010-06-09 18:21:37 -0700886 hwIntialized = mHwRenderer.initialize(mHolder);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800887 }
888 }
889 } else if (!mSurface.isValid()) {
890 // If the surface has been removed, then reset the scroll
891 // positions.
892 mLastScrolledFocus = null;
893 mScrollY = mCurScrollY = 0;
894 if (mScroller != null) {
895 mScroller.abortAnimation();
896 }
897 }
898 } catch (RemoteException e) {
899 }
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700900
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800901 if (DEBUG_ORIENTATION) Log.v(
Jeff Brownc5ed5912010-07-14 18:48:53 -0700902 TAG, "Relayout returned: frame=" + frame + ", surface=" + mSurface);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800903
904 attachInfo.mWindowLeft = frame.left;
905 attachInfo.mWindowTop = frame.top;
906
907 // !!FIXME!! This next section handles the case where we did not get the
908 // window size we asked for. We should avoid this by getting a maximum size from
909 // the window session beforehand.
910 mWidth = frame.width();
911 mHeight = frame.height();
912
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700913 if (mSurfaceHolder != null) {
914 // The app owns the surface; tell it about what is going on.
915 if (mSurface.isValid()) {
916 // XXX .copyFrom() doesn't work!
917 //mSurfaceHolder.mSurface.copyFrom(mSurface);
918 mSurfaceHolder.mSurface = mSurface;
919 }
920 mSurfaceHolder.mSurfaceLock.unlock();
921 if (mSurface.isValid()) {
922 if (!hadSurface) {
923 mSurfaceHolder.ungetCallbacks();
924
925 mIsCreating = true;
926 mSurfaceHolderCallback.surfaceCreated(mSurfaceHolder);
927 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
928 if (callbacks != null) {
929 for (SurfaceHolder.Callback c : callbacks) {
930 c.surfaceCreated(mSurfaceHolder);
931 }
932 }
933 surfaceChanged = true;
934 }
935 if (surfaceChanged) {
936 mSurfaceHolderCallback.surfaceChanged(mSurfaceHolder,
937 lp.format, mWidth, mHeight);
938 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
939 if (callbacks != null) {
940 for (SurfaceHolder.Callback c : callbacks) {
941 c.surfaceChanged(mSurfaceHolder, lp.format,
942 mWidth, mHeight);
943 }
944 }
945 }
946 mIsCreating = false;
947 } else if (hadSurface) {
948 mSurfaceHolder.ungetCallbacks();
949 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
950 mSurfaceHolderCallback.surfaceDestroyed(mSurfaceHolder);
951 if (callbacks != null) {
952 for (SurfaceHolder.Callback c : callbacks) {
953 c.surfaceDestroyed(mSurfaceHolder);
954 }
955 }
956 mSurfaceHolder.mSurfaceLock.lock();
957 // Make surface invalid.
958 //mSurfaceHolder.mSurface.copyFrom(mSurface);
959 mSurfaceHolder.mSurface = new Surface();
960 mSurfaceHolder.mSurfaceLock.unlock();
961 }
962 }
963
Romain Guy812ccbe2010-06-01 14:07:24 -0700964 if (hwIntialized) {
Romain Guy2d614592010-06-09 18:21:37 -0700965 mHwRenderer.setup(mWidth, mHeight, mAttachInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800966 }
967
968 boolean focusChangedDueToTouchMode = ensureTouchModeLocally(
Romain Guy2d4cff62010-04-09 15:39:00 -0700969 (relayoutResult&WindowManagerImpl.RELAYOUT_IN_TOUCH_MODE) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800970 if (focusChangedDueToTouchMode || mWidth != host.mMeasuredWidth
971 || mHeight != host.mMeasuredHeight || contentInsetsChanged) {
972 childWidthMeasureSpec = getRootMeasureSpec(mWidth, lp.width);
973 childHeightMeasureSpec = getRootMeasureSpec(mHeight, lp.height);
974
975 if (DEBUG_LAYOUT) Log.v(TAG, "Ooops, something changed! mWidth="
976 + mWidth + " measuredWidth=" + host.mMeasuredWidth
977 + " mHeight=" + mHeight
978 + " measuredHeight" + host.mMeasuredHeight
979 + " coveredInsetsChanged=" + contentInsetsChanged);
Romain Guy8506ab42009-06-11 17:35:47 -0700980
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800981 // Ask host how big it wants to be
982 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
983
984 // Implementation of weights from WindowManager.LayoutParams
985 // We just grow the dimensions as needed and re-measure if
986 // needs be
987 int width = host.mMeasuredWidth;
988 int height = host.mMeasuredHeight;
989 boolean measureAgain = false;
990
991 if (lp.horizontalWeight > 0.0f) {
992 width += (int) ((mWidth - width) * lp.horizontalWeight);
993 childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(width,
994 MeasureSpec.EXACTLY);
995 measureAgain = true;
996 }
997 if (lp.verticalWeight > 0.0f) {
998 height += (int) ((mHeight - height) * lp.verticalWeight);
999 childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(height,
1000 MeasureSpec.EXACTLY);
1001 measureAgain = true;
1002 }
1003
1004 if (measureAgain) {
1005 if (DEBUG_LAYOUT) Log.v(TAG,
1006 "And hey let's measure once more: width=" + width
1007 + " height=" + height);
1008 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
1009 }
1010
1011 mLayoutRequested = true;
1012 }
1013 }
1014
1015 final boolean didLayout = mLayoutRequested;
1016 boolean triggerGlobalLayoutListener = didLayout
1017 || attachInfo.mRecomputeGlobalAttributes;
1018 if (didLayout) {
1019 mLayoutRequested = false;
1020 mScrollMayChange = true;
1021 if (DEBUG_ORIENTATION || DEBUG_LAYOUT) Log.v(
Jeff Brownc5ed5912010-07-14 18:48:53 -07001022 TAG, "Laying out " + host + " to (" +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001023 host.mMeasuredWidth + ", " + host.mMeasuredHeight + ")");
Romain Guy13922e02009-05-12 17:56:14 -07001024 long startTime = 0L;
1025 if (Config.DEBUG && ViewDebug.profileLayout) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001026 startTime = SystemClock.elapsedRealtime();
1027 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001028 host.layout(0, 0, host.mMeasuredWidth, host.mMeasuredHeight);
1029
Romain Guy13922e02009-05-12 17:56:14 -07001030 if (Config.DEBUG && ViewDebug.consistencyCheckEnabled) {
1031 if (!host.dispatchConsistencyCheck(ViewDebug.CONSISTENCY_LAYOUT)) {
1032 throw new IllegalStateException("The view hierarchy is an inconsistent state,"
1033 + "please refer to the logs with the tag "
1034 + ViewDebug.CONSISTENCY_LOG_TAG + " for more infomation.");
1035 }
1036 }
1037
1038 if (Config.DEBUG && ViewDebug.profileLayout) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001039 EventLog.writeEvent(60001, SystemClock.elapsedRealtime() - startTime);
1040 }
1041
1042 // By this point all views have been sized and positionned
1043 // We can compute the transparent area
1044
1045 if ((host.mPrivateFlags & View.REQUEST_TRANSPARENT_REGIONS) != 0) {
1046 // start out transparent
1047 // TODO: AVOID THAT CALL BY CACHING THE RESULT?
1048 host.getLocationInWindow(mTmpLocation);
1049 mTransparentRegion.set(mTmpLocation[0], mTmpLocation[1],
1050 mTmpLocation[0] + host.mRight - host.mLeft,
1051 mTmpLocation[1] + host.mBottom - host.mTop);
1052
1053 host.gatherTransparentRegion(mTransparentRegion);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001054 if (mTranslator != null) {
1055 mTranslator.translateRegionInWindowToScreen(mTransparentRegion);
1056 }
1057
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001058 if (!mTransparentRegion.equals(mPreviousTransparentRegion)) {
1059 mPreviousTransparentRegion.set(mTransparentRegion);
1060 // reconfigure window manager
1061 try {
1062 sWindowSession.setTransparentRegion(mWindow, mTransparentRegion);
1063 } catch (RemoteException e) {
1064 }
1065 }
1066 }
1067
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001068 if (DBG) {
1069 System.out.println("======================================");
1070 System.out.println("performTraversals -- after setFrame");
1071 host.debug();
1072 }
1073 }
1074
1075 if (triggerGlobalLayoutListener) {
1076 attachInfo.mRecomputeGlobalAttributes = false;
1077 attachInfo.mTreeObserver.dispatchOnGlobalLayout();
1078 }
1079
1080 if (computesInternalInsets) {
1081 ViewTreeObserver.InternalInsetsInfo insets = attachInfo.mGivenInternalInsets;
1082 final Rect givenContent = attachInfo.mGivenInternalInsets.contentInsets;
1083 final Rect givenVisible = attachInfo.mGivenInternalInsets.visibleInsets;
1084 givenContent.left = givenContent.top = givenContent.right
1085 = givenContent.bottom = givenVisible.left = givenVisible.top
1086 = givenVisible.right = givenVisible.bottom = 0;
1087 attachInfo.mTreeObserver.dispatchOnComputeInternalInsets(insets);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001088 Rect contentInsets = insets.contentInsets;
1089 Rect visibleInsets = insets.visibleInsets;
1090 if (mTranslator != null) {
1091 contentInsets = mTranslator.getTranslatedContentInsets(contentInsets);
1092 visibleInsets = mTranslator.getTranslatedVisbileInsets(visibleInsets);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001093 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001094 if (insetsPending || !mLastGivenInsets.equals(insets)) {
1095 mLastGivenInsets.set(insets);
1096 try {
1097 sWindowSession.setInsets(mWindow, insets.mTouchableInsets,
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001098 contentInsets, visibleInsets);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001099 } catch (RemoteException e) {
1100 }
1101 }
1102 }
Romain Guy8506ab42009-06-11 17:35:47 -07001103
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001104 if (mFirst) {
1105 // handle first focus request
1106 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: mView.hasFocus()="
1107 + mView.hasFocus());
1108 if (mView != null) {
1109 if (!mView.hasFocus()) {
1110 mView.requestFocus(View.FOCUS_FORWARD);
1111 mFocusedView = mRealFocusedView = mView.findFocus();
1112 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: requested focused view="
1113 + mFocusedView);
1114 } else {
1115 mRealFocusedView = mView.findFocus();
1116 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: existing focused view="
1117 + mRealFocusedView);
1118 }
1119 }
1120 }
1121
1122 mFirst = false;
1123 mWillDrawSoon = false;
1124 mNewSurfaceNeeded = false;
1125 mViewVisibility = viewVisibility;
1126
1127 if (mAttachInfo.mHasWindowFocus) {
1128 final boolean imTarget = WindowManager.LayoutParams
1129 .mayUseInputMethod(mWindowAttributes.flags);
1130 if (imTarget != mLastWasImTarget) {
1131 mLastWasImTarget = imTarget;
1132 InputMethodManager imm = InputMethodManager.peekInstance();
1133 if (imm != null && imTarget) {
1134 imm.startGettingWindowFocus(mView);
1135 imm.onWindowFocus(mView, mView.findFocus(),
1136 mWindowAttributes.softInputMode,
1137 !mHasHadWindowFocus, mWindowAttributes.flags);
1138 }
1139 }
1140 }
Romain Guy8506ab42009-06-11 17:35:47 -07001141
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001142 boolean cancelDraw = attachInfo.mTreeObserver.dispatchOnPreDraw();
1143
1144 if (!cancelDraw && !newSurface) {
1145 mFullRedrawNeeded = false;
1146 draw(fullRedrawNeeded);
1147
1148 if ((relayoutResult&WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0
1149 || mReportNextDraw) {
1150 if (LOCAL_LOGV) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001151 Log.v(TAG, "FINISHED DRAWING: " + mWindowAttributes.getTitle());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001152 }
1153 mReportNextDraw = false;
Dianne Hackbornd76b67c2010-07-13 17:48:30 -07001154 if (mSurfaceHolder != null && mSurface.isValid()) {
1155 mSurfaceHolderCallback.surfaceRedrawNeeded(mSurfaceHolder);
1156 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
1157 if (callbacks != null) {
1158 for (SurfaceHolder.Callback c : callbacks) {
1159 if (c instanceof SurfaceHolder.Callback2) {
1160 ((SurfaceHolder.Callback2)c).surfaceRedrawNeeded(
1161 mSurfaceHolder);
1162 }
1163 }
1164 }
1165 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001166 try {
1167 sWindowSession.finishDrawing(mWindow);
1168 } catch (RemoteException e) {
1169 }
1170 }
1171 } else {
1172 // We were supposed to report when we are done drawing. Since we canceled the
1173 // draw, remember it here.
1174 if ((relayoutResult&WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0) {
1175 mReportNextDraw = true;
1176 }
1177 if (fullRedrawNeeded) {
1178 mFullRedrawNeeded = true;
1179 }
1180 // Try again
1181 scheduleTraversals();
1182 }
1183 }
1184
1185 public void requestTransparentRegion(View child) {
1186 // the test below should not fail unless someone is messing with us
1187 checkThread();
1188 if (mView == child) {
1189 mView.mPrivateFlags |= View.REQUEST_TRANSPARENT_REGIONS;
1190 // Need to make sure we re-evaluate the window attributes next
1191 // time around, to ensure the window has the correct format.
1192 mWindowAttributesChanged = true;
1193 }
1194 }
1195
1196 /**
1197 * Figures out the measure spec for the root view in a window based on it's
1198 * layout params.
1199 *
1200 * @param windowSize
1201 * The available width or height of the window
1202 *
1203 * @param rootDimension
1204 * The layout params for one dimension (width or height) of the
1205 * window.
1206 *
1207 * @return The measure spec to use to measure the root view.
1208 */
1209 private int getRootMeasureSpec(int windowSize, int rootDimension) {
1210 int measureSpec;
1211 switch (rootDimension) {
1212
Romain Guy980a9382010-01-08 15:06:28 -08001213 case ViewGroup.LayoutParams.MATCH_PARENT:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001214 // Window can't resize. Force root view to be windowSize.
1215 measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.EXACTLY);
1216 break;
1217 case ViewGroup.LayoutParams.WRAP_CONTENT:
1218 // Window can resize. Set max size for root view.
1219 measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.AT_MOST);
1220 break;
1221 default:
1222 // Window wants to be an exact size. Force root view to be that size.
1223 measureSpec = MeasureSpec.makeMeasureSpec(rootDimension, MeasureSpec.EXACTLY);
1224 break;
1225 }
1226 return measureSpec;
1227 }
1228
1229 private void draw(boolean fullRedrawNeeded) {
1230 Surface surface = mSurface;
1231 if (surface == null || !surface.isValid()) {
1232 return;
1233 }
1234
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001235 if (!sFirstDrawComplete) {
1236 synchronized (sFirstDrawHandlers) {
1237 sFirstDrawComplete = true;
Romain Guy812ccbe2010-06-01 14:07:24 -07001238 final int count = sFirstDrawHandlers.size();
1239 for (int i = 0; i< count; i++) {
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001240 post(sFirstDrawHandlers.get(i));
1241 }
1242 }
1243 }
1244
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001245 scrollToRectOrFocus(null, false);
1246
1247 if (mAttachInfo.mViewScrollChanged) {
1248 mAttachInfo.mViewScrollChanged = false;
1249 mAttachInfo.mTreeObserver.dispatchOnScrollChanged();
1250 }
Romain Guy8506ab42009-06-11 17:35:47 -07001251
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001252 int yoff;
Romain Guy5bcdff42009-05-14 21:27:18 -07001253 final boolean scrolling = mScroller != null && mScroller.computeScrollOffset();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001254 if (scrolling) {
1255 yoff = mScroller.getCurrY();
1256 } else {
1257 yoff = mScrollY;
1258 }
1259 if (mCurScrollY != yoff) {
1260 mCurScrollY = yoff;
1261 fullRedrawNeeded = true;
1262 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001263 float appScale = mAttachInfo.mApplicationScale;
1264 boolean scalingRequired = mAttachInfo.mScalingRequired;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001265
1266 Rect dirty = mDirty;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001267 if (mSurfaceHolder != null) {
1268 // The app owns the surface, we won't draw.
1269 dirty.setEmpty();
1270 return;
1271 }
1272
Romain Guy2d614592010-06-09 18:21:37 -07001273 if (mHwRenderer != null && mHwRenderer.isEnabled()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001274 if (!dirty.isEmpty()) {
Romain Guydbd77cd2010-07-09 10:36:05 -07001275 mHwRenderer.draw(mView, mAttachInfo, yoff);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001276 }
Romain Guy812ccbe2010-06-01 14:07:24 -07001277
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001278 if (scrolling) {
1279 mFullRedrawNeeded = true;
1280 scheduleTraversals();
1281 }
Romain Guy812ccbe2010-06-01 14:07:24 -07001282
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001283 return;
1284 }
1285
Romain Guy5bcdff42009-05-14 21:27:18 -07001286 if (fullRedrawNeeded) {
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001287 mAttachInfo.mIgnoreDirtyState = true;
Mitsuru Oshima61324e52009-07-21 15:40:36 -07001288 dirty.union(0, 0, (int) (mWidth * appScale + 0.5f), (int) (mHeight * appScale + 0.5f));
Romain Guy5bcdff42009-05-14 21:27:18 -07001289 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001290
1291 if (DEBUG_ORIENTATION || DEBUG_DRAW) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001292 Log.v(TAG, "Draw " + mView + "/"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001293 + mWindowAttributes.getTitle()
1294 + ": dirty={" + dirty.left + "," + dirty.top
1295 + "," + dirty.right + "," + dirty.bottom + "} surface="
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001296 + surface + " surface.isValid()=" + surface.isValid() + ", appScale:" +
1297 appScale + ", width=" + mWidth + ", height=" + mHeight);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001298 }
1299
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001300 if (!dirty.isEmpty() || mIsAnimating) {
1301 Canvas canvas;
1302 try {
1303 int left = dirty.left;
1304 int top = dirty.top;
1305 int right = dirty.right;
1306 int bottom = dirty.bottom;
1307 canvas = surface.lockCanvas(dirty);
Romain Guy5bcdff42009-05-14 21:27:18 -07001308
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001309 if (left != dirty.left || top != dirty.top || right != dirty.right ||
1310 bottom != dirty.bottom) {
1311 mAttachInfo.mIgnoreDirtyState = true;
1312 }
1313
1314 // TODO: Do this in native
1315 canvas.setDensity(mDensity);
1316 } catch (Surface.OutOfResourcesException e) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001317 Log.e(TAG, "OutOfResourcesException locking surface", e);
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001318 // TODO: we should ask the window manager to do something!
1319 // for now we just do nothing
1320 return;
1321 } catch (IllegalArgumentException e) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001322 Log.e(TAG, "IllegalArgumentException locking surface", e);
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001323 // TODO: we should ask the window manager to do something!
1324 // for now we just do nothing
1325 return;
Romain Guy5bcdff42009-05-14 21:27:18 -07001326 }
1327
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001328 try {
1329 if (!dirty.isEmpty() || mIsAnimating) {
1330 long startTime = 0L;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001331
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001332 if (DEBUG_ORIENTATION || DEBUG_DRAW) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001333 Log.v(TAG, "Surface " + surface + " drawing to bitmap w="
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001334 + canvas.getWidth() + ", h=" + canvas.getHeight());
1335 //canvas.drawARGB(255, 255, 0, 0);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001336 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001337
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001338 if (Config.DEBUG && ViewDebug.profileDrawing) {
1339 startTime = SystemClock.elapsedRealtime();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001340 }
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001341
1342 // If this bitmap's format includes an alpha channel, we
1343 // need to clear it before drawing so that the child will
1344 // properly re-composite its drawing on a transparent
1345 // background. This automatically respects the clip/dirty region
1346 // or
1347 // If we are applying an offset, we need to clear the area
1348 // where the offset doesn't appear to avoid having garbage
1349 // left in the blank areas.
1350 if (!canvas.isOpaque() || yoff != 0) {
1351 canvas.drawColor(0, PorterDuff.Mode.CLEAR);
1352 }
1353
1354 dirty.setEmpty();
1355 mIsAnimating = false;
1356 mAttachInfo.mDrawingTime = SystemClock.uptimeMillis();
1357 mView.mPrivateFlags |= View.DRAWN;
1358
1359 if (DEBUG_DRAW) {
1360 Context cxt = mView.getContext();
1361 Log.i(TAG, "Drawing: package:" + cxt.getPackageName() +
1362 ", metrics=" + cxt.getResources().getDisplayMetrics() +
1363 ", compatibilityInfo=" + cxt.getResources().getCompatibilityInfo());
1364 }
1365 int saveCount = canvas.save(Canvas.MATRIX_SAVE_FLAG);
1366 try {
1367 canvas.translate(0, -yoff);
1368 if (mTranslator != null) {
1369 mTranslator.translateCanvas(canvas);
1370 }
1371 canvas.setScreenDensity(scalingRequired
1372 ? DisplayMetrics.DENSITY_DEVICE : 0);
1373 mView.draw(canvas);
1374 } finally {
1375 mAttachInfo.mIgnoreDirtyState = false;
1376 canvas.restoreToCount(saveCount);
1377 }
1378
1379 if (Config.DEBUG && ViewDebug.consistencyCheckEnabled) {
1380 mView.dispatchConsistencyCheck(ViewDebug.CONSISTENCY_DRAWING);
1381 }
1382
1383 if (SHOW_FPS || Config.DEBUG && ViewDebug.showFps) {
1384 int now = (int)SystemClock.elapsedRealtime();
1385 if (sDrawTime != 0) {
1386 nativeShowFPS(canvas, now - sDrawTime);
1387 }
1388 sDrawTime = now;
1389 }
1390
1391 if (Config.DEBUG && ViewDebug.profileDrawing) {
1392 EventLog.writeEvent(60000, SystemClock.elapsedRealtime() - startTime);
1393 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001394 }
1395
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001396 } finally {
1397 surface.unlockCanvasAndPost(canvas);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001398 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001399 }
1400
1401 if (LOCAL_LOGV) {
Jeff Brownc5ed5912010-07-14 18:48:53 -07001402 Log.v(TAG, "Surface " + surface + " unlockCanvasAndPost");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001403 }
Romain Guy8506ab42009-06-11 17:35:47 -07001404
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001405 if (scrolling) {
1406 mFullRedrawNeeded = true;
1407 scheduleTraversals();
1408 }
1409 }
1410
1411 boolean scrollToRectOrFocus(Rect rectangle, boolean immediate) {
1412 final View.AttachInfo attachInfo = mAttachInfo;
1413 final Rect ci = attachInfo.mContentInsets;
1414 final Rect vi = attachInfo.mVisibleInsets;
1415 int scrollY = 0;
1416 boolean handled = false;
Romain Guy8506ab42009-06-11 17:35:47 -07001417
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001418 if (vi.left > ci.left || vi.top > ci.top
1419 || vi.right > ci.right || vi.bottom > ci.bottom) {
1420 // We'll assume that we aren't going to change the scroll
1421 // offset, since we want to avoid that unless it is actually
1422 // going to make the focus visible... otherwise we scroll
1423 // all over the place.
1424 scrollY = mScrollY;
1425 // We can be called for two different situations: during a draw,
1426 // to update the scroll position if the focus has changed (in which
1427 // case 'rectangle' is null), or in response to a
1428 // requestChildRectangleOnScreen() call (in which case 'rectangle'
1429 // is non-null and we just want to scroll to whatever that
1430 // rectangle is).
1431 View focus = mRealFocusedView;
Romain Guye8b16522009-07-14 13:06:42 -07001432
1433 // When in touch mode, focus points to the previously focused view,
1434 // which may have been removed from the view hierarchy. The following
Joe Onoratob71193b2009-11-24 18:34:42 -05001435 // line checks whether the view is still in our hierarchy.
1436 if (focus == null || focus.mAttachInfo != mAttachInfo) {
Romain Guye8b16522009-07-14 13:06:42 -07001437 mRealFocusedView = null;
1438 return false;
1439 }
1440
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001441 if (focus != mLastScrolledFocus) {
1442 // If the focus has changed, then ignore any requests to scroll
1443 // to a rectangle; first we want to make sure the entire focus
1444 // view is visible.
1445 rectangle = null;
1446 }
1447 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Eval scroll: focus=" + focus
1448 + " rectangle=" + rectangle + " ci=" + ci
1449 + " vi=" + vi);
1450 if (focus == mLastScrolledFocus && !mScrollMayChange
1451 && rectangle == null) {
1452 // Optimization: if the focus hasn't changed since last
1453 // time, and no layout has happened, then just leave things
1454 // as they are.
1455 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Keeping scroll y="
1456 + mScrollY + " vi=" + vi.toShortString());
1457 } else if (focus != null) {
1458 // We need to determine if the currently focused view is
1459 // within the visible part of the window and, if not, apply
1460 // a pan so it can be seen.
1461 mLastScrolledFocus = focus;
1462 mScrollMayChange = false;
1463 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Need to scroll?");
1464 // Try to find the rectangle from the focus view.
1465 if (focus.getGlobalVisibleRect(mVisRect, null)) {
1466 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Root w="
1467 + mView.getWidth() + " h=" + mView.getHeight()
1468 + " ci=" + ci.toShortString()
1469 + " vi=" + vi.toShortString());
1470 if (rectangle == null) {
1471 focus.getFocusedRect(mTempRect);
1472 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Focus " + focus
1473 + ": focusRect=" + mTempRect.toShortString());
Dianne Hackborn1c6a8942010-03-23 16:34:20 -07001474 if (mView instanceof ViewGroup) {
1475 ((ViewGroup) mView).offsetDescendantRectToMyCoords(
1476 focus, mTempRect);
1477 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001478 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1479 "Focus in window: focusRect="
1480 + mTempRect.toShortString()
1481 + " visRect=" + mVisRect.toShortString());
1482 } else {
1483 mTempRect.set(rectangle);
1484 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1485 "Request scroll to rect: "
1486 + mTempRect.toShortString()
1487 + " visRect=" + mVisRect.toShortString());
1488 }
1489 if (mTempRect.intersect(mVisRect)) {
1490 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1491 "Focus window visible rect: "
1492 + mTempRect.toShortString());
1493 if (mTempRect.height() >
1494 (mView.getHeight()-vi.top-vi.bottom)) {
1495 // If the focus simply is not going to fit, then
1496 // best is probably just to leave things as-is.
1497 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1498 "Too tall; leaving scrollY=" + scrollY);
1499 } else if ((mTempRect.top-scrollY) < vi.top) {
1500 scrollY -= vi.top - (mTempRect.top-scrollY);
1501 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1502 "Top covered; scrollY=" + scrollY);
1503 } else if ((mTempRect.bottom-scrollY)
1504 > (mView.getHeight()-vi.bottom)) {
1505 scrollY += (mTempRect.bottom-scrollY)
1506 - (mView.getHeight()-vi.bottom);
1507 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1508 "Bottom covered; scrollY=" + scrollY);
1509 }
1510 handled = true;
1511 }
1512 }
1513 }
1514 }
Romain Guy8506ab42009-06-11 17:35:47 -07001515
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001516 if (scrollY != mScrollY) {
1517 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Pan scroll changed: old="
1518 + mScrollY + " , new=" + scrollY);
1519 if (!immediate) {
1520 if (mScroller == null) {
1521 mScroller = new Scroller(mView.getContext());
1522 }
1523 mScroller.startScroll(0, mScrollY, 0, scrollY-mScrollY);
1524 } else if (mScroller != null) {
1525 mScroller.abortAnimation();
1526 }
1527 mScrollY = scrollY;
1528 }
Romain Guy8506ab42009-06-11 17:35:47 -07001529
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001530 return handled;
1531 }
Romain Guy8506ab42009-06-11 17:35:47 -07001532
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001533 public void requestChildFocus(View child, View focused) {
1534 checkThread();
1535 if (mFocusedView != focused) {
1536 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(mFocusedView, focused);
1537 scheduleTraversals();
1538 }
1539 mFocusedView = mRealFocusedView = focused;
1540 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Request child focus: focus now "
1541 + mFocusedView);
1542 }
1543
1544 public void clearChildFocus(View child) {
1545 checkThread();
1546
1547 View oldFocus = mFocusedView;
1548
1549 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Clearing child focus");
1550 mFocusedView = mRealFocusedView = null;
1551 if (mView != null && !mView.hasFocus()) {
1552 // If a view gets the focus, the listener will be invoked from requestChildFocus()
1553 if (!mView.requestFocus(View.FOCUS_FORWARD)) {
1554 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
1555 }
1556 } else if (oldFocus != null) {
1557 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
1558 }
1559 }
1560
1561
1562 public void focusableViewAvailable(View v) {
1563 checkThread();
1564
1565 if (mView != null && !mView.hasFocus()) {
1566 v.requestFocus();
1567 } else {
1568 // the one case where will transfer focus away from the current one
1569 // is if the current view is a view group that prefers to give focus
1570 // to its children first AND the view is a descendant of it.
1571 mFocusedView = mView.findFocus();
1572 boolean descendantsHaveDibsOnFocus =
1573 (mFocusedView instanceof ViewGroup) &&
1574 (((ViewGroup) mFocusedView).getDescendantFocusability() ==
1575 ViewGroup.FOCUS_AFTER_DESCENDANTS);
1576 if (descendantsHaveDibsOnFocus && isViewDescendantOf(v, mFocusedView)) {
1577 // If a view gets the focus, the listener will be invoked from requestChildFocus()
1578 v.requestFocus();
1579 }
1580 }
1581 }
1582
1583 public void recomputeViewAttributes(View child) {
1584 checkThread();
1585 if (mView == child) {
1586 mAttachInfo.mRecomputeGlobalAttributes = true;
1587 if (!mWillDrawSoon) {
1588 scheduleTraversals();
1589 }
1590 }
1591 }
1592
1593 void dispatchDetachedFromWindow() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001594 if (mView != null) {
1595 mView.dispatchDetachedFromWindow();
1596 }
1597
1598 mView = null;
1599 mAttachInfo.mRootView = null;
Mathias Agopian5583dc62009-07-09 16:28:11 -07001600 mAttachInfo.mSurface = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001601
Romain Guy812ccbe2010-06-01 14:07:24 -07001602 if (mHwRenderer != null) {
Romain Guy2d614592010-06-09 18:21:37 -07001603 mHwRenderer.destroy();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001604 }
Dianne Hackborn0586a1b2009-09-06 21:08:27 -07001605 mSurface.release();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001606
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001607 if (mInputChannel != null) {
1608 if (mInputQueueCallback != null) {
1609 mInputQueueCallback.onInputQueueDestroyed(mInputQueue);
1610 mInputQueueCallback = null;
1611 } else {
1612 InputQueue.unregisterInputChannel(mInputChannel);
Jeff Brown46b9ac02010-04-22 18:58:52 -07001613 }
1614 }
1615
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001616 try {
1617 sWindowSession.remove(mWindow);
1618 } catch (RemoteException e) {
1619 }
Jeff Brown349703e2010-06-22 01:27:15 -07001620
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001621 // Dispose the input channel after removing the window so the Window Manager
1622 // doesn't interpret the input channel being closed as an abnormal termination.
1623 if (mInputChannel != null) {
1624 mInputChannel.dispose();
1625 mInputChannel = null;
Jeff Brown349703e2010-06-22 01:27:15 -07001626 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001627 }
Romain Guy8506ab42009-06-11 17:35:47 -07001628
Dianne Hackborn694f79b2010-03-17 19:44:59 -07001629 void updateConfiguration(Configuration config, boolean force) {
1630 if (DEBUG_CONFIGURATION) Log.v(TAG,
1631 "Applying new config to window "
1632 + mWindowAttributes.getTitle()
1633 + ": " + config);
1634 synchronized (sConfigCallbacks) {
1635 for (int i=sConfigCallbacks.size()-1; i>=0; i--) {
1636 sConfigCallbacks.get(i).onConfigurationChanged(config);
1637 }
1638 }
1639 if (mView != null) {
1640 // At this point the resources have been updated to
1641 // have the most recent config, whatever that is. Use
1642 // the on in them which may be newer.
1643 if (mView != null) {
1644 config = mView.getResources().getConfiguration();
1645 }
1646 if (force || mLastConfiguration.diff(config) != 0) {
1647 mLastConfiguration.setTo(config);
1648 mView.dispatchConfigurationChanged(config);
1649 }
1650 }
1651 }
1652
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001653 /**
1654 * Return true if child is an ancestor of parent, (or equal to the parent).
1655 */
1656 private static boolean isViewDescendantOf(View child, View parent) {
1657 if (child == parent) {
1658 return true;
1659 }
1660
1661 final ViewParent theParent = child.getParent();
1662 return (theParent instanceof ViewGroup) && isViewDescendantOf((View) theParent, parent);
1663 }
1664
Romain Guycdb86672010-03-18 18:54:50 -07001665 private static void forceLayout(View view) {
1666 view.forceLayout();
1667 if (view instanceof ViewGroup) {
1668 ViewGroup group = (ViewGroup) view;
1669 final int count = group.getChildCount();
1670 for (int i = 0; i < count; i++) {
1671 forceLayout(group.getChildAt(i));
1672 }
1673 }
1674 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001675
1676 public final static int DO_TRAVERSAL = 1000;
1677 public final static int DIE = 1001;
1678 public final static int RESIZED = 1002;
1679 public final static int RESIZED_REPORT = 1003;
1680 public final static int WINDOW_FOCUS_CHANGED = 1004;
1681 public final static int DISPATCH_KEY = 1005;
1682 public final static int DISPATCH_POINTER = 1006;
1683 public final static int DISPATCH_TRACKBALL = 1007;
1684 public final static int DISPATCH_APP_VISIBILITY = 1008;
1685 public final static int DISPATCH_GET_NEW_SURFACE = 1009;
1686 public final static int FINISHED_EVENT = 1010;
1687 public final static int DISPATCH_KEY_FROM_IME = 1011;
1688 public final static int FINISH_INPUT_CONNECTION = 1012;
1689 public final static int CHECK_FOCUS = 1013;
Dianne Hackbornffa42482009-09-23 22:20:11 -07001690 public final static int CLOSE_SYSTEM_DIALOGS = 1014;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001691
1692 @Override
1693 public void handleMessage(Message msg) {
1694 switch (msg.what) {
1695 case View.AttachInfo.INVALIDATE_MSG:
1696 ((View) msg.obj).invalidate();
1697 break;
1698 case View.AttachInfo.INVALIDATE_RECT_MSG:
1699 final View.AttachInfo.InvalidateInfo info = (View.AttachInfo.InvalidateInfo) msg.obj;
1700 info.target.invalidate(info.left, info.top, info.right, info.bottom);
1701 info.release();
1702 break;
1703 case DO_TRAVERSAL:
1704 if (mProfile) {
1705 Debug.startMethodTracing("ViewRoot");
1706 }
1707
1708 performTraversals();
1709
1710 if (mProfile) {
1711 Debug.stopMethodTracing();
1712 mProfile = false;
1713 }
1714 break;
1715 case FINISHED_EVENT:
1716 handleFinishedEvent(msg.arg1, msg.arg2 != 0);
1717 break;
1718 case DISPATCH_KEY:
1719 if (LOCAL_LOGV) Log.v(
Jeff Brownc5ed5912010-07-14 18:48:53 -07001720 TAG, "Dispatching key "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001721 + msg.obj + " to " + mView);
1722 deliverKeyEvent((KeyEvent)msg.obj, true);
1723 break;
The Android Open Source Project10592532009-03-18 17:39:46 -07001724 case DISPATCH_POINTER: {
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001725 MotionEvent event = (MotionEvent) msg.obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001726 try {
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001727 deliverPointerEvent(event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001728 } finally {
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001729 event.recycle();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001730 if (LOCAL_LOGV || WATCH_POINTER) Log.i(TAG, "Done dispatching!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001731 }
The Android Open Source Project10592532009-03-18 17:39:46 -07001732 } break;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001733 case DISPATCH_TRACKBALL: {
1734 MotionEvent event = (MotionEvent) msg.obj;
1735 try {
1736 deliverTrackballEvent(event);
1737 } finally {
1738 event.recycle();
1739 }
1740 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001741 case DISPATCH_APP_VISIBILITY:
1742 handleAppVisibility(msg.arg1 != 0);
1743 break;
1744 case DISPATCH_GET_NEW_SURFACE:
1745 handleGetNewSurface();
1746 break;
1747 case RESIZED:
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001748 ResizedInfo ri = (ResizedInfo)msg.obj;
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001749
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001750 if (mWinFrame.width() == msg.arg1 && mWinFrame.height() == msg.arg2
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001751 && mPendingContentInsets.equals(ri.coveredInsets)
Dianne Hackbornd49258f2010-03-26 00:44:29 -07001752 && mPendingVisibleInsets.equals(ri.visibleInsets)
1753 && ((ResizedInfo)msg.obj).newConfig == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001754 break;
1755 }
1756 // fall through...
1757 case RESIZED_REPORT:
1758 if (mAdded) {
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001759 Configuration config = ((ResizedInfo)msg.obj).newConfig;
1760 if (config != null) {
Dianne Hackborn694f79b2010-03-17 19:44:59 -07001761 updateConfiguration(config, false);
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001762 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001763 mWinFrame.left = 0;
1764 mWinFrame.right = msg.arg1;
1765 mWinFrame.top = 0;
1766 mWinFrame.bottom = msg.arg2;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001767 mPendingContentInsets.set(((ResizedInfo)msg.obj).coveredInsets);
1768 mPendingVisibleInsets.set(((ResizedInfo)msg.obj).visibleInsets);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001769 if (msg.what == RESIZED_REPORT) {
1770 mReportNextDraw = true;
1771 }
Romain Guycdb86672010-03-18 18:54:50 -07001772
1773 if (mView != null) {
1774 forceLayout(mView);
1775 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001776 requestLayout();
1777 }
1778 break;
1779 case WINDOW_FOCUS_CHANGED: {
1780 if (mAdded) {
1781 boolean hasWindowFocus = msg.arg1 != 0;
1782 mAttachInfo.mHasWindowFocus = hasWindowFocus;
1783 if (hasWindowFocus) {
1784 boolean inTouchMode = msg.arg2 != 0;
Romain Guy2d4cff62010-04-09 15:39:00 -07001785 ensureTouchModeLocally(inTouchMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001786
Romain Guy812ccbe2010-06-01 14:07:24 -07001787 if (mHwRenderer != null) {
Romain Guy2d614592010-06-09 18:21:37 -07001788 mHwRenderer.initializeIfNeeded(mWidth, mHeight, mAttachInfo, mHolder);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001789 }
1790 }
Romain Guy8506ab42009-06-11 17:35:47 -07001791
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001792 mLastWasImTarget = WindowManager.LayoutParams
1793 .mayUseInputMethod(mWindowAttributes.flags);
Romain Guy8506ab42009-06-11 17:35:47 -07001794
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001795 InputMethodManager imm = InputMethodManager.peekInstance();
1796 if (mView != null) {
1797 if (hasWindowFocus && imm != null && mLastWasImTarget) {
1798 imm.startGettingWindowFocus(mView);
1799 }
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07001800 mAttachInfo.mKeyDispatchState.reset();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001801 mView.dispatchWindowFocusChanged(hasWindowFocus);
1802 }
svetoslavganov75986cf2009-05-14 22:28:01 -07001803
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001804 // Note: must be done after the focus change callbacks,
1805 // so all of the view state is set up correctly.
1806 if (hasWindowFocus) {
1807 if (imm != null && mLastWasImTarget) {
1808 imm.onWindowFocus(mView, mView.findFocus(),
1809 mWindowAttributes.softInputMode,
1810 !mHasHadWindowFocus, mWindowAttributes.flags);
1811 }
1812 // Clear the forward bit. We can just do this directly, since
1813 // the window manager doesn't care about it.
1814 mWindowAttributes.softInputMode &=
1815 ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
1816 ((WindowManager.LayoutParams)mView.getLayoutParams())
1817 .softInputMode &=
1818 ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
1819 mHasHadWindowFocus = true;
1820 }
svetoslavganov75986cf2009-05-14 22:28:01 -07001821
1822 if (hasWindowFocus && mView != null) {
1823 sendAccessibilityEvents();
1824 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001825 }
1826 } break;
1827 case DIE:
Dianne Hackborn94d69142009-09-28 22:14:42 -07001828 doDie();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001829 break;
The Android Open Source Project10592532009-03-18 17:39:46 -07001830 case DISPATCH_KEY_FROM_IME: {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001831 if (LOCAL_LOGV) Log.v(
Jeff Brownc5ed5912010-07-14 18:48:53 -07001832 TAG, "Dispatching key "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001833 + msg.obj + " from IME to " + mView);
The Android Open Source Project10592532009-03-18 17:39:46 -07001834 KeyEvent event = (KeyEvent)msg.obj;
1835 if ((event.getFlags()&KeyEvent.FLAG_FROM_SYSTEM) != 0) {
1836 // The IME is trying to say this event is from the
1837 // system! Bad bad bad!
Romain Guy812ccbe2010-06-01 14:07:24 -07001838 event = KeyEvent.changeFlags(event, event.getFlags() & ~KeyEvent.FLAG_FROM_SYSTEM);
The Android Open Source Project10592532009-03-18 17:39:46 -07001839 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001840 deliverKeyEventToViewHierarchy((KeyEvent)msg.obj, false);
The Android Open Source Project10592532009-03-18 17:39:46 -07001841 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001842 case FINISH_INPUT_CONNECTION: {
1843 InputMethodManager imm = InputMethodManager.peekInstance();
1844 if (imm != null) {
1845 imm.reportFinishInputConnection((InputConnection)msg.obj);
1846 }
1847 } break;
1848 case CHECK_FOCUS: {
1849 InputMethodManager imm = InputMethodManager.peekInstance();
1850 if (imm != null) {
1851 imm.checkFocus();
1852 }
1853 } break;
Dianne Hackbornffa42482009-09-23 22:20:11 -07001854 case CLOSE_SYSTEM_DIALOGS: {
1855 if (mView != null) {
1856 mView.onCloseSystemDialogs((String)msg.obj);
1857 }
1858 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001859 }
1860 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07001861
1862 private void finishKeyEvent(KeyEvent event) {
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001863 if (mFinishedCallback != null) {
1864 mFinishedCallback.run();
1865 mFinishedCallback = null;
Jeff Brown46b9ac02010-04-22 18:58:52 -07001866 }
1867 }
1868
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001869 /**
1870 * Something in the current window tells us we need to change the touch mode. For
1871 * example, we are not in touch mode, and the user touches the screen.
1872 *
1873 * If the touch mode has changed, tell the window manager, and handle it locally.
1874 *
1875 * @param inTouchMode Whether we want to be in touch mode.
1876 * @return True if the touch mode changed and focus changed was changed as a result
1877 */
1878 boolean ensureTouchMode(boolean inTouchMode) {
1879 if (DBG) Log.d("touchmode", "ensureTouchMode(" + inTouchMode + "), current "
1880 + "touch mode is " + mAttachInfo.mInTouchMode);
1881 if (mAttachInfo.mInTouchMode == inTouchMode) return false;
1882
1883 // tell the window manager
1884 try {
1885 sWindowSession.setInTouchMode(inTouchMode);
1886 } catch (RemoteException e) {
1887 throw new RuntimeException(e);
1888 }
1889
1890 // handle the change
Romain Guy2d4cff62010-04-09 15:39:00 -07001891 return ensureTouchModeLocally(inTouchMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001892 }
1893
1894 /**
1895 * Ensure that the touch mode for this window is set, and if it is changing,
1896 * take the appropriate action.
1897 * @param inTouchMode Whether we want to be in touch mode.
1898 * @return True if the touch mode changed and focus changed was changed as a result
1899 */
Romain Guy2d4cff62010-04-09 15:39:00 -07001900 private boolean ensureTouchModeLocally(boolean inTouchMode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001901 if (DBG) Log.d("touchmode", "ensureTouchModeLocally(" + inTouchMode + "), current "
1902 + "touch mode is " + mAttachInfo.mInTouchMode);
1903
1904 if (mAttachInfo.mInTouchMode == inTouchMode) return false;
1905
1906 mAttachInfo.mInTouchMode = inTouchMode;
1907 mAttachInfo.mTreeObserver.dispatchOnTouchModeChanged(inTouchMode);
1908
Romain Guy2d4cff62010-04-09 15:39:00 -07001909 return (inTouchMode) ? enterTouchMode() : leaveTouchMode();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001910 }
1911
1912 private boolean enterTouchMode() {
1913 if (mView != null) {
1914 if (mView.hasFocus()) {
1915 // note: not relying on mFocusedView here because this could
1916 // be when the window is first being added, and mFocused isn't
1917 // set yet.
1918 final View focused = mView.findFocus();
1919 if (focused != null && !focused.isFocusableInTouchMode()) {
1920
1921 final ViewGroup ancestorToTakeFocus =
1922 findAncestorToTakeFocusInTouchMode(focused);
1923 if (ancestorToTakeFocus != null) {
1924 // there is an ancestor that wants focus after its descendants that
1925 // is focusable in touch mode.. give it focus
1926 return ancestorToTakeFocus.requestFocus();
1927 } else {
1928 // nothing appropriate to have focus in touch mode, clear it out
1929 mView.unFocus();
1930 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(focused, null);
1931 mFocusedView = null;
1932 return true;
1933 }
1934 }
1935 }
1936 }
1937 return false;
1938 }
1939
1940
1941 /**
1942 * Find an ancestor of focused that wants focus after its descendants and is
1943 * focusable in touch mode.
1944 * @param focused The currently focused view.
1945 * @return An appropriate view, or null if no such view exists.
1946 */
1947 private ViewGroup findAncestorToTakeFocusInTouchMode(View focused) {
1948 ViewParent parent = focused.getParent();
1949 while (parent instanceof ViewGroup) {
1950 final ViewGroup vgParent = (ViewGroup) parent;
1951 if (vgParent.getDescendantFocusability() == ViewGroup.FOCUS_AFTER_DESCENDANTS
1952 && vgParent.isFocusableInTouchMode()) {
1953 return vgParent;
1954 }
1955 if (vgParent.isRootNamespace()) {
1956 return null;
1957 } else {
1958 parent = vgParent.getParent();
1959 }
1960 }
1961 return null;
1962 }
1963
1964 private boolean leaveTouchMode() {
1965 if (mView != null) {
1966 if (mView.hasFocus()) {
1967 // i learned the hard way to not trust mFocusedView :)
1968 mFocusedView = mView.findFocus();
1969 if (!(mFocusedView instanceof ViewGroup)) {
1970 // some view has focus, let it keep it
1971 return false;
1972 } else if (((ViewGroup)mFocusedView).getDescendantFocusability() !=
1973 ViewGroup.FOCUS_AFTER_DESCENDANTS) {
1974 // some view group has focus, and doesn't prefer its children
1975 // over itself for focus, so let them keep it.
1976 return false;
1977 }
1978 }
1979
1980 // find the best view to give focus to in this brave new non-touch-mode
1981 // world
1982 final View focused = focusSearch(null, View.FOCUS_DOWN);
1983 if (focused != null) {
1984 return focused.requestFocus(View.FOCUS_DOWN);
1985 }
1986 }
1987 return false;
1988 }
1989
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001990 private void deliverPointerEvent(MotionEvent event) {
1991 if (mTranslator != null) {
1992 mTranslator.translateEventInScreenToAppWindow(event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001993 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001994
1995 boolean handled;
1996 if (mView != null && mAdded) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001997
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001998 // enter touch mode on the down
1999 boolean isDown = event.getAction() == MotionEvent.ACTION_DOWN;
2000 if (isDown) {
2001 ensureTouchMode(true);
2002 }
2003 if(Config.LOGV) {
2004 captureMotionLog("captureDispatchPointer", event);
2005 }
2006 if (mCurScrollY != 0) {
2007 event.offsetLocation(0, mCurScrollY);
2008 }
2009 if (MEASURE_LATENCY) {
2010 lt.sample("A Dispatching TouchEvents", System.nanoTime() - event.getEventTimeNano());
2011 }
2012 handled = mView.dispatchTouchEvent(event);
2013 if (MEASURE_LATENCY) {
2014 lt.sample("B Dispatched TouchEvents ", System.nanoTime() - event.getEventTimeNano());
2015 }
2016 if (!handled && isDown) {
2017 int edgeSlop = mViewConfiguration.getScaledEdgeSlop();
2018
2019 final int edgeFlags = event.getEdgeFlags();
2020 int direction = View.FOCUS_UP;
2021 int x = (int)event.getX();
2022 int y = (int)event.getY();
2023 final int[] deltas = new int[2];
2024
2025 if ((edgeFlags & MotionEvent.EDGE_TOP) != 0) {
2026 direction = View.FOCUS_DOWN;
2027 if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
2028 deltas[0] = edgeSlop;
2029 x += edgeSlop;
2030 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
2031 deltas[0] = -edgeSlop;
2032 x -= edgeSlop;
2033 }
2034 } else if ((edgeFlags & MotionEvent.EDGE_BOTTOM) != 0) {
2035 direction = View.FOCUS_UP;
2036 if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
2037 deltas[0] = edgeSlop;
2038 x += edgeSlop;
2039 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
2040 deltas[0] = -edgeSlop;
2041 x -= edgeSlop;
2042 }
2043 } else if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
2044 direction = View.FOCUS_RIGHT;
2045 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
2046 direction = View.FOCUS_LEFT;
2047 }
2048
2049 if (edgeFlags != 0 && mView instanceof ViewGroup) {
2050 View nearest = FocusFinder.getInstance().findNearestTouchable(
2051 ((ViewGroup) mView), x, y, direction, deltas);
2052 if (nearest != null) {
2053 event.offsetLocation(deltas[0], deltas[1]);
2054 event.setEdgeFlags(0);
2055 mView.dispatchTouchEvent(event);
2056 }
2057 }
2058 }
2059 }
2060 }
2061
2062 private void deliverTrackballEvent(MotionEvent event) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002063 if (DEBUG_TRACKBALL) Log.v(TAG, "Motion event:" + event);
2064
2065 boolean handled = false;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002066 if (mView != null && mAdded) {
2067 handled = mView.dispatchTrackballEvent(event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002068 if (handled) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002069 // If we reach this, we delivered a trackball event to mView and
2070 // mView consumed it. Because we will not translate the trackball
2071 // event into a key event, touch mode will not exit, so we exit
2072 // touch mode here.
2073 ensureTouchMode(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002074 return;
2075 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002076
2077 // Otherwise we could do something here, like changing the focus
2078 // or something?
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002079 }
2080
2081 final TrackballAxis x = mTrackballAxisX;
2082 final TrackballAxis y = mTrackballAxisY;
2083
2084 long curTime = SystemClock.uptimeMillis();
2085 if ((mLastTrackballTime+MAX_TRACKBALL_DELAY) < curTime) {
2086 // It has been too long since the last movement,
2087 // so restart at the beginning.
2088 x.reset(0);
2089 y.reset(0);
2090 mLastTrackballTime = curTime;
2091 }
2092
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002093 final int action = event.getAction();
2094 final int metastate = event.getMetaState();
2095 switch (action) {
2096 case MotionEvent.ACTION_DOWN:
2097 x.reset(2);
2098 y.reset(2);
2099 deliverKeyEvent(new KeyEvent(curTime, curTime,
2100 KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_CENTER,
2101 0, metastate), false);
2102 break;
2103 case MotionEvent.ACTION_UP:
2104 x.reset(2);
2105 y.reset(2);
2106 deliverKeyEvent(new KeyEvent(curTime, curTime,
2107 KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_CENTER,
2108 0, metastate), false);
2109 break;
2110 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002111
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002112 if (DEBUG_TRACKBALL) Log.v(TAG, "TB X=" + x.position + " step="
2113 + x.step + " dir=" + x.dir + " acc=" + x.acceleration
2114 + " move=" + event.getX()
2115 + " / Y=" + y.position + " step="
2116 + y.step + " dir=" + y.dir + " acc=" + y.acceleration
2117 + " move=" + event.getY());
2118 final float xOff = x.collect(event.getX(), event.getEventTime(), "X");
2119 final float yOff = y.collect(event.getY(), event.getEventTime(), "Y");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002120
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002121 // Generate DPAD events based on the trackball movement.
2122 // We pick the axis that has moved the most as the direction of
2123 // the DPAD. When we generate DPAD events for one axis, then the
2124 // other axis is reset -- we don't want to perform DPAD jumps due
2125 // to slight movements in the trackball when making major movements
2126 // along the other axis.
2127 int keycode = 0;
2128 int movement = 0;
2129 float accel = 1;
2130 if (xOff > yOff) {
2131 movement = x.generate((2/event.getXPrecision()));
2132 if (movement != 0) {
2133 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_RIGHT
2134 : KeyEvent.KEYCODE_DPAD_LEFT;
2135 accel = x.acceleration;
2136 y.reset(2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002137 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002138 } else if (yOff > 0) {
2139 movement = y.generate((2/event.getYPrecision()));
2140 if (movement != 0) {
2141 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_DOWN
2142 : KeyEvent.KEYCODE_DPAD_UP;
2143 accel = y.acceleration;
2144 x.reset(2);
2145 }
2146 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002147
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002148 if (keycode != 0) {
2149 if (movement < 0) movement = -movement;
2150 int accelMovement = (int)(movement * accel);
2151 if (DEBUG_TRACKBALL) Log.v(TAG, "Move: movement=" + movement
2152 + " accelMovement=" + accelMovement
2153 + " accel=" + accel);
2154 if (accelMovement > movement) {
2155 if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: "
2156 + keycode);
2157 movement--;
2158 deliverKeyEvent(new KeyEvent(curTime, curTime,
2159 KeyEvent.ACTION_MULTIPLE, keycode,
2160 accelMovement-movement, metastate), false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002161 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002162 while (movement > 0) {
2163 if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: "
2164 + keycode);
2165 movement--;
2166 curTime = SystemClock.uptimeMillis();
2167 deliverKeyEvent(new KeyEvent(curTime, curTime,
2168 KeyEvent.ACTION_DOWN, keycode, 0, event.getMetaState()), false);
2169 deliverKeyEvent(new KeyEvent(curTime, curTime,
2170 KeyEvent.ACTION_UP, keycode, 0, metastate), false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002171 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002172 mLastTrackballTime = curTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002173 }
2174 }
2175
2176 /**
2177 * @param keyCode The key code
2178 * @return True if the key is directional.
2179 */
2180 static boolean isDirectional(int keyCode) {
2181 switch (keyCode) {
2182 case KeyEvent.KEYCODE_DPAD_LEFT:
2183 case KeyEvent.KEYCODE_DPAD_RIGHT:
2184 case KeyEvent.KEYCODE_DPAD_UP:
2185 case KeyEvent.KEYCODE_DPAD_DOWN:
2186 return true;
2187 }
2188 return false;
2189 }
2190
2191 /**
2192 * Returns true if this key is a keyboard key.
2193 * @param keyEvent The key event.
2194 * @return whether this key is a keyboard key.
2195 */
2196 private static boolean isKeyboardKey(KeyEvent keyEvent) {
2197 final int convertedKey = keyEvent.getUnicodeChar();
2198 return convertedKey > 0;
2199 }
2200
2201
2202
2203 /**
2204 * See if the key event means we should leave touch mode (and leave touch
2205 * mode if so).
2206 * @param event The key event.
2207 * @return Whether this key event should be consumed (meaning the act of
2208 * leaving touch mode alone is considered the event).
2209 */
2210 private boolean checkForLeavingTouchModeAndConsume(KeyEvent event) {
Adam Powell51a6bee2010-03-15 14:07:28 -07002211 final int action = event.getAction();
2212 if (action != KeyEvent.ACTION_DOWN && action != KeyEvent.ACTION_MULTIPLE) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002213 return false;
2214 }
2215 if ((event.getFlags()&KeyEvent.FLAG_KEEP_TOUCH_MODE) != 0) {
2216 return false;
2217 }
2218
2219 // only relevant if we are in touch mode
2220 if (!mAttachInfo.mInTouchMode) {
2221 return false;
2222 }
2223
2224 // if something like an edit text has focus and the user is typing,
2225 // leave touch mode
2226 //
2227 // note: the condition of not being a keyboard key is kind of a hacky
2228 // approximation of whether we think the focused view will want the
2229 // key; if we knew for sure whether the focused view would consume
2230 // the event, that would be better.
2231 if (isKeyboardKey(event) && mView != null && mView.hasFocus()) {
2232 mFocusedView = mView.findFocus();
2233 if ((mFocusedView instanceof ViewGroup)
2234 && ((ViewGroup) mFocusedView).getDescendantFocusability() ==
2235 ViewGroup.FOCUS_AFTER_DESCENDANTS) {
2236 // something has focus, but is holding it weakly as a container
2237 return false;
2238 }
2239 if (ensureTouchMode(false)) {
2240 throw new IllegalStateException("should not have changed focus "
2241 + "when leaving touch mode while a view has focus.");
2242 }
2243 return false;
2244 }
2245
2246 if (isDirectional(event.getKeyCode())) {
2247 // no view has focus, so we leave touch mode (and find something
2248 // to give focus to). the event is consumed if we were able to
2249 // find something to give focus to.
2250 return ensureTouchMode(false);
2251 }
2252 return false;
2253 }
2254
2255 /**
Romain Guy8506ab42009-06-11 17:35:47 -07002256 * log motion events
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002257 */
2258 private static void captureMotionLog(String subTag, MotionEvent ev) {
Romain Guy8506ab42009-06-11 17:35:47 -07002259 //check dynamic switch
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002260 if (ev == null ||
2261 SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_EVENT, 0) == 0) {
2262 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002263 }
Romain Guy8506ab42009-06-11 17:35:47 -07002264
2265 StringBuilder sb = new StringBuilder(subTag + ": ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002266 sb.append(ev.getDownTime()).append(',');
2267 sb.append(ev.getEventTime()).append(',');
2268 sb.append(ev.getAction()).append(',');
Romain Guy8506ab42009-06-11 17:35:47 -07002269 sb.append(ev.getX()).append(',');
2270 sb.append(ev.getY()).append(',');
2271 sb.append(ev.getPressure()).append(',');
2272 sb.append(ev.getSize()).append(',');
2273 sb.append(ev.getMetaState()).append(',');
2274 sb.append(ev.getXPrecision()).append(',');
2275 sb.append(ev.getYPrecision()).append(',');
2276 sb.append(ev.getDeviceId()).append(',');
2277 sb.append(ev.getEdgeFlags());
2278 Log.d(TAG, sb.toString());
2279 }
2280 /**
2281 * log motion events
2282 */
2283 private static void captureKeyLog(String subTag, KeyEvent ev) {
2284 //check dynamic switch
2285 if (ev == null ||
2286 SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_EVENT, 0) == 0) {
2287 return;
2288 }
2289 StringBuilder sb = new StringBuilder(subTag + ": ");
2290 sb.append(ev.getDownTime()).append(',');
2291 sb.append(ev.getEventTime()).append(',');
2292 sb.append(ev.getAction()).append(',');
2293 sb.append(ev.getKeyCode()).append(',');
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002294 sb.append(ev.getRepeatCount()).append(',');
2295 sb.append(ev.getMetaState()).append(',');
2296 sb.append(ev.getDeviceId()).append(',');
2297 sb.append(ev.getScanCode());
Romain Guy8506ab42009-06-11 17:35:47 -07002298 Log.d(TAG, sb.toString());
2299 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002300
2301 int enqueuePendingEvent(Object event, boolean sendDone) {
2302 int seq = mPendingEventSeq+1;
2303 if (seq < 0) seq = 0;
2304 mPendingEventSeq = seq;
2305 mPendingEvents.put(seq, event);
2306 return sendDone ? seq : -seq;
2307 }
2308
2309 Object retrievePendingEvent(int seq) {
2310 if (seq < 0) seq = -seq;
2311 Object event = mPendingEvents.get(seq);
2312 if (event != null) {
2313 mPendingEvents.remove(seq);
2314 }
2315 return event;
2316 }
Romain Guy8506ab42009-06-11 17:35:47 -07002317
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002318 private void deliverKeyEvent(KeyEvent event, boolean sendDone) {
2319 // If mView is null, we just consume the key event because it doesn't
2320 // make sense to do anything else with it.
Romain Guy812ccbe2010-06-01 14:07:24 -07002321 boolean handled = mView == null || mView.dispatchKeyEventPreIme(event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002322 if (handled) {
2323 if (sendDone) {
2324 if (LOCAL_LOGV) Log.v(
Jeff Brownc5ed5912010-07-14 18:48:53 -07002325 TAG, "Telling window manager key is finished");
Jeff Brown46b9ac02010-04-22 18:58:52 -07002326 finishKeyEvent(event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002327 }
2328 return;
2329 }
2330 // If it is possible for this window to interact with the input
2331 // method window, then we want to first dispatch our key events
2332 // to the input method.
2333 if (mLastWasImTarget) {
2334 InputMethodManager imm = InputMethodManager.peekInstance();
2335 if (imm != null && mView != null) {
2336 int seq = enqueuePendingEvent(event, sendDone);
2337 if (DEBUG_IMF) Log.v(TAG, "Sending key event to IME: seq="
2338 + seq + " event=" + event);
2339 imm.dispatchKeyEvent(mView.getContext(), seq, event,
2340 mInputMethodCallback);
2341 return;
2342 }
2343 }
2344 deliverKeyEventToViewHierarchy(event, sendDone);
2345 }
2346
2347 void handleFinishedEvent(int seq, boolean handled) {
2348 final KeyEvent event = (KeyEvent)retrievePendingEvent(seq);
2349 if (DEBUG_IMF) Log.v(TAG, "IME finished event: seq=" + seq
2350 + " handled=" + handled + " event=" + event);
2351 if (event != null) {
2352 final boolean sendDone = seq >= 0;
2353 if (!handled) {
2354 deliverKeyEventToViewHierarchy(event, sendDone);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002355 } else if (sendDone) {
2356 if (LOCAL_LOGV) Log.v(
Jeff Brownc5ed5912010-07-14 18:48:53 -07002357 TAG, "Telling window manager key is finished");
Jeff Brown46b9ac02010-04-22 18:58:52 -07002358 finishKeyEvent(event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002359 } else {
Jeff Brownc5ed5912010-07-14 18:48:53 -07002360 Log.w(TAG, "handleFinishedEvent(seq=" + seq
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002361 + " handled=" + handled + " ev=" + event
2362 + ") neither delivering nor finishing key");
2363 }
2364 }
2365 }
Romain Guy8506ab42009-06-11 17:35:47 -07002366
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002367 private void deliverKeyEventToViewHierarchy(KeyEvent event, boolean sendDone) {
2368 try {
2369 if (mView != null && mAdded) {
2370 final int action = event.getAction();
2371 boolean isDown = (action == KeyEvent.ACTION_DOWN);
2372
2373 if (checkForLeavingTouchModeAndConsume(event)) {
2374 return;
Romain Guy8506ab42009-06-11 17:35:47 -07002375 }
2376
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002377 if (Config.LOGV) {
2378 captureKeyLog("captureDispatchKeyEvent", event);
2379 }
2380 boolean keyHandled = mView.dispatchKeyEvent(event);
2381
2382 if (!keyHandled && isDown) {
2383 int direction = 0;
2384 switch (event.getKeyCode()) {
2385 case KeyEvent.KEYCODE_DPAD_LEFT:
2386 direction = View.FOCUS_LEFT;
2387 break;
2388 case KeyEvent.KEYCODE_DPAD_RIGHT:
2389 direction = View.FOCUS_RIGHT;
2390 break;
2391 case KeyEvent.KEYCODE_DPAD_UP:
2392 direction = View.FOCUS_UP;
2393 break;
2394 case KeyEvent.KEYCODE_DPAD_DOWN:
2395 direction = View.FOCUS_DOWN;
2396 break;
2397 }
2398
2399 if (direction != 0) {
2400
2401 View focused = mView != null ? mView.findFocus() : null;
2402 if (focused != null) {
2403 View v = focused.focusSearch(direction);
2404 boolean focusPassed = false;
2405 if (v != null && v != focused) {
2406 // do the math the get the interesting rect
2407 // of previous focused into the coord system of
2408 // newly focused view
2409 focused.getFocusedRect(mTempRect);
Dianne Hackborn1c6a8942010-03-23 16:34:20 -07002410 if (mView instanceof ViewGroup) {
2411 ((ViewGroup) mView).offsetDescendantRectToMyCoords(
2412 focused, mTempRect);
2413 ((ViewGroup) mView).offsetRectIntoDescendantCoords(
2414 v, mTempRect);
2415 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002416 focusPassed = v.requestFocus(direction, mTempRect);
2417 }
2418
2419 if (!focusPassed) {
2420 mView.dispatchUnhandledMove(focused, direction);
2421 } else {
2422 playSoundEffect(SoundEffectConstants.getContantForFocusDirection(direction));
2423 }
2424 }
2425 }
2426 }
2427 }
2428
2429 } finally {
2430 if (sendDone) {
2431 if (LOCAL_LOGV) Log.v(
Jeff Brownc5ed5912010-07-14 18:48:53 -07002432 TAG, "Telling window manager key is finished");
Jeff Brown46b9ac02010-04-22 18:58:52 -07002433 finishKeyEvent(event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002434 }
2435 // Let the exception fall through -- the looper will catch
2436 // it and take care of the bad app for us.
2437 }
2438 }
2439
2440 private AudioManager getAudioManager() {
2441 if (mView == null) {
2442 throw new IllegalStateException("getAudioManager called when there is no mView");
2443 }
2444 if (mAudioManager == null) {
2445 mAudioManager = (AudioManager) mView.getContext().getSystemService(Context.AUDIO_SERVICE);
2446 }
2447 return mAudioManager;
2448 }
2449
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002450 private int relayoutWindow(WindowManager.LayoutParams params, int viewVisibility,
2451 boolean insetsPending) throws RemoteException {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002452
2453 float appScale = mAttachInfo.mApplicationScale;
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002454 boolean restore = false;
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002455 if (params != null && mTranslator != null) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07002456 restore = true;
2457 params.backup();
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002458 mTranslator.translateWindowLayout(params);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002459 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002460 if (params != null) {
2461 if (DBG) Log.d(TAG, "WindowLayout in layoutWindow:" + params);
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002462 }
Dianne Hackborn694f79b2010-03-17 19:44:59 -07002463 mPendingConfiguration.seq = 0;
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002464 int relayoutResult = sWindowSession.relayout(
2465 mWindow, params,
Mitsuru Oshima61324e52009-07-21 15:40:36 -07002466 (int) (mView.mMeasuredWidth * appScale + 0.5f),
2467 (int) (mView.mMeasuredHeight * appScale + 0.5f),
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002468 viewVisibility, insetsPending, mWinFrame,
Dianne Hackborn694f79b2010-03-17 19:44:59 -07002469 mPendingContentInsets, mPendingVisibleInsets,
2470 mPendingConfiguration, mSurface);
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002471 if (restore) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07002472 params.restore();
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002473 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002474
2475 if (mTranslator != null) {
2476 mTranslator.translateRectInScreenToAppWinFrame(mWinFrame);
2477 mTranslator.translateRectInScreenToAppWindow(mPendingContentInsets);
2478 mTranslator.translateRectInScreenToAppWindow(mPendingVisibleInsets);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002479 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002480 return relayoutResult;
2481 }
Romain Guy8506ab42009-06-11 17:35:47 -07002482
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002483 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002484 * {@inheritDoc}
2485 */
2486 public void playSoundEffect(int effectId) {
2487 checkThread();
2488
Jean-Michel Trivi13b18fd2010-05-05 09:18:15 -07002489 try {
2490 final AudioManager audioManager = getAudioManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002491
Jean-Michel Trivi13b18fd2010-05-05 09:18:15 -07002492 switch (effectId) {
2493 case SoundEffectConstants.CLICK:
2494 audioManager.playSoundEffect(AudioManager.FX_KEY_CLICK);
2495 return;
2496 case SoundEffectConstants.NAVIGATION_DOWN:
2497 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_DOWN);
2498 return;
2499 case SoundEffectConstants.NAVIGATION_LEFT:
2500 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_LEFT);
2501 return;
2502 case SoundEffectConstants.NAVIGATION_RIGHT:
2503 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_RIGHT);
2504 return;
2505 case SoundEffectConstants.NAVIGATION_UP:
2506 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_UP);
2507 return;
2508 default:
2509 throw new IllegalArgumentException("unknown effect id " + effectId +
2510 " not defined in " + SoundEffectConstants.class.getCanonicalName());
2511 }
2512 } catch (IllegalStateException e) {
2513 // Exception thrown by getAudioManager() when mView is null
2514 Log.e(TAG, "FATAL EXCEPTION when attempting to play sound effect: " + e);
2515 e.printStackTrace();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002516 }
2517 }
2518
2519 /**
2520 * {@inheritDoc}
2521 */
2522 public boolean performHapticFeedback(int effectId, boolean always) {
2523 try {
2524 return sWindowSession.performHapticFeedback(mWindow, effectId, always);
2525 } catch (RemoteException e) {
2526 return false;
2527 }
2528 }
2529
2530 /**
2531 * {@inheritDoc}
2532 */
2533 public View focusSearch(View focused, int direction) {
2534 checkThread();
2535 if (!(mView instanceof ViewGroup)) {
2536 return null;
2537 }
2538 return FocusFinder.getInstance().findNextFocus((ViewGroup) mView, focused, direction);
2539 }
2540
2541 public void debug() {
2542 mView.debug();
2543 }
2544
2545 public void die(boolean immediate) {
Dianne Hackborn94d69142009-09-28 22:14:42 -07002546 if (immediate) {
2547 doDie();
2548 } else {
2549 sendEmptyMessage(DIE);
2550 }
2551 }
2552
2553 void doDie() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002554 checkThread();
Jeff Brownb75fa302010-07-15 23:47:29 -07002555 if (LOCAL_LOGV) Log.v(TAG, "DIE in " + this + " of " + mSurface);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002556 synchronized (this) {
2557 if (mAdded && !mFirst) {
2558 int viewVisibility = mView.getVisibility();
2559 boolean viewVisibilityChanged = mViewVisibility != viewVisibility;
2560 if (mWindowAttributesChanged || viewVisibilityChanged) {
2561 // If layout params have been changed, first give them
2562 // to the window manager to make sure it has the correct
2563 // animation info.
2564 try {
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002565 if ((relayoutWindow(mWindowAttributes, viewVisibility, false)
2566 & WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002567 sWindowSession.finishDrawing(mWindow);
2568 }
2569 } catch (RemoteException e) {
2570 }
2571 }
2572
Dianne Hackborn0586a1b2009-09-06 21:08:27 -07002573 mSurface.release();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002574 }
2575 if (mAdded) {
2576 mAdded = false;
Dianne Hackborn94d69142009-09-28 22:14:42 -07002577 dispatchDetachedFromWindow();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002578 }
2579 }
2580 }
2581
2582 public void dispatchFinishedEvent(int seq, boolean handled) {
2583 Message msg = obtainMessage(FINISHED_EVENT);
2584 msg.arg1 = seq;
2585 msg.arg2 = handled ? 1 : 0;
2586 sendMessage(msg);
2587 }
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002588
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002589 public void dispatchResized(int w, int h, Rect coveredInsets,
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002590 Rect visibleInsets, boolean reportDraw, Configuration newConfig) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002591 if (DEBUG_LAYOUT) Log.v(TAG, "Resizing " + this + ": w=" + w
2592 + " h=" + h + " coveredInsets=" + coveredInsets.toShortString()
2593 + " visibleInsets=" + visibleInsets.toShortString()
2594 + " reportDraw=" + reportDraw);
2595 Message msg = obtainMessage(reportDraw ? RESIZED_REPORT :RESIZED);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002596 if (mTranslator != null) {
2597 mTranslator.translateRectInScreenToAppWindow(coveredInsets);
2598 mTranslator.translateRectInScreenToAppWindow(visibleInsets);
2599 w *= mTranslator.applicationInvertedScale;
2600 h *= mTranslator.applicationInvertedScale;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002601 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002602 msg.arg1 = w;
2603 msg.arg2 = h;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002604 ResizedInfo ri = new ResizedInfo();
2605 ri.coveredInsets = new Rect(coveredInsets);
2606 ri.visibleInsets = new Rect(visibleInsets);
2607 ri.newConfig = newConfig;
2608 msg.obj = ri;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002609 sendMessage(msg);
2610 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002611
2612 private Runnable mFinishedCallback;
2613
2614 private final InputHandler mInputHandler = new InputHandler() {
2615 public void handleKey(KeyEvent event, Runnable finishedCallback) {
2616 mFinishedCallback = finishedCallback;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002617
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002618 dispatchKey(event);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002619 }
2620
Jeff Brownc5ed5912010-07-14 18:48:53 -07002621 public void handleMotion(MotionEvent event, Runnable finishedCallback) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002622 finishedCallback.run();
2623
Jeff Brownc5ed5912010-07-14 18:48:53 -07002624 dispatchMotion(event);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002625 }
2626 };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002627
2628 public void dispatchKey(KeyEvent event) {
2629 if (event.getAction() == KeyEvent.ACTION_DOWN) {
2630 //noinspection ConstantConditions
2631 if (false && event.getKeyCode() == KeyEvent.KEYCODE_CAMERA) {
Romain Guy812ccbe2010-06-01 14:07:24 -07002632 if (DBG) Log.d("keydisp", "===================================================");
2633 if (DBG) Log.d("keydisp", "Focused view Hierarchy is:");
2634
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002635 debug();
2636
Romain Guy812ccbe2010-06-01 14:07:24 -07002637 if (DBG) Log.d("keydisp", "===================================================");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002638 }
2639 }
2640
2641 Message msg = obtainMessage(DISPATCH_KEY);
2642 msg.obj = event;
2643
2644 if (LOCAL_LOGV) Log.v(
Jeff Brownc5ed5912010-07-14 18:48:53 -07002645 TAG, "sending key " + event + " to " + mView);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002646
2647 sendMessageAtTime(msg, event.getEventTime());
2648 }
Jeff Brownc5ed5912010-07-14 18:48:53 -07002649
2650 public void dispatchMotion(MotionEvent event) {
2651 int source = event.getSource();
2652 if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
2653 dispatchPointer(event);
2654 } else if ((source & InputDevice.SOURCE_CLASS_TRACKBALL) != 0) {
2655 dispatchTrackball(event);
2656 } else {
2657 // TODO
2658 Log.v(TAG, "Dropping unsupported motion event (unimplemented): " + event);
2659 }
2660 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002661
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002662 public void dispatchPointer(MotionEvent event) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002663 Message msg = obtainMessage(DISPATCH_POINTER);
2664 msg.obj = event;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002665 sendMessageAtTime(msg, event.getEventTime());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002666 }
2667
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002668 public void dispatchTrackball(MotionEvent event) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002669 Message msg = obtainMessage(DISPATCH_TRACKBALL);
2670 msg.obj = event;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002671 sendMessageAtTime(msg, event.getEventTime());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002672 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07002673
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002674 public void dispatchAppVisibility(boolean visible) {
2675 Message msg = obtainMessage(DISPATCH_APP_VISIBILITY);
2676 msg.arg1 = visible ? 1 : 0;
2677 sendMessage(msg);
2678 }
2679
2680 public void dispatchGetNewSurface() {
2681 Message msg = obtainMessage(DISPATCH_GET_NEW_SURFACE);
2682 sendMessage(msg);
2683 }
2684
2685 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
2686 Message msg = Message.obtain();
2687 msg.what = WINDOW_FOCUS_CHANGED;
2688 msg.arg1 = hasFocus ? 1 : 0;
2689 msg.arg2 = inTouchMode ? 1 : 0;
2690 sendMessage(msg);
2691 }
2692
Dianne Hackbornffa42482009-09-23 22:20:11 -07002693 public void dispatchCloseSystemDialogs(String reason) {
2694 Message msg = Message.obtain();
2695 msg.what = CLOSE_SYSTEM_DIALOGS;
2696 msg.obj = reason;
2697 sendMessage(msg);
2698 }
2699
svetoslavganov75986cf2009-05-14 22:28:01 -07002700 /**
2701 * The window is getting focus so if there is anything focused/selected
2702 * send an {@link AccessibilityEvent} to announce that.
2703 */
2704 private void sendAccessibilityEvents() {
2705 if (!AccessibilityManager.getInstance(mView.getContext()).isEnabled()) {
2706 return;
2707 }
2708 mView.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
2709 View focusedView = mView.findFocus();
2710 if (focusedView != null && focusedView != mView) {
2711 focusedView.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
2712 }
2713 }
2714
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002715 public boolean showContextMenuForChild(View originalView) {
2716 return false;
2717 }
2718
Adam Powell6e346362010-07-23 10:18:23 -07002719 public ActionMode startActionModeForChild(View originalView, ActionMode.Callback callback) {
2720 return null;
2721 }
2722
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002723 public void createContextMenu(ContextMenu menu) {
2724 }
2725
2726 public void childDrawableStateChanged(View child) {
2727 }
2728
2729 protected Rect getWindowFrame() {
2730 return mWinFrame;
2731 }
2732
2733 void checkThread() {
2734 if (mThread != Thread.currentThread()) {
2735 throw new CalledFromWrongThreadException(
2736 "Only the original thread that created a view hierarchy can touch its views.");
2737 }
2738 }
2739
2740 public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
2741 // ViewRoot never intercepts touch event, so this can be a no-op
2742 }
2743
2744 public boolean requestChildRectangleOnScreen(View child, Rect rectangle,
2745 boolean immediate) {
2746 return scrollToRectOrFocus(rectangle, immediate);
2747 }
Romain Guy8506ab42009-06-11 17:35:47 -07002748
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07002749 class TakenSurfaceHolder extends BaseSurfaceHolder {
2750 @Override
2751 public boolean onAllowLockCanvas() {
2752 return mDrawingAllowed;
2753 }
2754
2755 @Override
2756 public void onRelayoutContainer() {
2757 // Not currently interesting -- from changing between fixed and layout size.
2758 }
2759
2760 public void setFormat(int format) {
2761 ((RootViewSurfaceTaker)mView).setSurfaceFormat(format);
2762 }
2763
2764 public void setType(int type) {
2765 ((RootViewSurfaceTaker)mView).setSurfaceType(type);
2766 }
2767
2768 @Override
2769 public void onUpdateSurface() {
2770 // We take care of format and type changes on our own.
2771 throw new IllegalStateException("Shouldn't be here");
2772 }
2773
2774 public boolean isCreating() {
2775 return mIsCreating;
2776 }
2777
2778 @Override
2779 public void setFixedSize(int width, int height) {
2780 throw new UnsupportedOperationException(
2781 "Currently only support sizing from layout");
2782 }
2783
2784 public void setKeepScreenOn(boolean screenOn) {
2785 ((RootViewSurfaceTaker)mView).setSurfaceKeepScreenOn(screenOn);
2786 }
2787 }
2788
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002789 static class InputMethodCallback extends IInputMethodCallback.Stub {
2790 private WeakReference<ViewRoot> mViewRoot;
2791
2792 public InputMethodCallback(ViewRoot viewRoot) {
2793 mViewRoot = new WeakReference<ViewRoot>(viewRoot);
2794 }
Romain Guy8506ab42009-06-11 17:35:47 -07002795
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002796 public void finishedEvent(int seq, boolean handled) {
2797 final ViewRoot viewRoot = mViewRoot.get();
2798 if (viewRoot != null) {
2799 viewRoot.dispatchFinishedEvent(seq, handled);
2800 }
2801 }
2802
2803 public void sessionCreated(IInputMethodSession session) throws RemoteException {
2804 // Stub -- not for use in the client.
2805 }
2806 }
Romain Guy8506ab42009-06-11 17:35:47 -07002807
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002808 static class W extends IWindow.Stub {
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002809 private final WeakReference<ViewRoot> mViewRoot;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002810
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002811 public W(ViewRoot viewRoot, Context context) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002812 mViewRoot = new WeakReference<ViewRoot>(viewRoot);
2813 }
2814
2815 public void resized(int w, int h, Rect coveredInsets,
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002816 Rect visibleInsets, boolean reportDraw, Configuration newConfig) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002817 final ViewRoot viewRoot = mViewRoot.get();
2818 if (viewRoot != null) {
2819 viewRoot.dispatchResized(w, h, coveredInsets,
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002820 visibleInsets, reportDraw, newConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002821 }
2822 }
2823
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002824 public void dispatchAppVisibility(boolean visible) {
2825 final ViewRoot viewRoot = mViewRoot.get();
2826 if (viewRoot != null) {
2827 viewRoot.dispatchAppVisibility(visible);
2828 }
2829 }
2830
2831 public void dispatchGetNewSurface() {
2832 final ViewRoot viewRoot = mViewRoot.get();
2833 if (viewRoot != null) {
2834 viewRoot.dispatchGetNewSurface();
2835 }
2836 }
2837
2838 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
2839 final ViewRoot viewRoot = mViewRoot.get();
2840 if (viewRoot != null) {
2841 viewRoot.windowFocusChanged(hasFocus, inTouchMode);
2842 }
2843 }
2844
2845 private static int checkCallingPermission(String permission) {
2846 if (!Process.supportsProcesses()) {
2847 return PackageManager.PERMISSION_GRANTED;
2848 }
2849
2850 try {
2851 return ActivityManagerNative.getDefault().checkPermission(
2852 permission, Binder.getCallingPid(), Binder.getCallingUid());
2853 } catch (RemoteException e) {
2854 return PackageManager.PERMISSION_DENIED;
2855 }
2856 }
2857
2858 public void executeCommand(String command, String parameters, ParcelFileDescriptor out) {
2859 final ViewRoot viewRoot = mViewRoot.get();
2860 if (viewRoot != null) {
2861 final View view = viewRoot.mView;
2862 if (view != null) {
2863 if (checkCallingPermission(Manifest.permission.DUMP) !=
2864 PackageManager.PERMISSION_GRANTED) {
2865 throw new SecurityException("Insufficient permissions to invoke"
2866 + " executeCommand() from pid=" + Binder.getCallingPid()
2867 + ", uid=" + Binder.getCallingUid());
2868 }
2869
2870 OutputStream clientStream = null;
2871 try {
2872 clientStream = new ParcelFileDescriptor.AutoCloseOutputStream(out);
2873 ViewDebug.dispatchCommand(view, command, parameters, clientStream);
2874 } catch (IOException e) {
2875 e.printStackTrace();
2876 } finally {
2877 if (clientStream != null) {
2878 try {
2879 clientStream.close();
2880 } catch (IOException e) {
2881 e.printStackTrace();
2882 }
2883 }
2884 }
2885 }
2886 }
2887 }
Dianne Hackborn72c82ab2009-08-11 21:13:54 -07002888
Dianne Hackbornffa42482009-09-23 22:20:11 -07002889 public void closeSystemDialogs(String reason) {
2890 final ViewRoot viewRoot = mViewRoot.get();
2891 if (viewRoot != null) {
2892 viewRoot.dispatchCloseSystemDialogs(reason);
2893 }
2894 }
2895
Marco Nelissenbf6956b2009-11-09 15:21:13 -08002896 public void dispatchWallpaperOffsets(float x, float y, float xStep, float yStep,
2897 boolean sync) {
Dianne Hackborn19382ac2009-09-11 21:13:37 -07002898 if (sync) {
2899 try {
2900 sWindowSession.wallpaperOffsetsComplete(asBinder());
2901 } catch (RemoteException e) {
2902 }
2903 }
Dianne Hackborn72c82ab2009-08-11 21:13:54 -07002904 }
Dianne Hackborn75804932009-10-20 20:15:20 -07002905
2906 public void dispatchWallpaperCommand(String action, int x, int y,
2907 int z, Bundle extras, boolean sync) {
2908 if (sync) {
2909 try {
2910 sWindowSession.wallpaperCommandComplete(asBinder(), null);
2911 } catch (RemoteException e) {
2912 }
2913 }
2914 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002915 }
2916
2917 /**
2918 * Maintains state information for a single trackball axis, generating
2919 * discrete (DPAD) movements based on raw trackball motion.
2920 */
2921 static final class TrackballAxis {
2922 /**
2923 * The maximum amount of acceleration we will apply.
2924 */
2925 static final float MAX_ACCELERATION = 20;
Romain Guy8506ab42009-06-11 17:35:47 -07002926
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002927 /**
2928 * The maximum amount of time (in milliseconds) between events in order
2929 * for us to consider the user to be doing fast trackball movements,
2930 * and thus apply an acceleration.
2931 */
2932 static final long FAST_MOVE_TIME = 150;
Romain Guy8506ab42009-06-11 17:35:47 -07002933
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002934 /**
2935 * Scaling factor to the time (in milliseconds) between events to how
2936 * much to multiple/divide the current acceleration. When movement
2937 * is < FAST_MOVE_TIME this multiplies the acceleration; when >
2938 * FAST_MOVE_TIME it divides it.
2939 */
2940 static final float ACCEL_MOVE_SCALING_FACTOR = (1.0f/40);
Romain Guy8506ab42009-06-11 17:35:47 -07002941
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002942 float position;
2943 float absPosition;
2944 float acceleration = 1;
2945 long lastMoveTime = 0;
2946 int step;
2947 int dir;
2948 int nonAccelMovement;
2949
2950 void reset(int _step) {
2951 position = 0;
2952 acceleration = 1;
2953 lastMoveTime = 0;
2954 step = _step;
2955 dir = 0;
2956 }
2957
2958 /**
2959 * Add trackball movement into the state. If the direction of movement
2960 * has been reversed, the state is reset before adding the
2961 * movement (so that you don't have to compensate for any previously
2962 * collected movement before see the result of the movement in the
2963 * new direction).
2964 *
2965 * @return Returns the absolute value of the amount of movement
2966 * collected so far.
2967 */
2968 float collect(float off, long time, String axis) {
2969 long normTime;
2970 if (off > 0) {
2971 normTime = (long)(off * FAST_MOVE_TIME);
2972 if (dir < 0) {
2973 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to positive!");
2974 position = 0;
2975 step = 0;
2976 acceleration = 1;
2977 lastMoveTime = 0;
2978 }
2979 dir = 1;
2980 } else if (off < 0) {
2981 normTime = (long)((-off) * FAST_MOVE_TIME);
2982 if (dir > 0) {
2983 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to negative!");
2984 position = 0;
2985 step = 0;
2986 acceleration = 1;
2987 lastMoveTime = 0;
2988 }
2989 dir = -1;
2990 } else {
2991 normTime = 0;
2992 }
Romain Guy8506ab42009-06-11 17:35:47 -07002993
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002994 // The number of milliseconds between each movement that is
2995 // considered "normal" and will not result in any acceleration
2996 // or deceleration, scaled by the offset we have here.
2997 if (normTime > 0) {
2998 long delta = time - lastMoveTime;
2999 lastMoveTime = time;
3000 float acc = acceleration;
3001 if (delta < normTime) {
3002 // The user is scrolling rapidly, so increase acceleration.
3003 float scale = (normTime-delta) * ACCEL_MOVE_SCALING_FACTOR;
3004 if (scale > 1) acc *= scale;
3005 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " accelerate: off="
3006 + off + " normTime=" + normTime + " delta=" + delta
3007 + " scale=" + scale + " acc=" + acc);
3008 acceleration = acc < MAX_ACCELERATION ? acc : MAX_ACCELERATION;
3009 } else {
3010 // The user is scrolling slowly, so decrease acceleration.
3011 float scale = (delta-normTime) * ACCEL_MOVE_SCALING_FACTOR;
3012 if (scale > 1) acc /= scale;
3013 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " deccelerate: off="
3014 + off + " normTime=" + normTime + " delta=" + delta
3015 + " scale=" + scale + " acc=" + acc);
3016 acceleration = acc > 1 ? acc : 1;
3017 }
3018 }
3019 position += off;
3020 return (absPosition = Math.abs(position));
3021 }
3022
3023 /**
3024 * Generate the number of discrete movement events appropriate for
3025 * the currently collected trackball movement.
3026 *
3027 * @param precision The minimum movement required to generate the
3028 * first discrete movement.
3029 *
3030 * @return Returns the number of discrete movements, either positive
3031 * or negative, or 0 if there is not enough trackball movement yet
3032 * for a discrete movement.
3033 */
3034 int generate(float precision) {
3035 int movement = 0;
3036 nonAccelMovement = 0;
3037 do {
3038 final int dir = position >= 0 ? 1 : -1;
3039 switch (step) {
3040 // If we are going to execute the first step, then we want
3041 // to do this as soon as possible instead of waiting for
3042 // a full movement, in order to make things look responsive.
3043 case 0:
3044 if (absPosition < precision) {
3045 return movement;
3046 }
3047 movement += dir;
3048 nonAccelMovement += dir;
3049 step = 1;
3050 break;
3051 // If we have generated the first movement, then we need
3052 // to wait for the second complete trackball motion before
3053 // generating the second discrete movement.
3054 case 1:
3055 if (absPosition < 2) {
3056 return movement;
3057 }
3058 movement += dir;
3059 nonAccelMovement += dir;
3060 position += dir > 0 ? -2 : 2;
3061 absPosition = Math.abs(position);
3062 step = 2;
3063 break;
3064 // After the first two, we generate discrete movements
3065 // consistently with the trackball, applying an acceleration
3066 // if the trackball is moving quickly. This is a simple
3067 // acceleration on top of what we already compute based
3068 // on how quickly the wheel is being turned, to apply
3069 // a longer increasing acceleration to continuous movement
3070 // in one direction.
3071 default:
3072 if (absPosition < 1) {
3073 return movement;
3074 }
3075 movement += dir;
3076 position += dir >= 0 ? -1 : 1;
3077 absPosition = Math.abs(position);
3078 float acc = acceleration;
3079 acc *= 1.1f;
3080 acceleration = acc < MAX_ACCELERATION ? acc : acceleration;
3081 break;
3082 }
3083 } while (true);
3084 }
3085 }
3086
3087 public static final class CalledFromWrongThreadException extends AndroidRuntimeException {
3088 public CalledFromWrongThreadException(String msg) {
3089 super(msg);
3090 }
3091 }
3092
3093 private SurfaceHolder mHolder = new SurfaceHolder() {
3094 // we only need a SurfaceHolder for opengl. it would be nice
3095 // to implement everything else though, especially the callback
3096 // support (opengl doesn't make use of it right now, but eventually
3097 // will).
3098 public Surface getSurface() {
3099 return mSurface;
3100 }
3101
3102 public boolean isCreating() {
3103 return false;
3104 }
3105
3106 public void addCallback(Callback callback) {
3107 }
3108
3109 public void removeCallback(Callback callback) {
3110 }
3111
3112 public void setFixedSize(int width, int height) {
3113 }
3114
3115 public void setSizeFromLayout() {
3116 }
3117
3118 public void setFormat(int format) {
3119 }
3120
3121 public void setType(int type) {
3122 }
3123
3124 public void setKeepScreenOn(boolean screenOn) {
3125 }
3126
3127 public Canvas lockCanvas() {
3128 return null;
3129 }
3130
3131 public Canvas lockCanvas(Rect dirty) {
3132 return null;
3133 }
3134
3135 public void unlockCanvasAndPost(Canvas canvas) {
3136 }
3137 public Rect getSurfaceFrame() {
3138 return null;
3139 }
3140 };
3141
3142 static RunQueue getRunQueue() {
3143 RunQueue rq = sRunQueues.get();
3144 if (rq != null) {
3145 return rq;
3146 }
3147 rq = new RunQueue();
3148 sRunQueues.set(rq);
3149 return rq;
3150 }
Romain Guy8506ab42009-06-11 17:35:47 -07003151
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003152 /**
3153 * @hide
3154 */
3155 static final class RunQueue {
3156 private final ArrayList<HandlerAction> mActions = new ArrayList<HandlerAction>();
3157
3158 void post(Runnable action) {
3159 postDelayed(action, 0);
3160 }
3161
3162 void postDelayed(Runnable action, long delayMillis) {
3163 HandlerAction handlerAction = new HandlerAction();
3164 handlerAction.action = action;
3165 handlerAction.delay = delayMillis;
3166
3167 synchronized (mActions) {
3168 mActions.add(handlerAction);
3169 }
3170 }
3171
3172 void removeCallbacks(Runnable action) {
3173 final HandlerAction handlerAction = new HandlerAction();
3174 handlerAction.action = action;
3175
3176 synchronized (mActions) {
3177 final ArrayList<HandlerAction> actions = mActions;
3178
3179 while (actions.remove(handlerAction)) {
3180 // Keep going
3181 }
3182 }
3183 }
3184
3185 void executeActions(Handler handler) {
3186 synchronized (mActions) {
3187 final ArrayList<HandlerAction> actions = mActions;
3188 final int count = actions.size();
3189
3190 for (int i = 0; i < count; i++) {
3191 final HandlerAction handlerAction = actions.get(i);
3192 handler.postDelayed(handlerAction.action, handlerAction.delay);
3193 }
3194
Romain Guy15df6702009-08-17 20:17:30 -07003195 actions.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003196 }
3197 }
3198
3199 private static class HandlerAction {
3200 Runnable action;
3201 long delay;
3202
3203 @Override
3204 public boolean equals(Object o) {
3205 if (this == o) return true;
3206 if (o == null || getClass() != o.getClass()) return false;
3207
3208 HandlerAction that = (HandlerAction) o;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003209 return !(action != null ? !action.equals(that.action) : that.action != null);
3210
3211 }
3212
3213 @Override
3214 public int hashCode() {
3215 int result = action != null ? action.hashCode() : 0;
3216 result = 31 * result + (int) (delay ^ (delay >>> 32));
3217 return result;
3218 }
3219 }
3220 }
3221
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003222 private static native void nativeShowFPS(Canvas canvas, int durationMillis);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003223}