blob: 15c69105e32ff37005773dce89f058cff6c8ef22 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.view;
18
Romain Guy812ccbe2010-06-01 14:07:24 -070019import android.content.pm.ApplicationInfo;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -070020import com.android.internal.view.BaseSurfaceHolder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080021import com.android.internal.view.IInputMethodCallback;
22import com.android.internal.view.IInputMethodSession;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -070023import com.android.internal.view.RootViewSurfaceTaker;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080024
25import android.graphics.Canvas;
26import android.graphics.PixelFormat;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080027import android.graphics.PorterDuff;
28import android.graphics.Rect;
29import android.graphics.Region;
30import android.os.*;
31import android.os.Process;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080032import android.util.AndroidRuntimeException;
33import android.util.Config;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -070034import android.util.DisplayMetrics;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080035import android.util.Log;
36import android.util.EventLog;
37import android.util.SparseArray;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080038import android.view.View.MeasureSpec;
svetoslavganov75986cf2009-05-14 22:28:01 -070039import android.view.accessibility.AccessibilityEvent;
40import android.view.accessibility.AccessibilityManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080041import android.view.inputmethod.InputConnection;
42import android.view.inputmethod.InputMethodManager;
43import android.widget.Scroller;
44import android.content.pm.PackageManager;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -070045import android.content.res.CompatibilityInfo;
Dianne Hackborne36d6e22010-02-17 19:46:25 -080046import android.content.res.Configuration;
Mitsuru Oshima38ed7d772009-07-21 14:39:34 -070047import android.content.res.Resources;
Dianne Hackborne36d6e22010-02-17 19:46:25 -080048import android.content.ComponentCallbacks;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080049import android.content.Context;
50import android.app.ActivityManagerNative;
51import android.Manifest;
52import android.media.AudioManager;
53
54import java.lang.ref.WeakReference;
55import java.io.IOException;
56import java.io.OutputStream;
57import java.util.ArrayList;
58
59import javax.microedition.khronos.egl.*;
60import javax.microedition.khronos.opengles.*;
61import static javax.microedition.khronos.opengles.GL10.*;
62
63/**
64 * The top of a view hierarchy, implementing the needed protocol between View
65 * and the WindowManager. This is for the most part an internal implementation
66 * detail of {@link WindowManagerImpl}.
67 *
68 * {@hide}
69 */
Romain Guy812ccbe2010-06-01 14:07:24 -070070@SuppressWarnings({"EmptyCatchBlock", "PointlessBooleanExpression"})
71public final class ViewRoot extends Handler implements ViewParent, View.AttachInfo.Callbacks {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080072 private static final String TAG = "ViewRoot";
73 private static final boolean DBG = false;
Mike Reedfd716532009-10-12 14:42:56 -040074 private static final boolean SHOW_FPS = false;
Romain Guy812ccbe2010-06-01 14:07:24 -070075 private static final boolean LOCAL_LOGV = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080076 /** @noinspection PointlessBooleanExpression*/
77 private static final boolean DEBUG_DRAW = false || LOCAL_LOGV;
78 private static final boolean DEBUG_LAYOUT = false || LOCAL_LOGV;
Christopher Tatefa9e7c02010-05-06 12:07:10 -070079 private static final boolean DEBUG_INPUT = true || LOCAL_LOGV;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080080 private static final boolean DEBUG_INPUT_RESIZE = false || LOCAL_LOGV;
81 private static final boolean DEBUG_ORIENTATION = false || LOCAL_LOGV;
82 private static final boolean DEBUG_TRACKBALL = false || LOCAL_LOGV;
83 private static final boolean DEBUG_IMF = false || LOCAL_LOGV;
Dianne Hackborn694f79b2010-03-17 19:44:59 -070084 private static final boolean DEBUG_CONFIGURATION = false || LOCAL_LOGV;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080085 private static final boolean WATCH_POINTER = false;
86
Michael Chan53071d62009-05-13 17:29:48 -070087 private static final boolean MEASURE_LATENCY = false;
88 private static LatencyTimer lt;
89
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080090 /**
91 * Maximum time we allow the user to roll the trackball enough to generate
92 * a key event, before resetting the counters.
93 */
94 static final int MAX_TRACKBALL_DELAY = 250;
95
96 static long sInstanceCount = 0;
97
98 static IWindowSession sWindowSession;
99
100 static final Object mStaticInit = new Object();
101 static boolean mInitialized = false;
102
103 static final ThreadLocal<RunQueue> sRunQueues = new ThreadLocal<RunQueue>();
104
Dianne Hackborn2a9094d2010-02-03 19:20:09 -0800105 static final ArrayList<Runnable> sFirstDrawHandlers = new ArrayList<Runnable>();
106 static boolean sFirstDrawComplete = false;
107
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800108 static final ArrayList<ComponentCallbacks> sConfigCallbacks
109 = new ArrayList<ComponentCallbacks>();
110
Romain Guy8506ab42009-06-11 17:35:47 -0700111 private static int sDrawTime;
Romain Guy13922e02009-05-12 17:56:14 -0700112
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800113 long mLastTrackballTime = 0;
114 final TrackballAxis mTrackballAxisX = new TrackballAxis();
115 final TrackballAxis mTrackballAxisY = new TrackballAxis();
116
117 final int[] mTmpLocation = new int[2];
Romain Guy8506ab42009-06-11 17:35:47 -0700118
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800119 final InputMethodCallback mInputMethodCallback;
120 final SparseArray<Object> mPendingEvents = new SparseArray<Object>();
121 int mPendingEventSeq = 0;
Romain Guy8506ab42009-06-11 17:35:47 -0700122
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800123 final Thread mThread;
124
125 final WindowLeaked mLocation;
126
127 final WindowManager.LayoutParams mWindowAttributes = new WindowManager.LayoutParams();
128
129 final W mWindow;
130
131 View mView;
132 View mFocusedView;
133 View mRealFocusedView; // this is not set to null in touch mode
134 int mViewVisibility;
135 boolean mAppVisible = true;
136
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700137 SurfaceHolder.Callback mSurfaceHolderCallback;
138 BaseSurfaceHolder mSurfaceHolder;
139 boolean mIsCreating;
140 boolean mDrawingAllowed;
141
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800142 final Region mTransparentRegion;
143 final Region mPreviousTransparentRegion;
144
145 int mWidth;
146 int mHeight;
147 Rect mDirty; // will be a graphics.Region soon
Romain Guybb93d552009-03-24 21:04:15 -0700148 boolean mIsAnimating;
Romain Guy8506ab42009-06-11 17:35:47 -0700149
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700150 CompatibilityInfo.Translator mTranslator;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800151
152 final View.AttachInfo mAttachInfo;
153
154 final Rect mTempRect; // used in the transaction to not thrash the heap.
155 final Rect mVisRect; // used to retrieve visible rect of focused view.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800156
157 boolean mTraversalScheduled;
158 boolean mWillDrawSoon;
159 boolean mLayoutRequested;
160 boolean mFirst;
161 boolean mReportNextDraw;
162 boolean mFullRedrawNeeded;
163 boolean mNewSurfaceNeeded;
164 boolean mHasHadWindowFocus;
165 boolean mLastWasImTarget;
166
167 boolean mWindowAttributesChanged = false;
168
169 // These can be accessed by any thread, must be protected with a lock.
Mathias Agopian5583dc62009-07-09 16:28:11 -0700170 // Surface can never be reassigned or cleared (use Surface.clear()).
171 private final Surface mSurface = new Surface();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800172
173 boolean mAdded;
174 boolean mAddedTouchMode;
175
176 /*package*/ int mAddNesting;
177
178 // These are accessed by multiple threads.
179 final Rect mWinFrame; // frame given by window manager.
180
181 final Rect mPendingVisibleInsets = new Rect();
182 final Rect mPendingContentInsets = new Rect();
183 final ViewTreeObserver.InternalInsetsInfo mLastGivenInsets
184 = new ViewTreeObserver.InternalInsetsInfo();
185
Dianne Hackborn694f79b2010-03-17 19:44:59 -0700186 final Configuration mLastConfiguration = new Configuration();
187 final Configuration mPendingConfiguration = new Configuration();
188
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800189 class ResizedInfo {
190 Rect coveredInsets;
191 Rect visibleInsets;
192 Configuration newConfig;
193 }
194
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800195 boolean mScrollMayChange;
196 int mSoftInputMode;
197 View mLastScrolledFocus;
198 int mScrollY;
199 int mCurScrollY;
200 Scroller mScroller;
Romain Guy8506ab42009-06-11 17:35:47 -0700201
Romain Guy812ccbe2010-06-01 14:07:24 -0700202 HardwareRenderer mHwRenderer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800203
Romain Guy8506ab42009-06-11 17:35:47 -0700204 final ViewConfiguration mViewConfiguration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800205
206 /**
207 * see {@link #playSoundEffect(int)}
208 */
209 AudioManager mAudioManager;
210
Dianne Hackborn11ea3342009-07-22 21:48:55 -0700211 private final int mDensity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800212
Dianne Hackborn4c62fc02009-08-08 20:40:27 -0700213 public static IWindowSession getWindowSession(Looper mainLooper) {
214 synchronized (mStaticInit) {
215 if (!mInitialized) {
216 try {
217 InputMethodManager imm = InputMethodManager.getInstance(mainLooper);
218 sWindowSession = IWindowManager.Stub.asInterface(
219 ServiceManager.getService("window"))
220 .openSession(imm.getClient(), imm.getInputContext());
221 mInitialized = true;
222 } catch (RemoteException e) {
223 }
224 }
225 return sWindowSession;
226 }
227 }
228
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800229 public ViewRoot(Context context) {
230 super();
231
Romain Guy812ccbe2010-06-01 14:07:24 -0700232 if (MEASURE_LATENCY) {
233 if (lt == null) {
234 lt = new LatencyTimer(100, 1000);
235 }
Michael Chan53071d62009-05-13 17:29:48 -0700236 }
237
Carl Shapiro82fe5642010-02-24 00:14:23 -0800238 // For debug only
239 //++sInstanceCount;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800240
241 // Initialize the statics when this class is first instantiated. This is
242 // done here instead of in the static block because Zygote does not
243 // allow the spawning of threads.
Dianne Hackborn4c62fc02009-08-08 20:40:27 -0700244 getWindowSession(context.getMainLooper());
245
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800246 mThread = Thread.currentThread();
247 mLocation = new WindowLeaked(null);
248 mLocation.fillInStackTrace();
249 mWidth = -1;
250 mHeight = -1;
251 mDirty = new Rect();
252 mTempRect = new Rect();
253 mVisRect = new Rect();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800254 mWinFrame = new Rect();
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -0700255 mWindow = new W(this, context);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800256 mInputMethodCallback = new InputMethodCallback(this);
257 mViewVisibility = View.GONE;
258 mTransparentRegion = new Region();
259 mPreviousTransparentRegion = new Region();
260 mFirst = true; // true for the first time the view is added
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800261 mAdded = false;
262 mAttachInfo = new View.AttachInfo(sWindowSession, mWindow, this, this);
263 mViewConfiguration = ViewConfiguration.get(context);
Dianne Hackborn11ea3342009-07-22 21:48:55 -0700264 mDensity = context.getResources().getDisplayMetrics().densityDpi;
Romain Guy812ccbe2010-06-01 14:07:24 -0700265
266 // Try to enable hardware acceleration if requested
267 if ((context.getApplicationInfo().flags &
268 ApplicationInfo.FLAG_HARDWARE_ACCELERATED) != 0) {
269 mHwRenderer = new HardwareRenderer();
270 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800271 }
272
Carl Shapiro82fe5642010-02-24 00:14:23 -0800273 // For debug only
274 /*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800275 @Override
276 protected void finalize() throws Throwable {
277 super.finalize();
278 --sInstanceCount;
279 }
Carl Shapiro82fe5642010-02-24 00:14:23 -0800280 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800281
282 public static long getInstanceCount() {
283 return sInstanceCount;
284 }
285
Dianne Hackborn2a9094d2010-02-03 19:20:09 -0800286 public static void addFirstDrawHandler(Runnable callback) {
287 synchronized (sFirstDrawHandlers) {
288 if (!sFirstDrawComplete) {
289 sFirstDrawHandlers.add(callback);
290 }
291 }
292 }
293
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800294 public static void addConfigCallback(ComponentCallbacks callback) {
295 synchronized (sConfigCallbacks) {
296 sConfigCallbacks.add(callback);
297 }
298 }
299
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800300 // FIXME for perf testing only
301 private boolean mProfile = false;
302
303 /**
304 * Call this to profile the next traversal call.
305 * FIXME for perf testing only. Remove eventually
306 */
307 public void profile() {
308 mProfile = true;
309 }
310
311 /**
312 * Indicates whether we are in touch mode. Calling this method triggers an IPC
313 * call and should be avoided whenever possible.
314 *
315 * @return True, if the device is in touch mode, false otherwise.
316 *
317 * @hide
318 */
319 static boolean isInTouchMode() {
320 if (mInitialized) {
321 try {
322 return sWindowSession.getInTouchMode();
323 } catch (RemoteException e) {
324 }
325 }
326 return false;
327 }
328
Christopher Tatefa9e7c02010-05-06 12:07:10 -0700329 // fd [0] is the receiver, [1] is the sender
330 private native int[] makeInputChannel();
331
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800332 /**
333 * We have one child
334 */
335 public void setView(View view, WindowManager.LayoutParams attrs,
336 View panelParentView) {
337 synchronized (this) {
338 if (mView == null) {
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700339 mView = view;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700340 mWindowAttributes.copyFrom(attrs);
Mitsuru Oshima1ecf5d22009-07-06 17:20:38 -0700341 attrs = mWindowAttributes;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700342 if (view instanceof RootViewSurfaceTaker) {
343 mSurfaceHolderCallback =
344 ((RootViewSurfaceTaker)view).willYouTakeTheSurface();
345 if (mSurfaceHolderCallback != null) {
346 mSurfaceHolder = new TakenSurfaceHolder();
347 }
348 }
Mitsuru Oshima38ed7d772009-07-21 14:39:34 -0700349 Resources resources = mView.getContext().getResources();
350 CompatibilityInfo compatibilityInfo = resources.getCompatibilityInfo();
Mitsuru Oshima589cebe2009-07-22 20:38:58 -0700351 mTranslator = compatibilityInfo.getTranslator();
Mitsuru Oshima38ed7d772009-07-21 14:39:34 -0700352
353 if (mTranslator != null || !compatibilityInfo.supportsScreen()) {
Mitsuru Oshima240f8a72009-07-22 20:39:14 -0700354 mSurface.setCompatibleDisplayMetrics(resources.getDisplayMetrics(),
355 mTranslator);
Mitsuru Oshima38ed7d772009-07-21 14:39:34 -0700356 }
357
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -0700358 boolean restore = false;
Romain Guy35b38ce2009-10-07 13:38:55 -0700359 if (mTranslator != null) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -0700360 restore = true;
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700361 attrs.backup();
362 mTranslator.translateWindowLayout(attrs);
Mitsuru Oshima3d914922009-05-13 22:29:15 -0700363 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700364 if (DEBUG_LAYOUT) Log.d(TAG, "WindowLayout in setView:" + attrs);
365
Mitsuru Oshima1ecf5d22009-07-06 17:20:38 -0700366 if (!compatibilityInfo.supportsScreen()) {
367 attrs.flags |= WindowManager.LayoutParams.FLAG_COMPATIBLE_WINDOW;
368 }
369
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800370 mSoftInputMode = attrs.softInputMode;
371 mWindowAttributesChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800372 mAttachInfo.mRootView = view;
Romain Guy35b38ce2009-10-07 13:38:55 -0700373 mAttachInfo.mScalingRequired = mTranslator != null;
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700374 mAttachInfo.mApplicationScale =
375 mTranslator == null ? 1.0f : mTranslator.applicationScale;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800376 if (panelParentView != null) {
377 mAttachInfo.mPanelParentWindowToken
378 = panelParentView.getApplicationWindowToken();
379 }
380 mAdded = true;
381 int res; /* = WindowManagerImpl.ADD_OKAY; */
Romain Guy8506ab42009-06-11 17:35:47 -0700382
Christopher Tatefa9e7c02010-05-06 12:07:10 -0700383 // Set up the input event channel
384 if (false) {
Romain Guy812ccbe2010-06-01 14:07:24 -0700385 int[] fds = makeInputChannel();
386 if (DEBUG_INPUT) {
387 Log.v(TAG, "makeInputChannel() returned " + java.util.Arrays.toString(fds));
388 }
Christopher Tatefa9e7c02010-05-06 12:07:10 -0700389 }
390
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800391 // Schedule the first layout -before- adding to the window
392 // manager, to make sure we do the relayout before receiving
393 // any other events from the system.
394 requestLayout();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800395 try {
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700396 res = sWindowSession.add(mWindow, mWindowAttributes,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800397 getHostVisibility(), mAttachInfo.mContentInsets);
398 } catch (RemoteException e) {
399 mAdded = false;
400 mView = null;
401 mAttachInfo.mRootView = null;
402 unscheduleTraversals();
403 throw new RuntimeException("Adding window failed", e);
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700404 } finally {
405 if (restore) {
406 attrs.restore();
407 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800408 }
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -0700409
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700410 if (mTranslator != null) {
411 mTranslator.translateRectInScreenToAppWindow(mAttachInfo.mContentInsets);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700412 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800413 mPendingContentInsets.set(mAttachInfo.mContentInsets);
414 mPendingVisibleInsets.set(0, 0, 0, 0);
415 if (Config.LOGV) Log.v("ViewRoot", "Added window " + mWindow);
416 if (res < WindowManagerImpl.ADD_OKAY) {
417 mView = null;
418 mAttachInfo.mRootView = null;
419 mAdded = false;
420 unscheduleTraversals();
421 switch (res) {
422 case WindowManagerImpl.ADD_BAD_APP_TOKEN:
423 case WindowManagerImpl.ADD_BAD_SUBWINDOW_TOKEN:
424 throw new WindowManagerImpl.BadTokenException(
425 "Unable to add window -- token " + attrs.token
426 + " is not valid; is your activity running?");
427 case WindowManagerImpl.ADD_NOT_APP_TOKEN:
428 throw new WindowManagerImpl.BadTokenException(
429 "Unable to add window -- token " + attrs.token
430 + " is not for an application");
431 case WindowManagerImpl.ADD_APP_EXITING:
432 throw new WindowManagerImpl.BadTokenException(
433 "Unable to add window -- app for token " + attrs.token
434 + " is exiting");
435 case WindowManagerImpl.ADD_DUPLICATE_ADD:
436 throw new WindowManagerImpl.BadTokenException(
437 "Unable to add window -- window " + mWindow
438 + " has already been added");
439 case WindowManagerImpl.ADD_STARTING_NOT_NEEDED:
440 // Silently ignore -- we would have just removed it
441 // right away, anyway.
442 return;
443 case WindowManagerImpl.ADD_MULTIPLE_SINGLETON:
444 throw new WindowManagerImpl.BadTokenException(
445 "Unable to add window " + mWindow +
446 " -- another window of this type already exists");
447 case WindowManagerImpl.ADD_PERMISSION_DENIED:
448 throw new WindowManagerImpl.BadTokenException(
449 "Unable to add window " + mWindow +
450 " -- permission denied for this window type");
451 }
452 throw new RuntimeException(
453 "Unable to add window -- unknown error code " + res);
454 }
455 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
462 public View getView() {
463 return mView;
464 }
465
466 final WindowLeaked getLocation() {
467 return mLocation;
468 }
469
470 void setLayoutParams(WindowManager.LayoutParams attrs, boolean newView) {
471 synchronized (this) {
The Android Open Source Project10592532009-03-18 17:39:46 -0700472 int oldSoftInputMode = mWindowAttributes.softInputMode;
Mitsuru Oshima5a2b91d2009-07-16 16:30:02 -0700473 // preserve compatible window flag if exists.
474 int compatibleWindowFlag =
475 mWindowAttributes.flags & WindowManager.LayoutParams.FLAG_COMPATIBLE_WINDOW;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800476 mWindowAttributes.copyFrom(attrs);
Mitsuru Oshima5a2b91d2009-07-16 16:30:02 -0700477 mWindowAttributes.flags |= compatibleWindowFlag;
478
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800479 if (newView) {
480 mSoftInputMode = attrs.softInputMode;
481 requestLayout();
482 }
The Android Open Source Project10592532009-03-18 17:39:46 -0700483 // Don't lose the mode we last auto-computed.
484 if ((attrs.softInputMode&WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST)
485 == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED) {
486 mWindowAttributes.softInputMode = (mWindowAttributes.softInputMode
487 & ~WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST)
488 | (oldSoftInputMode
489 & WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST);
490 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800491 mWindowAttributesChanged = true;
492 scheduleTraversals();
493 }
494 }
495
496 void handleAppVisibility(boolean visible) {
497 if (mAppVisible != visible) {
498 mAppVisible = visible;
499 scheduleTraversals();
500 }
501 }
502
503 void handleGetNewSurface() {
504 mNewSurfaceNeeded = true;
505 mFullRedrawNeeded = true;
506 scheduleTraversals();
507 }
508
509 /**
510 * {@inheritDoc}
511 */
512 public void requestLayout() {
513 checkThread();
514 mLayoutRequested = true;
515 scheduleTraversals();
516 }
517
518 /**
519 * {@inheritDoc}
520 */
521 public boolean isLayoutRequested() {
522 return mLayoutRequested;
523 }
524
525 public void invalidateChild(View child, Rect dirty) {
526 checkThread();
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700527 if (DEBUG_DRAW) Log.v(TAG, "Invalidate child: " + dirty);
528 if (mCurScrollY != 0 || mTranslator != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800529 mTempRect.set(dirty);
Romain Guy1e095972009-07-07 11:22:45 -0700530 dirty = mTempRect;
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700531 if (mCurScrollY != 0) {
Romain Guy1e095972009-07-07 11:22:45 -0700532 dirty.offset(0, -mCurScrollY);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700533 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700534 if (mTranslator != null) {
Romain Guy1e095972009-07-07 11:22:45 -0700535 mTranslator.translateRectInAppWindowToScreen(dirty);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700536 }
Romain Guy1e095972009-07-07 11:22:45 -0700537 if (mAttachInfo.mScalingRequired) {
538 dirty.inset(-1, -1);
539 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800540 }
541 mDirty.union(dirty);
542 if (!mWillDrawSoon) {
543 scheduleTraversals();
544 }
545 }
546
547 public ViewParent getParent() {
548 return null;
549 }
550
551 public ViewParent invalidateChildInParent(final int[] location, final Rect dirty) {
552 invalidateChild(null, dirty);
553 return null;
554 }
555
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700556 public boolean getChildVisibleRect(View child, Rect r, android.graphics.Point offset) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800557 if (child != mView) {
558 throw new RuntimeException("child is not mine, honest!");
559 }
560 // Note: don't apply scroll offset, because we want to know its
561 // visibility in the virtual canvas being given to the view hierarchy.
562 return r.intersect(0, 0, mWidth, mHeight);
563 }
564
565 public void bringChildToFront(View child) {
566 }
567
568 public void scheduleTraversals() {
569 if (!mTraversalScheduled) {
570 mTraversalScheduled = true;
571 sendEmptyMessage(DO_TRAVERSAL);
572 }
573 }
574
575 public void unscheduleTraversals() {
576 if (mTraversalScheduled) {
577 mTraversalScheduled = false;
578 removeMessages(DO_TRAVERSAL);
579 }
580 }
581
582 int getHostVisibility() {
583 return mAppVisible ? mView.getVisibility() : View.GONE;
584 }
Romain Guy8506ab42009-06-11 17:35:47 -0700585
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800586 private void performTraversals() {
587 // cache mView since it is used so much below...
588 final View host = mView;
589
590 if (DBG) {
591 System.out.println("======================================");
592 System.out.println("performTraversals");
593 host.debug();
594 }
595
596 if (host == null || !mAdded)
597 return;
598
599 mTraversalScheduled = false;
600 mWillDrawSoon = true;
601 boolean windowResizesToFitContent = false;
602 boolean fullRedrawNeeded = mFullRedrawNeeded;
603 boolean newSurface = false;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700604 boolean surfaceChanged = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800605 WindowManager.LayoutParams lp = mWindowAttributes;
606
607 int desiredWindowWidth;
608 int desiredWindowHeight;
609 int childWidthMeasureSpec;
610 int childHeightMeasureSpec;
611
612 final View.AttachInfo attachInfo = mAttachInfo;
613
614 final int viewVisibility = getHostVisibility();
615 boolean viewVisibilityChanged = mViewVisibility != viewVisibility
616 || mNewSurfaceNeeded;
617
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700618 float appScale = mAttachInfo.mApplicationScale;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700619
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800620 WindowManager.LayoutParams params = null;
621 if (mWindowAttributesChanged) {
622 mWindowAttributesChanged = false;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700623 surfaceChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800624 params = lp;
625 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700626 Rect frame = mWinFrame;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800627 if (mFirst) {
628 fullRedrawNeeded = true;
629 mLayoutRequested = true;
630
Romain Guy8506ab42009-06-11 17:35:47 -0700631 DisplayMetrics packageMetrics =
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700632 mView.getContext().getResources().getDisplayMetrics();
633 desiredWindowWidth = packageMetrics.widthPixels;
634 desiredWindowHeight = packageMetrics.heightPixels;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800635
636 // For the very first time, tell the view hierarchy that it
637 // is attached to the window. Note that at this point the surface
638 // object is not initialized to its backing store, but soon it
639 // will be (assuming the window is visible).
640 attachInfo.mSurface = mSurface;
Romain Guy35b38ce2009-10-07 13:38:55 -0700641 attachInfo.mTranslucentWindow = lp.format != PixelFormat.OPAQUE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800642 attachInfo.mHasWindowFocus = false;
643 attachInfo.mWindowVisibility = viewVisibility;
644 attachInfo.mRecomputeGlobalAttributes = false;
645 attachInfo.mKeepScreenOn = false;
646 viewVisibilityChanged = false;
Dianne Hackborn694f79b2010-03-17 19:44:59 -0700647 mLastConfiguration.setTo(host.getResources().getConfiguration());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800648 host.dispatchAttachedToWindow(attachInfo, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800649 //Log.i(TAG, "Screen on initialized: " + attachInfo.mKeepScreenOn);
svetoslavganov75986cf2009-05-14 22:28:01 -0700650
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800651 } else {
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700652 desiredWindowWidth = frame.width();
653 desiredWindowHeight = frame.height();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800654 if (desiredWindowWidth != mWidth || desiredWindowHeight != mHeight) {
655 if (DEBUG_ORIENTATION) Log.v("ViewRoot",
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700656 "View " + host + " resized to: " + frame);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800657 fullRedrawNeeded = true;
658 mLayoutRequested = true;
659 windowResizesToFitContent = true;
660 }
661 }
662
663 if (viewVisibilityChanged) {
664 attachInfo.mWindowVisibility = viewVisibility;
665 host.dispatchWindowVisibilityChanged(viewVisibility);
666 if (viewVisibility != View.VISIBLE || mNewSurfaceNeeded) {
Romain Guy812ccbe2010-06-01 14:07:24 -0700667 if (mHwRenderer != null) {
668 mHwRenderer.destroyGL();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800669 }
670 }
671 if (viewVisibility == View.GONE) {
672 // After making a window gone, we will count it as being
673 // shown for the first time the next time it gets focus.
674 mHasHadWindowFocus = false;
675 }
676 }
677
678 boolean insetsChanged = false;
Romain Guy8506ab42009-06-11 17:35:47 -0700679
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800680 if (mLayoutRequested) {
Romain Guy15df6702009-08-17 20:17:30 -0700681 // Execute enqueued actions on every layout in case a view that was detached
682 // enqueued an action after being detached
683 getRunQueue().executeActions(attachInfo.mHandler);
684
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800685 if (mFirst) {
686 host.fitSystemWindows(mAttachInfo.mContentInsets);
687 // make sure touch mode code executes by setting cached value
688 // to opposite of the added touch mode.
689 mAttachInfo.mInTouchMode = !mAddedTouchMode;
Romain Guy2d4cff62010-04-09 15:39:00 -0700690 ensureTouchModeLocally(mAddedTouchMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800691 } else {
692 if (!mAttachInfo.mContentInsets.equals(mPendingContentInsets)) {
693 mAttachInfo.mContentInsets.set(mPendingContentInsets);
694 host.fitSystemWindows(mAttachInfo.mContentInsets);
695 insetsChanged = true;
696 if (DEBUG_LAYOUT) Log.v(TAG, "Content insets changing to: "
697 + mAttachInfo.mContentInsets);
698 }
699 if (!mAttachInfo.mVisibleInsets.equals(mPendingVisibleInsets)) {
700 mAttachInfo.mVisibleInsets.set(mPendingVisibleInsets);
701 if (DEBUG_LAYOUT) Log.v(TAG, "Visible insets changing to: "
702 + mAttachInfo.mVisibleInsets);
703 }
704 if (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT
705 || lp.height == ViewGroup.LayoutParams.WRAP_CONTENT) {
706 windowResizesToFitContent = true;
707
Romain Guy8506ab42009-06-11 17:35:47 -0700708 DisplayMetrics packageMetrics =
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700709 mView.getContext().getResources().getDisplayMetrics();
710 desiredWindowWidth = packageMetrics.widthPixels;
711 desiredWindowHeight = packageMetrics.heightPixels;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800712 }
713 }
714
715 childWidthMeasureSpec = getRootMeasureSpec(desiredWindowWidth, lp.width);
716 childHeightMeasureSpec = getRootMeasureSpec(desiredWindowHeight, lp.height);
717
718 // Ask host how big it wants to be
719 if (DEBUG_ORIENTATION || DEBUG_LAYOUT) Log.v("ViewRoot",
720 "Measuring " + host + " in display " + desiredWindowWidth
721 + "x" + desiredWindowHeight + "...");
722 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
723
724 if (DBG) {
725 System.out.println("======================================");
726 System.out.println("performTraversals -- after measure");
727 host.debug();
728 }
729 }
730
731 if (attachInfo.mRecomputeGlobalAttributes) {
732 //Log.i(TAG, "Computing screen on!");
733 attachInfo.mRecomputeGlobalAttributes = false;
734 boolean oldVal = attachInfo.mKeepScreenOn;
735 attachInfo.mKeepScreenOn = false;
736 host.dispatchCollectViewAttributes(0);
737 if (attachInfo.mKeepScreenOn != oldVal) {
738 params = lp;
739 //Log.i(TAG, "Keep screen on changed: " + attachInfo.mKeepScreenOn);
740 }
741 }
742
743 if (mFirst || attachInfo.mViewVisibilityChanged) {
744 attachInfo.mViewVisibilityChanged = false;
745 int resizeMode = mSoftInputMode &
746 WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST;
747 // If we are in auto resize mode, then we need to determine
748 // what mode to use now.
749 if (resizeMode == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED) {
750 final int N = attachInfo.mScrollContainers.size();
751 for (int i=0; i<N; i++) {
752 if (attachInfo.mScrollContainers.get(i).isShown()) {
753 resizeMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE;
754 }
755 }
756 if (resizeMode == 0) {
757 resizeMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN;
758 }
759 if ((lp.softInputMode &
760 WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) != resizeMode) {
761 lp.softInputMode = (lp.softInputMode &
762 ~WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) |
763 resizeMode;
764 params = lp;
765 }
766 }
767 }
Romain Guy8506ab42009-06-11 17:35:47 -0700768
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800769 if (params != null && (host.mPrivateFlags & View.REQUEST_TRANSPARENT_REGIONS) != 0) {
770 if (!PixelFormat.formatHasAlpha(params.format)) {
771 params.format = PixelFormat.TRANSLUCENT;
772 }
773 }
774
775 boolean windowShouldResize = mLayoutRequested && windowResizesToFitContent
Romain Guy2e4f4262010-04-06 11:07:52 -0700776 && ((mWidth != host.mMeasuredWidth || mHeight != host.mMeasuredHeight)
777 || (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT &&
778 frame.width() < desiredWindowWidth && frame.width() != mWidth)
779 || (lp.height == ViewGroup.LayoutParams.WRAP_CONTENT &&
780 frame.height() < desiredWindowHeight && frame.height() != mHeight));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800781
782 final boolean computesInternalInsets =
783 attachInfo.mTreeObserver.hasComputeInternalInsetsListeners();
Romain Guy812ccbe2010-06-01 14:07:24 -0700784
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800785 boolean insetsPending = false;
786 int relayoutResult = 0;
Romain Guy812ccbe2010-06-01 14:07:24 -0700787
788 if (mFirst || windowShouldResize || insetsChanged ||
789 viewVisibilityChanged || params != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800790
791 if (viewVisibility == View.VISIBLE) {
792 // If this window is giving internal insets to the window
793 // manager, and it is being added or changing its visibility,
794 // then we want to first give the window manager "fake"
795 // insets to cause it to effectively ignore the content of
796 // the window during layout. This avoids it briefly causing
797 // other windows to resize/move based on the raw frame of the
798 // window, waiting until we can finish laying out this window
799 // and get back to the window manager with the ultimately
800 // computed insets.
Romain Guy812ccbe2010-06-01 14:07:24 -0700801 insetsPending = computesInternalInsets && (mFirst || viewVisibilityChanged);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800802 }
803
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700804 if (mSurfaceHolder != null) {
805 mSurfaceHolder.mSurfaceLock.lock();
806 mDrawingAllowed = true;
807 lp.format = mSurfaceHolder.getRequestedFormat();
808 lp.type = mSurfaceHolder.getRequestedType();
809 }
Romain Guy812ccbe2010-06-01 14:07:24 -0700810
811 boolean hwIntialized = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800812 boolean contentInsetsChanged = false;
Romain Guy13922e02009-05-12 17:56:14 -0700813 boolean visibleInsetsChanged;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700814 boolean hadSurface = mSurface.isValid();
Romain Guy812ccbe2010-06-01 14:07:24 -0700815
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800816 try {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800817 int fl = 0;
818 if (params != null) {
819 fl = params.flags;
820 if (attachInfo.mKeepScreenOn) {
821 params.flags |= WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
822 }
823 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700824 if (DEBUG_LAYOUT) {
825 Log.i(TAG, "host=w:" + host.mMeasuredWidth + ", h:" +
826 host.mMeasuredHeight + ", params=" + params);
827 }
828 relayoutResult = relayoutWindow(params, viewVisibility, insetsPending);
829
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800830 if (params != null) {
831 params.flags = fl;
832 }
833
834 if (DEBUG_LAYOUT) Log.v(TAG, "relayout: frame=" + frame.toShortString()
835 + " content=" + mPendingContentInsets.toShortString()
836 + " visible=" + mPendingVisibleInsets.toShortString()
837 + " surface=" + mSurface);
Romain Guy8506ab42009-06-11 17:35:47 -0700838
Dianne Hackborn694f79b2010-03-17 19:44:59 -0700839 if (mPendingConfiguration.seq != 0) {
840 if (DEBUG_CONFIGURATION) Log.v(TAG, "Visible with new config: "
841 + mPendingConfiguration);
842 updateConfiguration(mPendingConfiguration, !mFirst);
843 mPendingConfiguration.seq = 0;
844 }
845
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800846 contentInsetsChanged = !mPendingContentInsets.equals(
847 mAttachInfo.mContentInsets);
848 visibleInsetsChanged = !mPendingVisibleInsets.equals(
849 mAttachInfo.mVisibleInsets);
850 if (contentInsetsChanged) {
851 mAttachInfo.mContentInsets.set(mPendingContentInsets);
852 host.fitSystemWindows(mAttachInfo.mContentInsets);
853 if (DEBUG_LAYOUT) Log.v(TAG, "Content insets changing to: "
854 + mAttachInfo.mContentInsets);
855 }
856 if (visibleInsetsChanged) {
857 mAttachInfo.mVisibleInsets.set(mPendingVisibleInsets);
858 if (DEBUG_LAYOUT) Log.v(TAG, "Visible insets changing to: "
859 + mAttachInfo.mVisibleInsets);
860 }
861
862 if (!hadSurface) {
863 if (mSurface.isValid()) {
864 // If we are creating a new surface, then we need to
865 // completely redraw it. Also, when we get to the
866 // point of drawing it we will hold off and schedule
867 // a new traversal instead. This is so we can tell the
868 // window manager about all of the windows being displayed
869 // before actually drawing them, so it can display then
870 // all at once.
871 newSurface = true;
872 fullRedrawNeeded = true;
Jack Palevich61a6e682009-10-09 17:37:50 -0700873 mPreviousTransparentRegion.setEmpty();
Romain Guy8506ab42009-06-11 17:35:47 -0700874
Romain Guy812ccbe2010-06-01 14:07:24 -0700875 if (mHwRenderer != null) {
876 hwIntialized = mHwRenderer.initialize();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800877 }
878 }
879 } else if (!mSurface.isValid()) {
880 // If the surface has been removed, then reset the scroll
881 // positions.
882 mLastScrolledFocus = null;
883 mScrollY = mCurScrollY = 0;
884 if (mScroller != null) {
885 mScroller.abortAnimation();
886 }
887 }
888 } catch (RemoteException e) {
889 }
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700890
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800891 if (DEBUG_ORIENTATION) Log.v(
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700892 "ViewRoot", "Relayout returned: frame=" + frame + ", surface=" + mSurface);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800893
894 attachInfo.mWindowLeft = frame.left;
895 attachInfo.mWindowTop = frame.top;
896
897 // !!FIXME!! This next section handles the case where we did not get the
898 // window size we asked for. We should avoid this by getting a maximum size from
899 // the window session beforehand.
900 mWidth = frame.width();
901 mHeight = frame.height();
902
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700903 if (mSurfaceHolder != null) {
904 // The app owns the surface; tell it about what is going on.
905 if (mSurface.isValid()) {
906 // XXX .copyFrom() doesn't work!
907 //mSurfaceHolder.mSurface.copyFrom(mSurface);
908 mSurfaceHolder.mSurface = mSurface;
909 }
910 mSurfaceHolder.mSurfaceLock.unlock();
911 if (mSurface.isValid()) {
912 if (!hadSurface) {
913 mSurfaceHolder.ungetCallbacks();
914
915 mIsCreating = true;
916 mSurfaceHolderCallback.surfaceCreated(mSurfaceHolder);
917 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
918 if (callbacks != null) {
919 for (SurfaceHolder.Callback c : callbacks) {
920 c.surfaceCreated(mSurfaceHolder);
921 }
922 }
923 surfaceChanged = true;
924 }
925 if (surfaceChanged) {
926 mSurfaceHolderCallback.surfaceChanged(mSurfaceHolder,
927 lp.format, mWidth, mHeight);
928 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
929 if (callbacks != null) {
930 for (SurfaceHolder.Callback c : callbacks) {
931 c.surfaceChanged(mSurfaceHolder, lp.format,
932 mWidth, mHeight);
933 }
934 }
935 }
936 mIsCreating = false;
937 } else if (hadSurface) {
938 mSurfaceHolder.ungetCallbacks();
939 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
940 mSurfaceHolderCallback.surfaceDestroyed(mSurfaceHolder);
941 if (callbacks != null) {
942 for (SurfaceHolder.Callback c : callbacks) {
943 c.surfaceDestroyed(mSurfaceHolder);
944 }
945 }
946 mSurfaceHolder.mSurfaceLock.lock();
947 // Make surface invalid.
948 //mSurfaceHolder.mSurface.copyFrom(mSurface);
949 mSurfaceHolder.mSurface = new Surface();
950 mSurfaceHolder.mSurfaceLock.unlock();
951 }
952 }
953
Romain Guy812ccbe2010-06-01 14:07:24 -0700954 if (hwIntialized) {
955 mHwRenderer.setup(appScale);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800956 }
957
958 boolean focusChangedDueToTouchMode = ensureTouchModeLocally(
Romain Guy2d4cff62010-04-09 15:39:00 -0700959 (relayoutResult&WindowManagerImpl.RELAYOUT_IN_TOUCH_MODE) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800960 if (focusChangedDueToTouchMode || mWidth != host.mMeasuredWidth
961 || mHeight != host.mMeasuredHeight || contentInsetsChanged) {
962 childWidthMeasureSpec = getRootMeasureSpec(mWidth, lp.width);
963 childHeightMeasureSpec = getRootMeasureSpec(mHeight, lp.height);
964
965 if (DEBUG_LAYOUT) Log.v(TAG, "Ooops, something changed! mWidth="
966 + mWidth + " measuredWidth=" + host.mMeasuredWidth
967 + " mHeight=" + mHeight
968 + " measuredHeight" + host.mMeasuredHeight
969 + " coveredInsetsChanged=" + contentInsetsChanged);
Romain Guy8506ab42009-06-11 17:35:47 -0700970
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800971 // Ask host how big it wants to be
972 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
973
974 // Implementation of weights from WindowManager.LayoutParams
975 // We just grow the dimensions as needed and re-measure if
976 // needs be
977 int width = host.mMeasuredWidth;
978 int height = host.mMeasuredHeight;
979 boolean measureAgain = false;
980
981 if (lp.horizontalWeight > 0.0f) {
982 width += (int) ((mWidth - width) * lp.horizontalWeight);
983 childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(width,
984 MeasureSpec.EXACTLY);
985 measureAgain = true;
986 }
987 if (lp.verticalWeight > 0.0f) {
988 height += (int) ((mHeight - height) * lp.verticalWeight);
989 childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(height,
990 MeasureSpec.EXACTLY);
991 measureAgain = true;
992 }
993
994 if (measureAgain) {
995 if (DEBUG_LAYOUT) Log.v(TAG,
996 "And hey let's measure once more: width=" + width
997 + " height=" + height);
998 host.measure(childWidthMeasureSpec, childHeightMeasureSpec);
999 }
1000
1001 mLayoutRequested = true;
1002 }
1003 }
1004
1005 final boolean didLayout = mLayoutRequested;
1006 boolean triggerGlobalLayoutListener = didLayout
1007 || attachInfo.mRecomputeGlobalAttributes;
1008 if (didLayout) {
1009 mLayoutRequested = false;
1010 mScrollMayChange = true;
1011 if (DEBUG_ORIENTATION || DEBUG_LAYOUT) Log.v(
1012 "ViewRoot", "Laying out " + host + " to (" +
1013 host.mMeasuredWidth + ", " + host.mMeasuredHeight + ")");
Romain Guy13922e02009-05-12 17:56:14 -07001014 long startTime = 0L;
1015 if (Config.DEBUG && ViewDebug.profileLayout) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001016 startTime = SystemClock.elapsedRealtime();
1017 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001018 host.layout(0, 0, host.mMeasuredWidth, host.mMeasuredHeight);
1019
Romain Guy13922e02009-05-12 17:56:14 -07001020 if (Config.DEBUG && ViewDebug.consistencyCheckEnabled) {
1021 if (!host.dispatchConsistencyCheck(ViewDebug.CONSISTENCY_LAYOUT)) {
1022 throw new IllegalStateException("The view hierarchy is an inconsistent state,"
1023 + "please refer to the logs with the tag "
1024 + ViewDebug.CONSISTENCY_LOG_TAG + " for more infomation.");
1025 }
1026 }
1027
1028 if (Config.DEBUG && ViewDebug.profileLayout) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001029 EventLog.writeEvent(60001, SystemClock.elapsedRealtime() - startTime);
1030 }
1031
1032 // By this point all views have been sized and positionned
1033 // We can compute the transparent area
1034
1035 if ((host.mPrivateFlags & View.REQUEST_TRANSPARENT_REGIONS) != 0) {
1036 // start out transparent
1037 // TODO: AVOID THAT CALL BY CACHING THE RESULT?
1038 host.getLocationInWindow(mTmpLocation);
1039 mTransparentRegion.set(mTmpLocation[0], mTmpLocation[1],
1040 mTmpLocation[0] + host.mRight - host.mLeft,
1041 mTmpLocation[1] + host.mBottom - host.mTop);
1042
1043 host.gatherTransparentRegion(mTransparentRegion);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001044 if (mTranslator != null) {
1045 mTranslator.translateRegionInWindowToScreen(mTransparentRegion);
1046 }
1047
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001048 if (!mTransparentRegion.equals(mPreviousTransparentRegion)) {
1049 mPreviousTransparentRegion.set(mTransparentRegion);
1050 // reconfigure window manager
1051 try {
1052 sWindowSession.setTransparentRegion(mWindow, mTransparentRegion);
1053 } catch (RemoteException e) {
1054 }
1055 }
1056 }
1057
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001058 if (DBG) {
1059 System.out.println("======================================");
1060 System.out.println("performTraversals -- after setFrame");
1061 host.debug();
1062 }
1063 }
1064
1065 if (triggerGlobalLayoutListener) {
1066 attachInfo.mRecomputeGlobalAttributes = false;
1067 attachInfo.mTreeObserver.dispatchOnGlobalLayout();
1068 }
1069
1070 if (computesInternalInsets) {
1071 ViewTreeObserver.InternalInsetsInfo insets = attachInfo.mGivenInternalInsets;
1072 final Rect givenContent = attachInfo.mGivenInternalInsets.contentInsets;
1073 final Rect givenVisible = attachInfo.mGivenInternalInsets.visibleInsets;
1074 givenContent.left = givenContent.top = givenContent.right
1075 = givenContent.bottom = givenVisible.left = givenVisible.top
1076 = givenVisible.right = givenVisible.bottom = 0;
1077 attachInfo.mTreeObserver.dispatchOnComputeInternalInsets(insets);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001078 Rect contentInsets = insets.contentInsets;
1079 Rect visibleInsets = insets.visibleInsets;
1080 if (mTranslator != null) {
1081 contentInsets = mTranslator.getTranslatedContentInsets(contentInsets);
1082 visibleInsets = mTranslator.getTranslatedVisbileInsets(visibleInsets);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001083 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001084 if (insetsPending || !mLastGivenInsets.equals(insets)) {
1085 mLastGivenInsets.set(insets);
1086 try {
1087 sWindowSession.setInsets(mWindow, insets.mTouchableInsets,
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001088 contentInsets, visibleInsets);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001089 } catch (RemoteException e) {
1090 }
1091 }
1092 }
Romain Guy8506ab42009-06-11 17:35:47 -07001093
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001094 if (mFirst) {
1095 // handle first focus request
1096 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: mView.hasFocus()="
1097 + mView.hasFocus());
1098 if (mView != null) {
1099 if (!mView.hasFocus()) {
1100 mView.requestFocus(View.FOCUS_FORWARD);
1101 mFocusedView = mRealFocusedView = mView.findFocus();
1102 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: requested focused view="
1103 + mFocusedView);
1104 } else {
1105 mRealFocusedView = mView.findFocus();
1106 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "First: existing focused view="
1107 + mRealFocusedView);
1108 }
1109 }
1110 }
1111
1112 mFirst = false;
1113 mWillDrawSoon = false;
1114 mNewSurfaceNeeded = false;
1115 mViewVisibility = viewVisibility;
1116
1117 if (mAttachInfo.mHasWindowFocus) {
1118 final boolean imTarget = WindowManager.LayoutParams
1119 .mayUseInputMethod(mWindowAttributes.flags);
1120 if (imTarget != mLastWasImTarget) {
1121 mLastWasImTarget = imTarget;
1122 InputMethodManager imm = InputMethodManager.peekInstance();
1123 if (imm != null && imTarget) {
1124 imm.startGettingWindowFocus(mView);
1125 imm.onWindowFocus(mView, mView.findFocus(),
1126 mWindowAttributes.softInputMode,
1127 !mHasHadWindowFocus, mWindowAttributes.flags);
1128 }
1129 }
1130 }
Romain Guy8506ab42009-06-11 17:35:47 -07001131
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001132 boolean cancelDraw = attachInfo.mTreeObserver.dispatchOnPreDraw();
1133
1134 if (!cancelDraw && !newSurface) {
1135 mFullRedrawNeeded = false;
1136 draw(fullRedrawNeeded);
1137
1138 if ((relayoutResult&WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0
1139 || mReportNextDraw) {
1140 if (LOCAL_LOGV) {
1141 Log.v("ViewRoot", "FINISHED DRAWING: " + mWindowAttributes.getTitle());
1142 }
1143 mReportNextDraw = false;
1144 try {
1145 sWindowSession.finishDrawing(mWindow);
1146 } catch (RemoteException e) {
1147 }
1148 }
1149 } else {
1150 // We were supposed to report when we are done drawing. Since we canceled the
1151 // draw, remember it here.
1152 if ((relayoutResult&WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0) {
1153 mReportNextDraw = true;
1154 }
1155 if (fullRedrawNeeded) {
1156 mFullRedrawNeeded = true;
1157 }
1158 // Try again
1159 scheduleTraversals();
1160 }
1161 }
1162
1163 public void requestTransparentRegion(View child) {
1164 // the test below should not fail unless someone is messing with us
1165 checkThread();
1166 if (mView == child) {
1167 mView.mPrivateFlags |= View.REQUEST_TRANSPARENT_REGIONS;
1168 // Need to make sure we re-evaluate the window attributes next
1169 // time around, to ensure the window has the correct format.
1170 mWindowAttributesChanged = true;
1171 }
1172 }
1173
1174 /**
1175 * Figures out the measure spec for the root view in a window based on it's
1176 * layout params.
1177 *
1178 * @param windowSize
1179 * The available width or height of the window
1180 *
1181 * @param rootDimension
1182 * The layout params for one dimension (width or height) of the
1183 * window.
1184 *
1185 * @return The measure spec to use to measure the root view.
1186 */
1187 private int getRootMeasureSpec(int windowSize, int rootDimension) {
1188 int measureSpec;
1189 switch (rootDimension) {
1190
Romain Guy980a9382010-01-08 15:06:28 -08001191 case ViewGroup.LayoutParams.MATCH_PARENT:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001192 // Window can't resize. Force root view to be windowSize.
1193 measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.EXACTLY);
1194 break;
1195 case ViewGroup.LayoutParams.WRAP_CONTENT:
1196 // Window can resize. Set max size for root view.
1197 measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.AT_MOST);
1198 break;
1199 default:
1200 // Window wants to be an exact size. Force root view to be that size.
1201 measureSpec = MeasureSpec.makeMeasureSpec(rootDimension, MeasureSpec.EXACTLY);
1202 break;
1203 }
1204 return measureSpec;
1205 }
1206
1207 private void draw(boolean fullRedrawNeeded) {
1208 Surface surface = mSurface;
1209 if (surface == null || !surface.isValid()) {
1210 return;
1211 }
1212
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001213 if (!sFirstDrawComplete) {
1214 synchronized (sFirstDrawHandlers) {
1215 sFirstDrawComplete = true;
Romain Guy812ccbe2010-06-01 14:07:24 -07001216 final int count = sFirstDrawHandlers.size();
1217 for (int i = 0; i< count; i++) {
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001218 post(sFirstDrawHandlers.get(i));
1219 }
1220 }
1221 }
1222
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001223 scrollToRectOrFocus(null, false);
1224
1225 if (mAttachInfo.mViewScrollChanged) {
1226 mAttachInfo.mViewScrollChanged = false;
1227 mAttachInfo.mTreeObserver.dispatchOnScrollChanged();
1228 }
Romain Guy8506ab42009-06-11 17:35:47 -07001229
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001230 int yoff;
Romain Guy5bcdff42009-05-14 21:27:18 -07001231 final boolean scrolling = mScroller != null && mScroller.computeScrollOffset();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001232 if (scrolling) {
1233 yoff = mScroller.getCurrY();
1234 } else {
1235 yoff = mScrollY;
1236 }
1237 if (mCurScrollY != yoff) {
1238 mCurScrollY = yoff;
1239 fullRedrawNeeded = true;
1240 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001241 float appScale = mAttachInfo.mApplicationScale;
1242 boolean scalingRequired = mAttachInfo.mScalingRequired;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001243
1244 Rect dirty = mDirty;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001245 if (mSurfaceHolder != null) {
1246 // The app owns the surface, we won't draw.
1247 dirty.setEmpty();
1248 return;
1249 }
1250
Romain Guy812ccbe2010-06-01 14:07:24 -07001251 if (mHwRenderer != null && mHwRenderer.mEnabled) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001252 if (!dirty.isEmpty()) {
Romain Guy812ccbe2010-06-01 14:07:24 -07001253 mHwRenderer.draw(yoff, scalingRequired);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001254 }
Romain Guy812ccbe2010-06-01 14:07:24 -07001255
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001256 if (scrolling) {
1257 mFullRedrawNeeded = true;
1258 scheduleTraversals();
1259 }
Romain Guy812ccbe2010-06-01 14:07:24 -07001260
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001261 return;
1262 }
1263
Romain Guy5bcdff42009-05-14 21:27:18 -07001264 if (fullRedrawNeeded) {
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001265 mAttachInfo.mIgnoreDirtyState = true;
Mitsuru Oshima61324e52009-07-21 15:40:36 -07001266 dirty.union(0, 0, (int) (mWidth * appScale + 0.5f), (int) (mHeight * appScale + 0.5f));
Romain Guy5bcdff42009-05-14 21:27:18 -07001267 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001268
1269 if (DEBUG_ORIENTATION || DEBUG_DRAW) {
1270 Log.v("ViewRoot", "Draw " + mView + "/"
1271 + mWindowAttributes.getTitle()
1272 + ": dirty={" + dirty.left + "," + dirty.top
1273 + "," + dirty.right + "," + dirty.bottom + "} surface="
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07001274 + surface + " surface.isValid()=" + surface.isValid() + ", appScale:" +
1275 appScale + ", width=" + mWidth + ", height=" + mHeight);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001276 }
1277
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001278 if (!dirty.isEmpty() || mIsAnimating) {
1279 Canvas canvas;
1280 try {
1281 int left = dirty.left;
1282 int top = dirty.top;
1283 int right = dirty.right;
1284 int bottom = dirty.bottom;
1285 canvas = surface.lockCanvas(dirty);
Romain Guy5bcdff42009-05-14 21:27:18 -07001286
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001287 if (left != dirty.left || top != dirty.top || right != dirty.right ||
1288 bottom != dirty.bottom) {
1289 mAttachInfo.mIgnoreDirtyState = true;
1290 }
1291
1292 // TODO: Do this in native
1293 canvas.setDensity(mDensity);
1294 } catch (Surface.OutOfResourcesException e) {
1295 Log.e("ViewRoot", "OutOfResourcesException locking surface", e);
1296 // TODO: we should ask the window manager to do something!
1297 // for now we just do nothing
1298 return;
1299 } catch (IllegalArgumentException e) {
1300 Log.e("ViewRoot", "IllegalArgumentException locking surface", e);
1301 // TODO: we should ask the window manager to do something!
1302 // for now we just do nothing
1303 return;
Romain Guy5bcdff42009-05-14 21:27:18 -07001304 }
1305
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001306 try {
1307 if (!dirty.isEmpty() || mIsAnimating) {
1308 long startTime = 0L;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001309
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001310 if (DEBUG_ORIENTATION || DEBUG_DRAW) {
1311 Log.v("ViewRoot", "Surface " + surface + " drawing to bitmap w="
1312 + canvas.getWidth() + ", h=" + canvas.getHeight());
1313 //canvas.drawARGB(255, 255, 0, 0);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001314 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001315
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001316 if (Config.DEBUG && ViewDebug.profileDrawing) {
1317 startTime = SystemClock.elapsedRealtime();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001318 }
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001319
1320 // If this bitmap's format includes an alpha channel, we
1321 // need to clear it before drawing so that the child will
1322 // properly re-composite its drawing on a transparent
1323 // background. This automatically respects the clip/dirty region
1324 // or
1325 // If we are applying an offset, we need to clear the area
1326 // where the offset doesn't appear to avoid having garbage
1327 // left in the blank areas.
1328 if (!canvas.isOpaque() || yoff != 0) {
1329 canvas.drawColor(0, PorterDuff.Mode.CLEAR);
1330 }
1331
1332 dirty.setEmpty();
1333 mIsAnimating = false;
1334 mAttachInfo.mDrawingTime = SystemClock.uptimeMillis();
1335 mView.mPrivateFlags |= View.DRAWN;
1336
1337 if (DEBUG_DRAW) {
1338 Context cxt = mView.getContext();
1339 Log.i(TAG, "Drawing: package:" + cxt.getPackageName() +
1340 ", metrics=" + cxt.getResources().getDisplayMetrics() +
1341 ", compatibilityInfo=" + cxt.getResources().getCompatibilityInfo());
1342 }
1343 int saveCount = canvas.save(Canvas.MATRIX_SAVE_FLAG);
1344 try {
1345 canvas.translate(0, -yoff);
1346 if (mTranslator != null) {
1347 mTranslator.translateCanvas(canvas);
1348 }
1349 canvas.setScreenDensity(scalingRequired
1350 ? DisplayMetrics.DENSITY_DEVICE : 0);
1351 mView.draw(canvas);
1352 } finally {
1353 mAttachInfo.mIgnoreDirtyState = false;
1354 canvas.restoreToCount(saveCount);
1355 }
1356
1357 if (Config.DEBUG && ViewDebug.consistencyCheckEnabled) {
1358 mView.dispatchConsistencyCheck(ViewDebug.CONSISTENCY_DRAWING);
1359 }
1360
1361 if (SHOW_FPS || Config.DEBUG && ViewDebug.showFps) {
1362 int now = (int)SystemClock.elapsedRealtime();
1363 if (sDrawTime != 0) {
1364 nativeShowFPS(canvas, now - sDrawTime);
1365 }
1366 sDrawTime = now;
1367 }
1368
1369 if (Config.DEBUG && ViewDebug.profileDrawing) {
1370 EventLog.writeEvent(60000, SystemClock.elapsedRealtime() - startTime);
1371 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001372 }
1373
Mathias Agopiana62b09a2010-04-21 18:36:53 -07001374 } finally {
1375 surface.unlockCanvasAndPost(canvas);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001376 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001377 }
1378
1379 if (LOCAL_LOGV) {
1380 Log.v("ViewRoot", "Surface " + surface + " unlockCanvasAndPost");
1381 }
Romain Guy8506ab42009-06-11 17:35:47 -07001382
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001383 if (scrolling) {
1384 mFullRedrawNeeded = true;
1385 scheduleTraversals();
1386 }
1387 }
1388
1389 boolean scrollToRectOrFocus(Rect rectangle, boolean immediate) {
1390 final View.AttachInfo attachInfo = mAttachInfo;
1391 final Rect ci = attachInfo.mContentInsets;
1392 final Rect vi = attachInfo.mVisibleInsets;
1393 int scrollY = 0;
1394 boolean handled = false;
Romain Guy8506ab42009-06-11 17:35:47 -07001395
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001396 if (vi.left > ci.left || vi.top > ci.top
1397 || vi.right > ci.right || vi.bottom > ci.bottom) {
1398 // We'll assume that we aren't going to change the scroll
1399 // offset, since we want to avoid that unless it is actually
1400 // going to make the focus visible... otherwise we scroll
1401 // all over the place.
1402 scrollY = mScrollY;
1403 // We can be called for two different situations: during a draw,
1404 // to update the scroll position if the focus has changed (in which
1405 // case 'rectangle' is null), or in response to a
1406 // requestChildRectangleOnScreen() call (in which case 'rectangle'
1407 // is non-null and we just want to scroll to whatever that
1408 // rectangle is).
1409 View focus = mRealFocusedView;
Romain Guye8b16522009-07-14 13:06:42 -07001410
1411 // When in touch mode, focus points to the previously focused view,
1412 // which may have been removed from the view hierarchy. The following
Joe Onoratob71193b2009-11-24 18:34:42 -05001413 // line checks whether the view is still in our hierarchy.
1414 if (focus == null || focus.mAttachInfo != mAttachInfo) {
Romain Guye8b16522009-07-14 13:06:42 -07001415 mRealFocusedView = null;
1416 return false;
1417 }
1418
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001419 if (focus != mLastScrolledFocus) {
1420 // If the focus has changed, then ignore any requests to scroll
1421 // to a rectangle; first we want to make sure the entire focus
1422 // view is visible.
1423 rectangle = null;
1424 }
1425 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Eval scroll: focus=" + focus
1426 + " rectangle=" + rectangle + " ci=" + ci
1427 + " vi=" + vi);
1428 if (focus == mLastScrolledFocus && !mScrollMayChange
1429 && rectangle == null) {
1430 // Optimization: if the focus hasn't changed since last
1431 // time, and no layout has happened, then just leave things
1432 // as they are.
1433 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Keeping scroll y="
1434 + mScrollY + " vi=" + vi.toShortString());
1435 } else if (focus != null) {
1436 // We need to determine if the currently focused view is
1437 // within the visible part of the window and, if not, apply
1438 // a pan so it can be seen.
1439 mLastScrolledFocus = focus;
1440 mScrollMayChange = false;
1441 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Need to scroll?");
1442 // Try to find the rectangle from the focus view.
1443 if (focus.getGlobalVisibleRect(mVisRect, null)) {
1444 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Root w="
1445 + mView.getWidth() + " h=" + mView.getHeight()
1446 + " ci=" + ci.toShortString()
1447 + " vi=" + vi.toShortString());
1448 if (rectangle == null) {
1449 focus.getFocusedRect(mTempRect);
1450 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Focus " + focus
1451 + ": focusRect=" + mTempRect.toShortString());
Dianne Hackborn1c6a8942010-03-23 16:34:20 -07001452 if (mView instanceof ViewGroup) {
1453 ((ViewGroup) mView).offsetDescendantRectToMyCoords(
1454 focus, mTempRect);
1455 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001456 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1457 "Focus in window: focusRect="
1458 + mTempRect.toShortString()
1459 + " visRect=" + mVisRect.toShortString());
1460 } else {
1461 mTempRect.set(rectangle);
1462 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1463 "Request scroll to rect: "
1464 + mTempRect.toShortString()
1465 + " visRect=" + mVisRect.toShortString());
1466 }
1467 if (mTempRect.intersect(mVisRect)) {
1468 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1469 "Focus window visible rect: "
1470 + mTempRect.toShortString());
1471 if (mTempRect.height() >
1472 (mView.getHeight()-vi.top-vi.bottom)) {
1473 // If the focus simply is not going to fit, then
1474 // best is probably just to leave things as-is.
1475 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1476 "Too tall; leaving scrollY=" + scrollY);
1477 } else if ((mTempRect.top-scrollY) < vi.top) {
1478 scrollY -= vi.top - (mTempRect.top-scrollY);
1479 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1480 "Top covered; scrollY=" + scrollY);
1481 } else if ((mTempRect.bottom-scrollY)
1482 > (mView.getHeight()-vi.bottom)) {
1483 scrollY += (mTempRect.bottom-scrollY)
1484 - (mView.getHeight()-vi.bottom);
1485 if (DEBUG_INPUT_RESIZE) Log.v(TAG,
1486 "Bottom covered; scrollY=" + scrollY);
1487 }
1488 handled = true;
1489 }
1490 }
1491 }
1492 }
Romain Guy8506ab42009-06-11 17:35:47 -07001493
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001494 if (scrollY != mScrollY) {
1495 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Pan scroll changed: old="
1496 + mScrollY + " , new=" + scrollY);
1497 if (!immediate) {
1498 if (mScroller == null) {
1499 mScroller = new Scroller(mView.getContext());
1500 }
1501 mScroller.startScroll(0, mScrollY, 0, scrollY-mScrollY);
1502 } else if (mScroller != null) {
1503 mScroller.abortAnimation();
1504 }
1505 mScrollY = scrollY;
1506 }
Romain Guy8506ab42009-06-11 17:35:47 -07001507
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001508 return handled;
1509 }
Romain Guy8506ab42009-06-11 17:35:47 -07001510
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001511 public void requestChildFocus(View child, View focused) {
1512 checkThread();
1513 if (mFocusedView != focused) {
1514 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(mFocusedView, focused);
1515 scheduleTraversals();
1516 }
1517 mFocusedView = mRealFocusedView = focused;
1518 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Request child focus: focus now "
1519 + mFocusedView);
1520 }
1521
1522 public void clearChildFocus(View child) {
1523 checkThread();
1524
1525 View oldFocus = mFocusedView;
1526
1527 if (DEBUG_INPUT_RESIZE) Log.v(TAG, "Clearing child focus");
1528 mFocusedView = mRealFocusedView = null;
1529 if (mView != null && !mView.hasFocus()) {
1530 // If a view gets the focus, the listener will be invoked from requestChildFocus()
1531 if (!mView.requestFocus(View.FOCUS_FORWARD)) {
1532 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
1533 }
1534 } else if (oldFocus != null) {
1535 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
1536 }
1537 }
1538
1539
1540 public void focusableViewAvailable(View v) {
1541 checkThread();
1542
1543 if (mView != null && !mView.hasFocus()) {
1544 v.requestFocus();
1545 } else {
1546 // the one case where will transfer focus away from the current one
1547 // is if the current view is a view group that prefers to give focus
1548 // to its children first AND the view is a descendant of it.
1549 mFocusedView = mView.findFocus();
1550 boolean descendantsHaveDibsOnFocus =
1551 (mFocusedView instanceof ViewGroup) &&
1552 (((ViewGroup) mFocusedView).getDescendantFocusability() ==
1553 ViewGroup.FOCUS_AFTER_DESCENDANTS);
1554 if (descendantsHaveDibsOnFocus && isViewDescendantOf(v, mFocusedView)) {
1555 // If a view gets the focus, the listener will be invoked from requestChildFocus()
1556 v.requestFocus();
1557 }
1558 }
1559 }
1560
1561 public void recomputeViewAttributes(View child) {
1562 checkThread();
1563 if (mView == child) {
1564 mAttachInfo.mRecomputeGlobalAttributes = true;
1565 if (!mWillDrawSoon) {
1566 scheduleTraversals();
1567 }
1568 }
1569 }
1570
1571 void dispatchDetachedFromWindow() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001572 if (mView != null) {
1573 mView.dispatchDetachedFromWindow();
1574 }
1575
1576 mView = null;
1577 mAttachInfo.mRootView = null;
Mathias Agopian5583dc62009-07-09 16:28:11 -07001578 mAttachInfo.mSurface = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001579
Romain Guy812ccbe2010-06-01 14:07:24 -07001580 if (mHwRenderer != null) {
1581 mHwRenderer.destroyGL();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001582 }
Dianne Hackborn0586a1b2009-09-06 21:08:27 -07001583 mSurface.release();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001584
1585 try {
1586 sWindowSession.remove(mWindow);
1587 } catch (RemoteException e) {
1588 }
1589 }
Romain Guy8506ab42009-06-11 17:35:47 -07001590
Dianne Hackborn694f79b2010-03-17 19:44:59 -07001591 void updateConfiguration(Configuration config, boolean force) {
1592 if (DEBUG_CONFIGURATION) Log.v(TAG,
1593 "Applying new config to window "
1594 + mWindowAttributes.getTitle()
1595 + ": " + config);
1596 synchronized (sConfigCallbacks) {
1597 for (int i=sConfigCallbacks.size()-1; i>=0; i--) {
1598 sConfigCallbacks.get(i).onConfigurationChanged(config);
1599 }
1600 }
1601 if (mView != null) {
1602 // At this point the resources have been updated to
1603 // have the most recent config, whatever that is. Use
1604 // the on in them which may be newer.
1605 if (mView != null) {
1606 config = mView.getResources().getConfiguration();
1607 }
1608 if (force || mLastConfiguration.diff(config) != 0) {
1609 mLastConfiguration.setTo(config);
1610 mView.dispatchConfigurationChanged(config);
1611 }
1612 }
1613 }
1614
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001615 /**
1616 * Return true if child is an ancestor of parent, (or equal to the parent).
1617 */
1618 private static boolean isViewDescendantOf(View child, View parent) {
1619 if (child == parent) {
1620 return true;
1621 }
1622
1623 final ViewParent theParent = child.getParent();
1624 return (theParent instanceof ViewGroup) && isViewDescendantOf((View) theParent, parent);
1625 }
1626
Romain Guycdb86672010-03-18 18:54:50 -07001627 private static void forceLayout(View view) {
1628 view.forceLayout();
1629 if (view instanceof ViewGroup) {
1630 ViewGroup group = (ViewGroup) view;
1631 final int count = group.getChildCount();
1632 for (int i = 0; i < count; i++) {
1633 forceLayout(group.getChildAt(i));
1634 }
1635 }
1636 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001637
1638 public final static int DO_TRAVERSAL = 1000;
1639 public final static int DIE = 1001;
1640 public final static int RESIZED = 1002;
1641 public final static int RESIZED_REPORT = 1003;
1642 public final static int WINDOW_FOCUS_CHANGED = 1004;
1643 public final static int DISPATCH_KEY = 1005;
1644 public final static int DISPATCH_POINTER = 1006;
1645 public final static int DISPATCH_TRACKBALL = 1007;
1646 public final static int DISPATCH_APP_VISIBILITY = 1008;
1647 public final static int DISPATCH_GET_NEW_SURFACE = 1009;
1648 public final static int FINISHED_EVENT = 1010;
1649 public final static int DISPATCH_KEY_FROM_IME = 1011;
1650 public final static int FINISH_INPUT_CONNECTION = 1012;
1651 public final static int CHECK_FOCUS = 1013;
Dianne Hackbornffa42482009-09-23 22:20:11 -07001652 public final static int CLOSE_SYSTEM_DIALOGS = 1014;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001653
1654 @Override
1655 public void handleMessage(Message msg) {
1656 switch (msg.what) {
1657 case View.AttachInfo.INVALIDATE_MSG:
1658 ((View) msg.obj).invalidate();
1659 break;
1660 case View.AttachInfo.INVALIDATE_RECT_MSG:
1661 final View.AttachInfo.InvalidateInfo info = (View.AttachInfo.InvalidateInfo) msg.obj;
1662 info.target.invalidate(info.left, info.top, info.right, info.bottom);
1663 info.release();
1664 break;
1665 case DO_TRAVERSAL:
1666 if (mProfile) {
1667 Debug.startMethodTracing("ViewRoot");
1668 }
1669
1670 performTraversals();
1671
1672 if (mProfile) {
1673 Debug.stopMethodTracing();
1674 mProfile = false;
1675 }
1676 break;
1677 case FINISHED_EVENT:
1678 handleFinishedEvent(msg.arg1, msg.arg2 != 0);
1679 break;
1680 case DISPATCH_KEY:
1681 if (LOCAL_LOGV) Log.v(
1682 "ViewRoot", "Dispatching key "
1683 + msg.obj + " to " + mView);
1684 deliverKeyEvent((KeyEvent)msg.obj, true);
1685 break;
The Android Open Source Project10592532009-03-18 17:39:46 -07001686 case DISPATCH_POINTER: {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001687 MotionEvent event = (MotionEvent)msg.obj;
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07001688 boolean callWhenDone = msg.arg1 != 0;
1689
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001690 if (event == null) {
1691 try {
Michael Chan53071d62009-05-13 17:29:48 -07001692 long timeBeforeGettingEvents;
1693 if (MEASURE_LATENCY) {
1694 timeBeforeGettingEvents = System.nanoTime();
1695 }
1696
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001697 event = sWindowSession.getPendingPointerMove(mWindow);
Michael Chan53071d62009-05-13 17:29:48 -07001698
1699 if (MEASURE_LATENCY && event != null) {
Romain Guy812ccbe2010-06-01 14:07:24 -07001700 lt.sample("9 Client got events ",
1701 System.nanoTime() - event.getEventTimeNano());
1702 lt.sample("8 Client getting events ",
1703 timeBeforeGettingEvents - event.getEventTimeNano());
Michael Chan53071d62009-05-13 17:29:48 -07001704 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001705 } catch (RemoteException e) {
1706 }
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07001707 callWhenDone = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001708 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001709 if (event != null && mTranslator != null) {
1710 mTranslator.translateEventInScreenToAppWindow(event);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001711 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001712 try {
1713 boolean handled;
1714 if (mView != null && mAdded && event != null) {
1715
1716 // enter touch mode on the down
1717 boolean isDown = event.getAction() == MotionEvent.ACTION_DOWN;
1718 if (isDown) {
1719 ensureTouchMode(true);
1720 }
1721 if(Config.LOGV) {
1722 captureMotionLog("captureDispatchPointer", event);
1723 }
Dianne Hackbornddca3ee2009-07-23 19:01:31 -07001724 if (mCurScrollY != 0) {
1725 event.offsetLocation(0, mCurScrollY);
1726 }
Michael Chan53071d62009-05-13 17:29:48 -07001727 if (MEASURE_LATENCY) {
Romain Guy812ccbe2010-06-01 14:07:24 -07001728 lt.sample("A Dispatching TouchEvents",
1729 System.nanoTime() - event.getEventTimeNano());
Michael Chan53071d62009-05-13 17:29:48 -07001730 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001731 handled = mView.dispatchTouchEvent(event);
Michael Chan53071d62009-05-13 17:29:48 -07001732 if (MEASURE_LATENCY) {
Romain Guy812ccbe2010-06-01 14:07:24 -07001733 lt.sample("B Dispatched TouchEvents ",
1734 System.nanoTime() - event.getEventTimeNano());
Michael Chan53071d62009-05-13 17:29:48 -07001735 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001736 if (!handled && isDown) {
1737 int edgeSlop = mViewConfiguration.getScaledEdgeSlop();
1738
1739 final int edgeFlags = event.getEdgeFlags();
1740 int direction = View.FOCUS_UP;
1741 int x = (int)event.getX();
1742 int y = (int)event.getY();
1743 final int[] deltas = new int[2];
1744
1745 if ((edgeFlags & MotionEvent.EDGE_TOP) != 0) {
1746 direction = View.FOCUS_DOWN;
1747 if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
1748 deltas[0] = edgeSlop;
1749 x += edgeSlop;
1750 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
1751 deltas[0] = -edgeSlop;
1752 x -= edgeSlop;
1753 }
1754 } else if ((edgeFlags & MotionEvent.EDGE_BOTTOM) != 0) {
1755 direction = View.FOCUS_UP;
1756 if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
1757 deltas[0] = edgeSlop;
1758 x += edgeSlop;
1759 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
1760 deltas[0] = -edgeSlop;
1761 x -= edgeSlop;
1762 }
1763 } else if ((edgeFlags & MotionEvent.EDGE_LEFT) != 0) {
1764 direction = View.FOCUS_RIGHT;
1765 } else if ((edgeFlags & MotionEvent.EDGE_RIGHT) != 0) {
1766 direction = View.FOCUS_LEFT;
1767 }
1768
1769 if (edgeFlags != 0 && mView instanceof ViewGroup) {
1770 View nearest = FocusFinder.getInstance().findNearestTouchable(
1771 ((ViewGroup) mView), x, y, direction, deltas);
1772 if (nearest != null) {
1773 event.offsetLocation(deltas[0], deltas[1]);
1774 event.setEdgeFlags(0);
1775 mView.dispatchTouchEvent(event);
1776 }
1777 }
1778 }
1779 }
1780 } finally {
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07001781 if (callWhenDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001782 try {
1783 sWindowSession.finishKey(mWindow);
1784 } catch (RemoteException e) {
1785 }
1786 }
1787 if (event != null) {
1788 event.recycle();
1789 }
1790 if (LOCAL_LOGV || WATCH_POINTER) Log.i(TAG, "Done dispatching!");
1791 // Let the exception fall through -- the looper will catch
1792 // it and take care of the bad app for us.
1793 }
The Android Open Source Project10592532009-03-18 17:39:46 -07001794 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001795 case DISPATCH_TRACKBALL:
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07001796 deliverTrackballEvent((MotionEvent)msg.obj, msg.arg1 != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001797 break;
1798 case DISPATCH_APP_VISIBILITY:
1799 handleAppVisibility(msg.arg1 != 0);
1800 break;
1801 case DISPATCH_GET_NEW_SURFACE:
1802 handleGetNewSurface();
1803 break;
1804 case RESIZED:
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001805 ResizedInfo ri = (ResizedInfo)msg.obj;
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001806
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001807 if (mWinFrame.width() == msg.arg1 && mWinFrame.height() == msg.arg2
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001808 && mPendingContentInsets.equals(ri.coveredInsets)
Dianne Hackbornd49258f2010-03-26 00:44:29 -07001809 && mPendingVisibleInsets.equals(ri.visibleInsets)
1810 && ((ResizedInfo)msg.obj).newConfig == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001811 break;
1812 }
1813 // fall through...
1814 case RESIZED_REPORT:
1815 if (mAdded) {
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001816 Configuration config = ((ResizedInfo)msg.obj).newConfig;
1817 if (config != null) {
Dianne Hackborn694f79b2010-03-17 19:44:59 -07001818 updateConfiguration(config, false);
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001819 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001820 mWinFrame.left = 0;
1821 mWinFrame.right = msg.arg1;
1822 mWinFrame.top = 0;
1823 mWinFrame.bottom = msg.arg2;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08001824 mPendingContentInsets.set(((ResizedInfo)msg.obj).coveredInsets);
1825 mPendingVisibleInsets.set(((ResizedInfo)msg.obj).visibleInsets);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001826 if (msg.what == RESIZED_REPORT) {
1827 mReportNextDraw = true;
1828 }
Romain Guycdb86672010-03-18 18:54:50 -07001829
1830 if (mView != null) {
1831 forceLayout(mView);
1832 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001833 requestLayout();
1834 }
1835 break;
1836 case WINDOW_FOCUS_CHANGED: {
1837 if (mAdded) {
1838 boolean hasWindowFocus = msg.arg1 != 0;
1839 mAttachInfo.mHasWindowFocus = hasWindowFocus;
1840 if (hasWindowFocus) {
1841 boolean inTouchMode = msg.arg2 != 0;
Romain Guy2d4cff62010-04-09 15:39:00 -07001842 ensureTouchModeLocally(inTouchMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001843
Romain Guy812ccbe2010-06-01 14:07:24 -07001844 if (mHwRenderer != null) {
1845 mHwRenderer.initializeAndSetup();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001846 }
1847 }
Romain Guy8506ab42009-06-11 17:35:47 -07001848
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001849 mLastWasImTarget = WindowManager.LayoutParams
1850 .mayUseInputMethod(mWindowAttributes.flags);
Romain Guy8506ab42009-06-11 17:35:47 -07001851
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001852 InputMethodManager imm = InputMethodManager.peekInstance();
1853 if (mView != null) {
1854 if (hasWindowFocus && imm != null && mLastWasImTarget) {
1855 imm.startGettingWindowFocus(mView);
1856 }
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07001857 mAttachInfo.mKeyDispatchState.reset();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001858 mView.dispatchWindowFocusChanged(hasWindowFocus);
1859 }
svetoslavganov75986cf2009-05-14 22:28:01 -07001860
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001861 // Note: must be done after the focus change callbacks,
1862 // so all of the view state is set up correctly.
1863 if (hasWindowFocus) {
1864 if (imm != null && mLastWasImTarget) {
1865 imm.onWindowFocus(mView, mView.findFocus(),
1866 mWindowAttributes.softInputMode,
1867 !mHasHadWindowFocus, mWindowAttributes.flags);
1868 }
1869 // Clear the forward bit. We can just do this directly, since
1870 // the window manager doesn't care about it.
1871 mWindowAttributes.softInputMode &=
1872 ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
1873 ((WindowManager.LayoutParams)mView.getLayoutParams())
1874 .softInputMode &=
1875 ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
1876 mHasHadWindowFocus = true;
1877 }
svetoslavganov75986cf2009-05-14 22:28:01 -07001878
1879 if (hasWindowFocus && mView != null) {
1880 sendAccessibilityEvents();
1881 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001882 }
1883 } break;
1884 case DIE:
Dianne Hackborn94d69142009-09-28 22:14:42 -07001885 doDie();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001886 break;
The Android Open Source Project10592532009-03-18 17:39:46 -07001887 case DISPATCH_KEY_FROM_IME: {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001888 if (LOCAL_LOGV) Log.v(
1889 "ViewRoot", "Dispatching key "
1890 + msg.obj + " from IME to " + mView);
The Android Open Source Project10592532009-03-18 17:39:46 -07001891 KeyEvent event = (KeyEvent)msg.obj;
1892 if ((event.getFlags()&KeyEvent.FLAG_FROM_SYSTEM) != 0) {
1893 // The IME is trying to say this event is from the
1894 // system! Bad bad bad!
Romain Guy812ccbe2010-06-01 14:07:24 -07001895 event = KeyEvent.changeFlags(event, event.getFlags() & ~KeyEvent.FLAG_FROM_SYSTEM);
The Android Open Source Project10592532009-03-18 17:39:46 -07001896 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001897 deliverKeyEventToViewHierarchy((KeyEvent)msg.obj, false);
The Android Open Source Project10592532009-03-18 17:39:46 -07001898 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001899 case FINISH_INPUT_CONNECTION: {
1900 InputMethodManager imm = InputMethodManager.peekInstance();
1901 if (imm != null) {
1902 imm.reportFinishInputConnection((InputConnection)msg.obj);
1903 }
1904 } break;
1905 case CHECK_FOCUS: {
1906 InputMethodManager imm = InputMethodManager.peekInstance();
1907 if (imm != null) {
1908 imm.checkFocus();
1909 }
1910 } break;
Dianne Hackbornffa42482009-09-23 22:20:11 -07001911 case CLOSE_SYSTEM_DIALOGS: {
1912 if (mView != null) {
1913 mView.onCloseSystemDialogs((String)msg.obj);
1914 }
1915 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001916 }
1917 }
1918
1919 /**
1920 * Something in the current window tells us we need to change the touch mode. For
1921 * example, we are not in touch mode, and the user touches the screen.
1922 *
1923 * If the touch mode has changed, tell the window manager, and handle it locally.
1924 *
1925 * @param inTouchMode Whether we want to be in touch mode.
1926 * @return True if the touch mode changed and focus changed was changed as a result
1927 */
1928 boolean ensureTouchMode(boolean inTouchMode) {
1929 if (DBG) Log.d("touchmode", "ensureTouchMode(" + inTouchMode + "), current "
1930 + "touch mode is " + mAttachInfo.mInTouchMode);
1931 if (mAttachInfo.mInTouchMode == inTouchMode) return false;
1932
1933 // tell the window manager
1934 try {
1935 sWindowSession.setInTouchMode(inTouchMode);
1936 } catch (RemoteException e) {
1937 throw new RuntimeException(e);
1938 }
1939
1940 // handle the change
Romain Guy2d4cff62010-04-09 15:39:00 -07001941 return ensureTouchModeLocally(inTouchMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001942 }
1943
1944 /**
1945 * Ensure that the touch mode for this window is set, and if it is changing,
1946 * take the appropriate action.
1947 * @param inTouchMode Whether we want to be in touch mode.
1948 * @return True if the touch mode changed and focus changed was changed as a result
1949 */
Romain Guy2d4cff62010-04-09 15:39:00 -07001950 private boolean ensureTouchModeLocally(boolean inTouchMode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001951 if (DBG) Log.d("touchmode", "ensureTouchModeLocally(" + inTouchMode + "), current "
1952 + "touch mode is " + mAttachInfo.mInTouchMode);
1953
1954 if (mAttachInfo.mInTouchMode == inTouchMode) return false;
1955
1956 mAttachInfo.mInTouchMode = inTouchMode;
1957 mAttachInfo.mTreeObserver.dispatchOnTouchModeChanged(inTouchMode);
1958
Romain Guy2d4cff62010-04-09 15:39:00 -07001959 return (inTouchMode) ? enterTouchMode() : leaveTouchMode();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001960 }
1961
1962 private boolean enterTouchMode() {
1963 if (mView != null) {
1964 if (mView.hasFocus()) {
1965 // note: not relying on mFocusedView here because this could
1966 // be when the window is first being added, and mFocused isn't
1967 // set yet.
1968 final View focused = mView.findFocus();
1969 if (focused != null && !focused.isFocusableInTouchMode()) {
1970
1971 final ViewGroup ancestorToTakeFocus =
1972 findAncestorToTakeFocusInTouchMode(focused);
1973 if (ancestorToTakeFocus != null) {
1974 // there is an ancestor that wants focus after its descendants that
1975 // is focusable in touch mode.. give it focus
1976 return ancestorToTakeFocus.requestFocus();
1977 } else {
1978 // nothing appropriate to have focus in touch mode, clear it out
1979 mView.unFocus();
1980 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(focused, null);
1981 mFocusedView = null;
1982 return true;
1983 }
1984 }
1985 }
1986 }
1987 return false;
1988 }
1989
1990
1991 /**
1992 * Find an ancestor of focused that wants focus after its descendants and is
1993 * focusable in touch mode.
1994 * @param focused The currently focused view.
1995 * @return An appropriate view, or null if no such view exists.
1996 */
1997 private ViewGroup findAncestorToTakeFocusInTouchMode(View focused) {
1998 ViewParent parent = focused.getParent();
1999 while (parent instanceof ViewGroup) {
2000 final ViewGroup vgParent = (ViewGroup) parent;
2001 if (vgParent.getDescendantFocusability() == ViewGroup.FOCUS_AFTER_DESCENDANTS
2002 && vgParent.isFocusableInTouchMode()) {
2003 return vgParent;
2004 }
2005 if (vgParent.isRootNamespace()) {
2006 return null;
2007 } else {
2008 parent = vgParent.getParent();
2009 }
2010 }
2011 return null;
2012 }
2013
2014 private boolean leaveTouchMode() {
2015 if (mView != null) {
2016 if (mView.hasFocus()) {
2017 // i learned the hard way to not trust mFocusedView :)
2018 mFocusedView = mView.findFocus();
2019 if (!(mFocusedView instanceof ViewGroup)) {
2020 // some view has focus, let it keep it
2021 return false;
2022 } else if (((ViewGroup)mFocusedView).getDescendantFocusability() !=
2023 ViewGroup.FOCUS_AFTER_DESCENDANTS) {
2024 // some view group has focus, and doesn't prefer its children
2025 // over itself for focus, so let them keep it.
2026 return false;
2027 }
2028 }
2029
2030 // find the best view to give focus to in this brave new non-touch-mode
2031 // world
2032 final View focused = focusSearch(null, View.FOCUS_DOWN);
2033 if (focused != null) {
2034 return focused.requestFocus(View.FOCUS_DOWN);
2035 }
2036 }
2037 return false;
2038 }
2039
2040
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07002041 private void deliverTrackballEvent(MotionEvent event, boolean callWhenDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002042 if (event == null) {
2043 try {
2044 event = sWindowSession.getPendingTrackballMove(mWindow);
2045 } catch (RemoteException e) {
2046 }
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07002047 callWhenDone = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002048 }
2049
2050 if (DEBUG_TRACKBALL) Log.v(TAG, "Motion event:" + event);
2051
2052 boolean handled = false;
2053 try {
2054 if (event == null) {
2055 handled = true;
2056 } else if (mView != null && mAdded) {
2057 handled = mView.dispatchTrackballEvent(event);
2058 if (!handled) {
2059 // we could do something here, like changing the focus
2060 // or something?
2061 }
2062 }
2063 } finally {
2064 if (handled) {
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07002065 if (callWhenDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002066 try {
2067 sWindowSession.finishKey(mWindow);
2068 } catch (RemoteException e) {
2069 }
2070 }
2071 if (event != null) {
2072 event.recycle();
2073 }
2074 // If we reach this, we delivered a trackball event to mView and
2075 // mView consumed it. Because we will not translate the trackball
2076 // event into a key event, touch mode will not exit, so we exit
2077 // touch mode here.
2078 ensureTouchMode(false);
2079 //noinspection ReturnInsideFinallyBlock
2080 return;
2081 }
2082 // Let the exception fall through -- the looper will catch
2083 // it and take care of the bad app for us.
2084 }
2085
2086 final TrackballAxis x = mTrackballAxisX;
2087 final TrackballAxis y = mTrackballAxisY;
2088
2089 long curTime = SystemClock.uptimeMillis();
2090 if ((mLastTrackballTime+MAX_TRACKBALL_DELAY) < curTime) {
2091 // It has been too long since the last movement,
2092 // so restart at the beginning.
2093 x.reset(0);
2094 y.reset(0);
2095 mLastTrackballTime = curTime;
2096 }
2097
2098 try {
2099 final int action = event.getAction();
2100 final int metastate = event.getMetaState();
2101 switch (action) {
2102 case MotionEvent.ACTION_DOWN:
2103 x.reset(2);
2104 y.reset(2);
2105 deliverKeyEvent(new KeyEvent(curTime, curTime,
2106 KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_CENTER,
2107 0, metastate), false);
2108 break;
2109 case MotionEvent.ACTION_UP:
2110 x.reset(2);
2111 y.reset(2);
2112 deliverKeyEvent(new KeyEvent(curTime, curTime,
2113 KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_CENTER,
2114 0, metastate), false);
2115 break;
2116 }
2117
2118 if (DEBUG_TRACKBALL) Log.v(TAG, "TB X=" + x.position + " step="
2119 + x.step + " dir=" + x.dir + " acc=" + x.acceleration
2120 + " move=" + event.getX()
2121 + " / Y=" + y.position + " step="
2122 + y.step + " dir=" + y.dir + " acc=" + y.acceleration
2123 + " move=" + event.getY());
2124 final float xOff = x.collect(event.getX(), event.getEventTime(), "X");
2125 final float yOff = y.collect(event.getY(), event.getEventTime(), "Y");
2126
2127 // Generate DPAD events based on the trackball movement.
2128 // We pick the axis that has moved the most as the direction of
2129 // the DPAD. When we generate DPAD events for one axis, then the
2130 // other axis is reset -- we don't want to perform DPAD jumps due
2131 // to slight movements in the trackball when making major movements
2132 // along the other axis.
2133 int keycode = 0;
2134 int movement = 0;
2135 float accel = 1;
2136 if (xOff > yOff) {
2137 movement = x.generate((2/event.getXPrecision()));
2138 if (movement != 0) {
2139 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_RIGHT
2140 : KeyEvent.KEYCODE_DPAD_LEFT;
2141 accel = x.acceleration;
2142 y.reset(2);
2143 }
2144 } else if (yOff > 0) {
2145 movement = y.generate((2/event.getYPrecision()));
2146 if (movement != 0) {
2147 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_DOWN
2148 : KeyEvent.KEYCODE_DPAD_UP;
2149 accel = y.acceleration;
2150 x.reset(2);
2151 }
2152 }
2153
2154 if (keycode != 0) {
2155 if (movement < 0) movement = -movement;
2156 int accelMovement = (int)(movement * accel);
2157 if (DEBUG_TRACKBALL) Log.v(TAG, "Move: movement=" + movement
2158 + " accelMovement=" + accelMovement
2159 + " accel=" + accel);
2160 if (accelMovement > movement) {
2161 if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: "
2162 + keycode);
2163 movement--;
2164 deliverKeyEvent(new KeyEvent(curTime, curTime,
2165 KeyEvent.ACTION_MULTIPLE, keycode,
2166 accelMovement-movement, metastate), false);
2167 }
2168 while (movement > 0) {
2169 if (DEBUG_TRACKBALL) Log.v("foo", "Delivering fake DPAD: "
2170 + keycode);
2171 movement--;
2172 curTime = SystemClock.uptimeMillis();
2173 deliverKeyEvent(new KeyEvent(curTime, curTime,
2174 KeyEvent.ACTION_DOWN, keycode, 0, event.getMetaState()), false);
2175 deliverKeyEvent(new KeyEvent(curTime, curTime,
2176 KeyEvent.ACTION_UP, keycode, 0, metastate), false);
2177 }
2178 mLastTrackballTime = curTime;
2179 }
2180 } finally {
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07002181 if (callWhenDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002182 try {
2183 sWindowSession.finishKey(mWindow);
2184 } catch (RemoteException e) {
2185 }
2186 if (event != null) {
2187 event.recycle();
2188 }
2189 }
2190 // Let the exception fall through -- the looper will catch
2191 // it and take care of the bad app for us.
2192 }
2193 }
2194
2195 /**
2196 * @param keyCode The key code
2197 * @return True if the key is directional.
2198 */
2199 static boolean isDirectional(int keyCode) {
2200 switch (keyCode) {
2201 case KeyEvent.KEYCODE_DPAD_LEFT:
2202 case KeyEvent.KEYCODE_DPAD_RIGHT:
2203 case KeyEvent.KEYCODE_DPAD_UP:
2204 case KeyEvent.KEYCODE_DPAD_DOWN:
2205 return true;
2206 }
2207 return false;
2208 }
2209
2210 /**
2211 * Returns true if this key is a keyboard key.
2212 * @param keyEvent The key event.
2213 * @return whether this key is a keyboard key.
2214 */
2215 private static boolean isKeyboardKey(KeyEvent keyEvent) {
2216 final int convertedKey = keyEvent.getUnicodeChar();
2217 return convertedKey > 0;
2218 }
2219
2220
2221
2222 /**
2223 * See if the key event means we should leave touch mode (and leave touch
2224 * mode if so).
2225 * @param event The key event.
2226 * @return Whether this key event should be consumed (meaning the act of
2227 * leaving touch mode alone is considered the event).
2228 */
2229 private boolean checkForLeavingTouchModeAndConsume(KeyEvent event) {
Adam Powell51a6bee2010-03-15 14:07:28 -07002230 final int action = event.getAction();
2231 if (action != KeyEvent.ACTION_DOWN && action != KeyEvent.ACTION_MULTIPLE) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002232 return false;
2233 }
2234 if ((event.getFlags()&KeyEvent.FLAG_KEEP_TOUCH_MODE) != 0) {
2235 return false;
2236 }
2237
2238 // only relevant if we are in touch mode
2239 if (!mAttachInfo.mInTouchMode) {
2240 return false;
2241 }
2242
2243 // if something like an edit text has focus and the user is typing,
2244 // leave touch mode
2245 //
2246 // note: the condition of not being a keyboard key is kind of a hacky
2247 // approximation of whether we think the focused view will want the
2248 // key; if we knew for sure whether the focused view would consume
2249 // the event, that would be better.
2250 if (isKeyboardKey(event) && mView != null && mView.hasFocus()) {
2251 mFocusedView = mView.findFocus();
2252 if ((mFocusedView instanceof ViewGroup)
2253 && ((ViewGroup) mFocusedView).getDescendantFocusability() ==
2254 ViewGroup.FOCUS_AFTER_DESCENDANTS) {
2255 // something has focus, but is holding it weakly as a container
2256 return false;
2257 }
2258 if (ensureTouchMode(false)) {
2259 throw new IllegalStateException("should not have changed focus "
2260 + "when leaving touch mode while a view has focus.");
2261 }
2262 return false;
2263 }
2264
2265 if (isDirectional(event.getKeyCode())) {
2266 // no view has focus, so we leave touch mode (and find something
2267 // to give focus to). the event is consumed if we were able to
2268 // find something to give focus to.
2269 return ensureTouchMode(false);
2270 }
2271 return false;
2272 }
2273
2274 /**
Romain Guy8506ab42009-06-11 17:35:47 -07002275 * log motion events
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002276 */
2277 private static void captureMotionLog(String subTag, MotionEvent ev) {
Romain Guy8506ab42009-06-11 17:35:47 -07002278 //check dynamic switch
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002279 if (ev == null ||
2280 SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_EVENT, 0) == 0) {
2281 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002282 }
Romain Guy8506ab42009-06-11 17:35:47 -07002283
2284 StringBuilder sb = new StringBuilder(subTag + ": ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002285 sb.append(ev.getDownTime()).append(',');
2286 sb.append(ev.getEventTime()).append(',');
2287 sb.append(ev.getAction()).append(',');
Romain Guy8506ab42009-06-11 17:35:47 -07002288 sb.append(ev.getX()).append(',');
2289 sb.append(ev.getY()).append(',');
2290 sb.append(ev.getPressure()).append(',');
2291 sb.append(ev.getSize()).append(',');
2292 sb.append(ev.getMetaState()).append(',');
2293 sb.append(ev.getXPrecision()).append(',');
2294 sb.append(ev.getYPrecision()).append(',');
2295 sb.append(ev.getDeviceId()).append(',');
2296 sb.append(ev.getEdgeFlags());
2297 Log.d(TAG, sb.toString());
2298 }
2299 /**
2300 * log motion events
2301 */
2302 private static void captureKeyLog(String subTag, KeyEvent ev) {
2303 //check dynamic switch
2304 if (ev == null ||
2305 SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_EVENT, 0) == 0) {
2306 return;
2307 }
2308 StringBuilder sb = new StringBuilder(subTag + ": ");
2309 sb.append(ev.getDownTime()).append(',');
2310 sb.append(ev.getEventTime()).append(',');
2311 sb.append(ev.getAction()).append(',');
2312 sb.append(ev.getKeyCode()).append(',');
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002313 sb.append(ev.getRepeatCount()).append(',');
2314 sb.append(ev.getMetaState()).append(',');
2315 sb.append(ev.getDeviceId()).append(',');
2316 sb.append(ev.getScanCode());
Romain Guy8506ab42009-06-11 17:35:47 -07002317 Log.d(TAG, sb.toString());
2318 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002319
2320 int enqueuePendingEvent(Object event, boolean sendDone) {
2321 int seq = mPendingEventSeq+1;
2322 if (seq < 0) seq = 0;
2323 mPendingEventSeq = seq;
2324 mPendingEvents.put(seq, event);
2325 return sendDone ? seq : -seq;
2326 }
2327
2328 Object retrievePendingEvent(int seq) {
2329 if (seq < 0) seq = -seq;
2330 Object event = mPendingEvents.get(seq);
2331 if (event != null) {
2332 mPendingEvents.remove(seq);
2333 }
2334 return event;
2335 }
Romain Guy8506ab42009-06-11 17:35:47 -07002336
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002337 private void deliverKeyEvent(KeyEvent event, boolean sendDone) {
2338 // If mView is null, we just consume the key event because it doesn't
2339 // make sense to do anything else with it.
Romain Guy812ccbe2010-06-01 14:07:24 -07002340 boolean handled = mView == null || mView.dispatchKeyEventPreIme(event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002341 if (handled) {
2342 if (sendDone) {
2343 if (LOCAL_LOGV) Log.v(
2344 "ViewRoot", "Telling window manager key is finished");
2345 try {
2346 sWindowSession.finishKey(mWindow);
2347 } catch (RemoteException e) {
2348 }
2349 }
2350 return;
2351 }
2352 // If it is possible for this window to interact with the input
2353 // method window, then we want to first dispatch our key events
2354 // to the input method.
2355 if (mLastWasImTarget) {
2356 InputMethodManager imm = InputMethodManager.peekInstance();
2357 if (imm != null && mView != null) {
2358 int seq = enqueuePendingEvent(event, sendDone);
2359 if (DEBUG_IMF) Log.v(TAG, "Sending key event to IME: seq="
2360 + seq + " event=" + event);
2361 imm.dispatchKeyEvent(mView.getContext(), seq, event,
2362 mInputMethodCallback);
2363 return;
2364 }
2365 }
2366 deliverKeyEventToViewHierarchy(event, sendDone);
2367 }
2368
2369 void handleFinishedEvent(int seq, boolean handled) {
2370 final KeyEvent event = (KeyEvent)retrievePendingEvent(seq);
2371 if (DEBUG_IMF) Log.v(TAG, "IME finished event: seq=" + seq
2372 + " handled=" + handled + " event=" + event);
2373 if (event != null) {
2374 final boolean sendDone = seq >= 0;
2375 if (!handled) {
2376 deliverKeyEventToViewHierarchy(event, sendDone);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002377 } else if (sendDone) {
2378 if (LOCAL_LOGV) Log.v(
2379 "ViewRoot", "Telling window manager key is finished");
2380 try {
2381 sWindowSession.finishKey(mWindow);
2382 } catch (RemoteException e) {
2383 }
2384 } else {
2385 Log.w("ViewRoot", "handleFinishedEvent(seq=" + seq
2386 + " handled=" + handled + " ev=" + event
2387 + ") neither delivering nor finishing key");
2388 }
2389 }
2390 }
Romain Guy8506ab42009-06-11 17:35:47 -07002391
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002392 private void deliverKeyEventToViewHierarchy(KeyEvent event, boolean sendDone) {
2393 try {
2394 if (mView != null && mAdded) {
2395 final int action = event.getAction();
2396 boolean isDown = (action == KeyEvent.ACTION_DOWN);
2397
2398 if (checkForLeavingTouchModeAndConsume(event)) {
2399 return;
Romain Guy8506ab42009-06-11 17:35:47 -07002400 }
2401
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002402 if (Config.LOGV) {
2403 captureKeyLog("captureDispatchKeyEvent", event);
2404 }
2405 boolean keyHandled = mView.dispatchKeyEvent(event);
2406
2407 if (!keyHandled && isDown) {
2408 int direction = 0;
2409 switch (event.getKeyCode()) {
2410 case KeyEvent.KEYCODE_DPAD_LEFT:
2411 direction = View.FOCUS_LEFT;
2412 break;
2413 case KeyEvent.KEYCODE_DPAD_RIGHT:
2414 direction = View.FOCUS_RIGHT;
2415 break;
2416 case KeyEvent.KEYCODE_DPAD_UP:
2417 direction = View.FOCUS_UP;
2418 break;
2419 case KeyEvent.KEYCODE_DPAD_DOWN:
2420 direction = View.FOCUS_DOWN;
2421 break;
2422 }
2423
2424 if (direction != 0) {
2425
2426 View focused = mView != null ? mView.findFocus() : null;
2427 if (focused != null) {
2428 View v = focused.focusSearch(direction);
2429 boolean focusPassed = false;
2430 if (v != null && v != focused) {
2431 // do the math the get the interesting rect
2432 // of previous focused into the coord system of
2433 // newly focused view
2434 focused.getFocusedRect(mTempRect);
Dianne Hackborn1c6a8942010-03-23 16:34:20 -07002435 if (mView instanceof ViewGroup) {
2436 ((ViewGroup) mView).offsetDescendantRectToMyCoords(
2437 focused, mTempRect);
2438 ((ViewGroup) mView).offsetRectIntoDescendantCoords(
2439 v, mTempRect);
2440 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002441 focusPassed = v.requestFocus(direction, mTempRect);
2442 }
2443
2444 if (!focusPassed) {
2445 mView.dispatchUnhandledMove(focused, direction);
2446 } else {
2447 playSoundEffect(SoundEffectConstants.getContantForFocusDirection(direction));
2448 }
2449 }
2450 }
2451 }
2452 }
2453
2454 } finally {
2455 if (sendDone) {
2456 if (LOCAL_LOGV) Log.v(
2457 "ViewRoot", "Telling window manager key is finished");
2458 try {
2459 sWindowSession.finishKey(mWindow);
2460 } catch (RemoteException e) {
2461 }
2462 }
2463 // Let the exception fall through -- the looper will catch
2464 // it and take care of the bad app for us.
2465 }
2466 }
2467
2468 private AudioManager getAudioManager() {
2469 if (mView == null) {
2470 throw new IllegalStateException("getAudioManager called when there is no mView");
2471 }
2472 if (mAudioManager == null) {
2473 mAudioManager = (AudioManager) mView.getContext().getSystemService(Context.AUDIO_SERVICE);
2474 }
2475 return mAudioManager;
2476 }
2477
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002478 private int relayoutWindow(WindowManager.LayoutParams params, int viewVisibility,
2479 boolean insetsPending) throws RemoteException {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002480
2481 float appScale = mAttachInfo.mApplicationScale;
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002482 boolean restore = false;
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002483 if (params != null && mTranslator != null) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07002484 restore = true;
2485 params.backup();
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002486 mTranslator.translateWindowLayout(params);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002487 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002488 if (params != null) {
2489 if (DBG) Log.d(TAG, "WindowLayout in layoutWindow:" + params);
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002490 }
Dianne Hackborn694f79b2010-03-17 19:44:59 -07002491 mPendingConfiguration.seq = 0;
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002492 int relayoutResult = sWindowSession.relayout(
2493 mWindow, params,
Mitsuru Oshima61324e52009-07-21 15:40:36 -07002494 (int) (mView.mMeasuredWidth * appScale + 0.5f),
2495 (int) (mView.mMeasuredHeight * appScale + 0.5f),
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002496 viewVisibility, insetsPending, mWinFrame,
Dianne Hackborn694f79b2010-03-17 19:44:59 -07002497 mPendingContentInsets, mPendingVisibleInsets,
2498 mPendingConfiguration, mSurface);
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002499 if (restore) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07002500 params.restore();
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002501 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002502
2503 if (mTranslator != null) {
2504 mTranslator.translateRectInScreenToAppWinFrame(mWinFrame);
2505 mTranslator.translateRectInScreenToAppWindow(mPendingContentInsets);
2506 mTranslator.translateRectInScreenToAppWindow(mPendingVisibleInsets);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002507 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002508 return relayoutResult;
2509 }
Romain Guy8506ab42009-06-11 17:35:47 -07002510
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002511 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002512 * {@inheritDoc}
2513 */
2514 public void playSoundEffect(int effectId) {
2515 checkThread();
2516
Jean-Michel Trivi13b18fd2010-05-05 09:18:15 -07002517 try {
2518 final AudioManager audioManager = getAudioManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002519
Jean-Michel Trivi13b18fd2010-05-05 09:18:15 -07002520 switch (effectId) {
2521 case SoundEffectConstants.CLICK:
2522 audioManager.playSoundEffect(AudioManager.FX_KEY_CLICK);
2523 return;
2524 case SoundEffectConstants.NAVIGATION_DOWN:
2525 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_DOWN);
2526 return;
2527 case SoundEffectConstants.NAVIGATION_LEFT:
2528 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_LEFT);
2529 return;
2530 case SoundEffectConstants.NAVIGATION_RIGHT:
2531 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_RIGHT);
2532 return;
2533 case SoundEffectConstants.NAVIGATION_UP:
2534 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_UP);
2535 return;
2536 default:
2537 throw new IllegalArgumentException("unknown effect id " + effectId +
2538 " not defined in " + SoundEffectConstants.class.getCanonicalName());
2539 }
2540 } catch (IllegalStateException e) {
2541 // Exception thrown by getAudioManager() when mView is null
2542 Log.e(TAG, "FATAL EXCEPTION when attempting to play sound effect: " + e);
2543 e.printStackTrace();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002544 }
2545 }
2546
2547 /**
2548 * {@inheritDoc}
2549 */
2550 public boolean performHapticFeedback(int effectId, boolean always) {
2551 try {
2552 return sWindowSession.performHapticFeedback(mWindow, effectId, always);
2553 } catch (RemoteException e) {
2554 return false;
2555 }
2556 }
2557
2558 /**
2559 * {@inheritDoc}
2560 */
2561 public View focusSearch(View focused, int direction) {
2562 checkThread();
2563 if (!(mView instanceof ViewGroup)) {
2564 return null;
2565 }
2566 return FocusFinder.getInstance().findNextFocus((ViewGroup) mView, focused, direction);
2567 }
2568
2569 public void debug() {
2570 mView.debug();
2571 }
2572
2573 public void die(boolean immediate) {
Dianne Hackborn94d69142009-09-28 22:14:42 -07002574 if (immediate) {
2575 doDie();
2576 } else {
2577 sendEmptyMessage(DIE);
2578 }
2579 }
2580
2581 void doDie() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002582 checkThread();
Romain Guy812ccbe2010-06-01 14:07:24 -07002583 if (LOCAL_LOGV) Log.v("ViewRoot", "DIE in " + this + " of " + mSurface);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002584 synchronized (this) {
2585 if (mAdded && !mFirst) {
2586 int viewVisibility = mView.getVisibility();
2587 boolean viewVisibilityChanged = mViewVisibility != viewVisibility;
2588 if (mWindowAttributesChanged || viewVisibilityChanged) {
2589 // If layout params have been changed, first give them
2590 // to the window manager to make sure it has the correct
2591 // animation info.
2592 try {
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002593 if ((relayoutWindow(mWindowAttributes, viewVisibility, false)
2594 & WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002595 sWindowSession.finishDrawing(mWindow);
2596 }
2597 } catch (RemoteException e) {
2598 }
2599 }
2600
Dianne Hackborn0586a1b2009-09-06 21:08:27 -07002601 mSurface.release();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002602 }
2603 if (mAdded) {
2604 mAdded = false;
Dianne Hackborn94d69142009-09-28 22:14:42 -07002605 dispatchDetachedFromWindow();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002606 }
2607 }
2608 }
2609
2610 public void dispatchFinishedEvent(int seq, boolean handled) {
2611 Message msg = obtainMessage(FINISHED_EVENT);
2612 msg.arg1 = seq;
2613 msg.arg2 = handled ? 1 : 0;
2614 sendMessage(msg);
2615 }
Mitsuru Oshima3d914922009-05-13 22:29:15 -07002616
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002617 public void dispatchResized(int w, int h, Rect coveredInsets,
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002618 Rect visibleInsets, boolean reportDraw, Configuration newConfig) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002619 if (DEBUG_LAYOUT) Log.v(TAG, "Resizing " + this + ": w=" + w
2620 + " h=" + h + " coveredInsets=" + coveredInsets.toShortString()
2621 + " visibleInsets=" + visibleInsets.toShortString()
2622 + " reportDraw=" + reportDraw);
2623 Message msg = obtainMessage(reportDraw ? RESIZED_REPORT :RESIZED);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002624 if (mTranslator != null) {
2625 mTranslator.translateRectInScreenToAppWindow(coveredInsets);
2626 mTranslator.translateRectInScreenToAppWindow(visibleInsets);
2627 w *= mTranslator.applicationInvertedScale;
2628 h *= mTranslator.applicationInvertedScale;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002629 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07002630 msg.arg1 = w;
2631 msg.arg2 = h;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002632 ResizedInfo ri = new ResizedInfo();
2633 ri.coveredInsets = new Rect(coveredInsets);
2634 ri.visibleInsets = new Rect(visibleInsets);
2635 ri.newConfig = newConfig;
2636 msg.obj = ri;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002637 sendMessage(msg);
2638 }
2639
2640 public void dispatchKey(KeyEvent event) {
2641 if (event.getAction() == KeyEvent.ACTION_DOWN) {
2642 //noinspection ConstantConditions
2643 if (false && event.getKeyCode() == KeyEvent.KEYCODE_CAMERA) {
Romain Guy812ccbe2010-06-01 14:07:24 -07002644 if (DBG) Log.d("keydisp", "===================================================");
2645 if (DBG) Log.d("keydisp", "Focused view Hierarchy is:");
2646
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002647 debug();
2648
Romain Guy812ccbe2010-06-01 14:07:24 -07002649 if (DBG) Log.d("keydisp", "===================================================");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002650 }
2651 }
2652
2653 Message msg = obtainMessage(DISPATCH_KEY);
2654 msg.obj = event;
2655
2656 if (LOCAL_LOGV) Log.v(
2657 "ViewRoot", "sending key " + event + " to " + mView);
2658
2659 sendMessageAtTime(msg, event.getEventTime());
2660 }
2661
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07002662 public void dispatchPointer(MotionEvent event, long eventTime,
2663 boolean callWhenDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002664 Message msg = obtainMessage(DISPATCH_POINTER);
2665 msg.obj = event;
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07002666 msg.arg1 = callWhenDone ? 1 : 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002667 sendMessageAtTime(msg, eventTime);
2668 }
2669
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07002670 public void dispatchTrackball(MotionEvent event, long eventTime,
2671 boolean callWhenDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002672 Message msg = obtainMessage(DISPATCH_TRACKBALL);
2673 msg.obj = event;
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07002674 msg.arg1 = callWhenDone ? 1 : 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002675 sendMessageAtTime(msg, eventTime);
2676 }
2677
2678 public void dispatchAppVisibility(boolean visible) {
2679 Message msg = obtainMessage(DISPATCH_APP_VISIBILITY);
2680 msg.arg1 = visible ? 1 : 0;
2681 sendMessage(msg);
2682 }
2683
2684 public void dispatchGetNewSurface() {
2685 Message msg = obtainMessage(DISPATCH_GET_NEW_SURFACE);
2686 sendMessage(msg);
2687 }
2688
2689 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
2690 Message msg = Message.obtain();
2691 msg.what = WINDOW_FOCUS_CHANGED;
2692 msg.arg1 = hasFocus ? 1 : 0;
2693 msg.arg2 = inTouchMode ? 1 : 0;
2694 sendMessage(msg);
2695 }
2696
Dianne Hackbornffa42482009-09-23 22:20:11 -07002697 public void dispatchCloseSystemDialogs(String reason) {
2698 Message msg = Message.obtain();
2699 msg.what = CLOSE_SYSTEM_DIALOGS;
2700 msg.obj = reason;
2701 sendMessage(msg);
2702 }
2703
svetoslavganov75986cf2009-05-14 22:28:01 -07002704 /**
2705 * The window is getting focus so if there is anything focused/selected
2706 * send an {@link AccessibilityEvent} to announce that.
2707 */
2708 private void sendAccessibilityEvents() {
2709 if (!AccessibilityManager.getInstance(mView.getContext()).isEnabled()) {
2710 return;
2711 }
2712 mView.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
2713 View focusedView = mView.findFocus();
2714 if (focusedView != null && focusedView != mView) {
2715 focusedView.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
2716 }
2717 }
2718
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002719 public boolean showContextMenuForChild(View originalView) {
2720 return false;
2721 }
2722
2723 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 Projectba87e3e2009-03-13 13:04:22 -07002808 static class EventCompletion extends Handler {
2809 final IWindow mWindow;
2810 final KeyEvent mKeyEvent;
2811 final boolean mIsPointer;
2812 final MotionEvent mMotionEvent;
Romain Guy8506ab42009-06-11 17:35:47 -07002813
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002814 EventCompletion(Looper looper, IWindow window, KeyEvent key,
2815 boolean isPointer, MotionEvent motion) {
2816 super(looper);
2817 mWindow = window;
2818 mKeyEvent = key;
2819 mIsPointer = isPointer;
2820 mMotionEvent = motion;
2821 sendEmptyMessage(0);
2822 }
Romain Guy8506ab42009-06-11 17:35:47 -07002823
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002824 @Override
2825 public void handleMessage(Message msg) {
2826 if (mKeyEvent != null) {
2827 try {
2828 sWindowSession.finishKey(mWindow);
2829 } catch (RemoteException e) {
2830 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07002831 } else if (mIsPointer) {
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002832 boolean didFinish;
2833 MotionEvent event = mMotionEvent;
2834 if (event == null) {
2835 try {
2836 event = sWindowSession.getPendingPointerMove(mWindow);
2837 } catch (RemoteException e) {
2838 }
2839 didFinish = true;
2840 } else {
2841 didFinish = event.getAction() == MotionEvent.ACTION_OUTSIDE;
2842 }
2843 if (!didFinish) {
2844 try {
2845 sWindowSession.finishKey(mWindow);
2846 } catch (RemoteException e) {
2847 }
2848 }
2849 } else {
2850 MotionEvent event = mMotionEvent;
2851 if (event == null) {
2852 try {
2853 event = sWindowSession.getPendingTrackballMove(mWindow);
2854 } catch (RemoteException e) {
2855 }
2856 } else {
2857 try {
2858 sWindowSession.finishKey(mWindow);
2859 } catch (RemoteException e) {
2860 }
2861 }
2862 }
2863 }
2864 }
Romain Guy8506ab42009-06-11 17:35:47 -07002865
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002866 static class W extends IWindow.Stub {
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002867 private final WeakReference<ViewRoot> mViewRoot;
2868 private final Looper mMainLooper;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002869
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002870 public W(ViewRoot viewRoot, Context context) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002871 mViewRoot = new WeakReference<ViewRoot>(viewRoot);
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002872 mMainLooper = context.getMainLooper();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002873 }
2874
2875 public void resized(int w, int h, Rect coveredInsets,
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002876 Rect visibleInsets, boolean reportDraw, Configuration newConfig) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002877 final ViewRoot viewRoot = mViewRoot.get();
2878 if (viewRoot != null) {
2879 viewRoot.dispatchResized(w, h, coveredInsets,
Dianne Hackborne36d6e22010-02-17 19:46:25 -08002880 visibleInsets, reportDraw, newConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002881 }
2882 }
2883
2884 public void dispatchKey(KeyEvent event) {
2885 final ViewRoot viewRoot = mViewRoot.get();
2886 if (viewRoot != null) {
2887 viewRoot.dispatchKey(event);
2888 } else {
2889 Log.w("ViewRoot.W", "Key event " + event + " but no ViewRoot available!");
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002890 new EventCompletion(mMainLooper, this, event, false, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002891 }
2892 }
2893
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07002894 public void dispatchPointer(MotionEvent event, long eventTime,
2895 boolean callWhenDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002896 final ViewRoot viewRoot = mViewRoot.get();
Michael Chan53071d62009-05-13 17:29:48 -07002897 if (viewRoot != null) {
2898 if (MEASURE_LATENCY) {
2899 // Note: eventTime is in milliseconds
2900 ViewRoot.lt.sample("* ViewRoot b4 dispatchPtr", System.nanoTime() - eventTime * 1000000);
2901 }
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07002902 viewRoot.dispatchPointer(event, eventTime, callWhenDone);
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002903 } else {
2904 new EventCompletion(mMainLooper, this, null, true, event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002905 }
2906 }
2907
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07002908 public void dispatchTrackball(MotionEvent event, long eventTime,
2909 boolean callWhenDone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002910 final ViewRoot viewRoot = mViewRoot.get();
2911 if (viewRoot != null) {
Dianne Hackborn8df8b2b2009-08-17 15:15:18 -07002912 viewRoot.dispatchTrackball(event, eventTime, callWhenDone);
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07002913 } else {
2914 new EventCompletion(mMainLooper, this, null, false, event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002915 }
2916 }
2917
2918 public void dispatchAppVisibility(boolean visible) {
2919 final ViewRoot viewRoot = mViewRoot.get();
2920 if (viewRoot != null) {
2921 viewRoot.dispatchAppVisibility(visible);
2922 }
2923 }
2924
2925 public void dispatchGetNewSurface() {
2926 final ViewRoot viewRoot = mViewRoot.get();
2927 if (viewRoot != null) {
2928 viewRoot.dispatchGetNewSurface();
2929 }
2930 }
2931
2932 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
2933 final ViewRoot viewRoot = mViewRoot.get();
2934 if (viewRoot != null) {
2935 viewRoot.windowFocusChanged(hasFocus, inTouchMode);
2936 }
2937 }
2938
2939 private static int checkCallingPermission(String permission) {
2940 if (!Process.supportsProcesses()) {
2941 return PackageManager.PERMISSION_GRANTED;
2942 }
2943
2944 try {
2945 return ActivityManagerNative.getDefault().checkPermission(
2946 permission, Binder.getCallingPid(), Binder.getCallingUid());
2947 } catch (RemoteException e) {
2948 return PackageManager.PERMISSION_DENIED;
2949 }
2950 }
2951
2952 public void executeCommand(String command, String parameters, ParcelFileDescriptor out) {
2953 final ViewRoot viewRoot = mViewRoot.get();
2954 if (viewRoot != null) {
2955 final View view = viewRoot.mView;
2956 if (view != null) {
2957 if (checkCallingPermission(Manifest.permission.DUMP) !=
2958 PackageManager.PERMISSION_GRANTED) {
2959 throw new SecurityException("Insufficient permissions to invoke"
2960 + " executeCommand() from pid=" + Binder.getCallingPid()
2961 + ", uid=" + Binder.getCallingUid());
2962 }
2963
2964 OutputStream clientStream = null;
2965 try {
2966 clientStream = new ParcelFileDescriptor.AutoCloseOutputStream(out);
2967 ViewDebug.dispatchCommand(view, command, parameters, clientStream);
2968 } catch (IOException e) {
2969 e.printStackTrace();
2970 } finally {
2971 if (clientStream != null) {
2972 try {
2973 clientStream.close();
2974 } catch (IOException e) {
2975 e.printStackTrace();
2976 }
2977 }
2978 }
2979 }
2980 }
2981 }
Dianne Hackborn72c82ab2009-08-11 21:13:54 -07002982
Dianne Hackbornffa42482009-09-23 22:20:11 -07002983 public void closeSystemDialogs(String reason) {
2984 final ViewRoot viewRoot = mViewRoot.get();
2985 if (viewRoot != null) {
2986 viewRoot.dispatchCloseSystemDialogs(reason);
2987 }
2988 }
2989
Marco Nelissenbf6956b2009-11-09 15:21:13 -08002990 public void dispatchWallpaperOffsets(float x, float y, float xStep, float yStep,
2991 boolean sync) {
Dianne Hackborn19382ac2009-09-11 21:13:37 -07002992 if (sync) {
2993 try {
2994 sWindowSession.wallpaperOffsetsComplete(asBinder());
2995 } catch (RemoteException e) {
2996 }
2997 }
Dianne Hackborn72c82ab2009-08-11 21:13:54 -07002998 }
Dianne Hackborn75804932009-10-20 20:15:20 -07002999
3000 public void dispatchWallpaperCommand(String action, int x, int y,
3001 int z, Bundle extras, boolean sync) {
3002 if (sync) {
3003 try {
3004 sWindowSession.wallpaperCommandComplete(asBinder(), null);
3005 } catch (RemoteException e) {
3006 }
3007 }
3008 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003009 }
3010
3011 /**
3012 * Maintains state information for a single trackball axis, generating
3013 * discrete (DPAD) movements based on raw trackball motion.
3014 */
3015 static final class TrackballAxis {
3016 /**
3017 * The maximum amount of acceleration we will apply.
3018 */
3019 static final float MAX_ACCELERATION = 20;
Romain Guy8506ab42009-06-11 17:35:47 -07003020
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003021 /**
3022 * The maximum amount of time (in milliseconds) between events in order
3023 * for us to consider the user to be doing fast trackball movements,
3024 * and thus apply an acceleration.
3025 */
3026 static final long FAST_MOVE_TIME = 150;
Romain Guy8506ab42009-06-11 17:35:47 -07003027
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003028 /**
3029 * Scaling factor to the time (in milliseconds) between events to how
3030 * much to multiple/divide the current acceleration. When movement
3031 * is < FAST_MOVE_TIME this multiplies the acceleration; when >
3032 * FAST_MOVE_TIME it divides it.
3033 */
3034 static final float ACCEL_MOVE_SCALING_FACTOR = (1.0f/40);
Romain Guy8506ab42009-06-11 17:35:47 -07003035
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003036 float position;
3037 float absPosition;
3038 float acceleration = 1;
3039 long lastMoveTime = 0;
3040 int step;
3041 int dir;
3042 int nonAccelMovement;
3043
3044 void reset(int _step) {
3045 position = 0;
3046 acceleration = 1;
3047 lastMoveTime = 0;
3048 step = _step;
3049 dir = 0;
3050 }
3051
3052 /**
3053 * Add trackball movement into the state. If the direction of movement
3054 * has been reversed, the state is reset before adding the
3055 * movement (so that you don't have to compensate for any previously
3056 * collected movement before see the result of the movement in the
3057 * new direction).
3058 *
3059 * @return Returns the absolute value of the amount of movement
3060 * collected so far.
3061 */
3062 float collect(float off, long time, String axis) {
3063 long normTime;
3064 if (off > 0) {
3065 normTime = (long)(off * FAST_MOVE_TIME);
3066 if (dir < 0) {
3067 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to positive!");
3068 position = 0;
3069 step = 0;
3070 acceleration = 1;
3071 lastMoveTime = 0;
3072 }
3073 dir = 1;
3074 } else if (off < 0) {
3075 normTime = (long)((-off) * FAST_MOVE_TIME);
3076 if (dir > 0) {
3077 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to negative!");
3078 position = 0;
3079 step = 0;
3080 acceleration = 1;
3081 lastMoveTime = 0;
3082 }
3083 dir = -1;
3084 } else {
3085 normTime = 0;
3086 }
Romain Guy8506ab42009-06-11 17:35:47 -07003087
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003088 // The number of milliseconds between each movement that is
3089 // considered "normal" and will not result in any acceleration
3090 // or deceleration, scaled by the offset we have here.
3091 if (normTime > 0) {
3092 long delta = time - lastMoveTime;
3093 lastMoveTime = time;
3094 float acc = acceleration;
3095 if (delta < normTime) {
3096 // The user is scrolling rapidly, so increase acceleration.
3097 float scale = (normTime-delta) * ACCEL_MOVE_SCALING_FACTOR;
3098 if (scale > 1) acc *= scale;
3099 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " accelerate: off="
3100 + off + " normTime=" + normTime + " delta=" + delta
3101 + " scale=" + scale + " acc=" + acc);
3102 acceleration = acc < MAX_ACCELERATION ? acc : MAX_ACCELERATION;
3103 } else {
3104 // The user is scrolling slowly, so decrease acceleration.
3105 float scale = (delta-normTime) * ACCEL_MOVE_SCALING_FACTOR;
3106 if (scale > 1) acc /= scale;
3107 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " deccelerate: off="
3108 + off + " normTime=" + normTime + " delta=" + delta
3109 + " scale=" + scale + " acc=" + acc);
3110 acceleration = acc > 1 ? acc : 1;
3111 }
3112 }
3113 position += off;
3114 return (absPosition = Math.abs(position));
3115 }
3116
3117 /**
3118 * Generate the number of discrete movement events appropriate for
3119 * the currently collected trackball movement.
3120 *
3121 * @param precision The minimum movement required to generate the
3122 * first discrete movement.
3123 *
3124 * @return Returns the number of discrete movements, either positive
3125 * or negative, or 0 if there is not enough trackball movement yet
3126 * for a discrete movement.
3127 */
3128 int generate(float precision) {
3129 int movement = 0;
3130 nonAccelMovement = 0;
3131 do {
3132 final int dir = position >= 0 ? 1 : -1;
3133 switch (step) {
3134 // If we are going to execute the first step, then we want
3135 // to do this as soon as possible instead of waiting for
3136 // a full movement, in order to make things look responsive.
3137 case 0:
3138 if (absPosition < precision) {
3139 return movement;
3140 }
3141 movement += dir;
3142 nonAccelMovement += dir;
3143 step = 1;
3144 break;
3145 // If we have generated the first movement, then we need
3146 // to wait for the second complete trackball motion before
3147 // generating the second discrete movement.
3148 case 1:
3149 if (absPosition < 2) {
3150 return movement;
3151 }
3152 movement += dir;
3153 nonAccelMovement += dir;
3154 position += dir > 0 ? -2 : 2;
3155 absPosition = Math.abs(position);
3156 step = 2;
3157 break;
3158 // After the first two, we generate discrete movements
3159 // consistently with the trackball, applying an acceleration
3160 // if the trackball is moving quickly. This is a simple
3161 // acceleration on top of what we already compute based
3162 // on how quickly the wheel is being turned, to apply
3163 // a longer increasing acceleration to continuous movement
3164 // in one direction.
3165 default:
3166 if (absPosition < 1) {
3167 return movement;
3168 }
3169 movement += dir;
3170 position += dir >= 0 ? -1 : 1;
3171 absPosition = Math.abs(position);
3172 float acc = acceleration;
3173 acc *= 1.1f;
3174 acceleration = acc < MAX_ACCELERATION ? acc : acceleration;
3175 break;
3176 }
3177 } while (true);
3178 }
3179 }
3180
3181 public static final class CalledFromWrongThreadException extends AndroidRuntimeException {
3182 public CalledFromWrongThreadException(String msg) {
3183 super(msg);
3184 }
3185 }
3186
3187 private SurfaceHolder mHolder = new SurfaceHolder() {
3188 // we only need a SurfaceHolder for opengl. it would be nice
3189 // to implement everything else though, especially the callback
3190 // support (opengl doesn't make use of it right now, but eventually
3191 // will).
3192 public Surface getSurface() {
3193 return mSurface;
3194 }
3195
3196 public boolean isCreating() {
3197 return false;
3198 }
3199
3200 public void addCallback(Callback callback) {
3201 }
3202
3203 public void removeCallback(Callback callback) {
3204 }
3205
3206 public void setFixedSize(int width, int height) {
3207 }
3208
3209 public void setSizeFromLayout() {
3210 }
3211
3212 public void setFormat(int format) {
3213 }
3214
3215 public void setType(int type) {
3216 }
3217
3218 public void setKeepScreenOn(boolean screenOn) {
3219 }
3220
3221 public Canvas lockCanvas() {
3222 return null;
3223 }
3224
3225 public Canvas lockCanvas(Rect dirty) {
3226 return null;
3227 }
3228
3229 public void unlockCanvasAndPost(Canvas canvas) {
3230 }
3231 public Rect getSurfaceFrame() {
3232 return null;
3233 }
3234 };
3235
3236 static RunQueue getRunQueue() {
3237 RunQueue rq = sRunQueues.get();
3238 if (rq != null) {
3239 return rq;
3240 }
3241 rq = new RunQueue();
3242 sRunQueues.set(rq);
3243 return rq;
3244 }
Romain Guy8506ab42009-06-11 17:35:47 -07003245
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003246 /**
3247 * @hide
3248 */
3249 static final class RunQueue {
3250 private final ArrayList<HandlerAction> mActions = new ArrayList<HandlerAction>();
3251
3252 void post(Runnable action) {
3253 postDelayed(action, 0);
3254 }
3255
3256 void postDelayed(Runnable action, long delayMillis) {
3257 HandlerAction handlerAction = new HandlerAction();
3258 handlerAction.action = action;
3259 handlerAction.delay = delayMillis;
3260
3261 synchronized (mActions) {
3262 mActions.add(handlerAction);
3263 }
3264 }
3265
3266 void removeCallbacks(Runnable action) {
3267 final HandlerAction handlerAction = new HandlerAction();
3268 handlerAction.action = action;
3269
3270 synchronized (mActions) {
3271 final ArrayList<HandlerAction> actions = mActions;
3272
3273 while (actions.remove(handlerAction)) {
3274 // Keep going
3275 }
3276 }
3277 }
3278
3279 void executeActions(Handler handler) {
3280 synchronized (mActions) {
3281 final ArrayList<HandlerAction> actions = mActions;
3282 final int count = actions.size();
3283
3284 for (int i = 0; i < count; i++) {
3285 final HandlerAction handlerAction = actions.get(i);
3286 handler.postDelayed(handlerAction.action, handlerAction.delay);
3287 }
3288
Romain Guy15df6702009-08-17 20:17:30 -07003289 actions.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003290 }
3291 }
3292
3293 private static class HandlerAction {
3294 Runnable action;
3295 long delay;
3296
3297 @Override
3298 public boolean equals(Object o) {
3299 if (this == o) return true;
3300 if (o == null || getClass() != o.getClass()) return false;
3301
3302 HandlerAction that = (HandlerAction) o;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003303 return !(action != null ? !action.equals(that.action) : that.action != null);
3304
3305 }
3306
3307 @Override
3308 public int hashCode() {
3309 int result = action != null ? action.hashCode() : 0;
3310 result = 31 * result + (int) (delay ^ (delay >>> 32));
3311 return result;
3312 }
3313 }
3314 }
3315
Romain Guy812ccbe2010-06-01 14:07:24 -07003316 class HardwareRenderer {
3317 private EGL10 mEgl;
3318 private EGLDisplay mEglDisplay;
3319 private EGLContext mEglContext;
3320 private EGLSurface mEglSurface;
3321 private GL11 mGL;
3322
3323 private Canvas mGlCanvas;
3324
3325 boolean mEnabled;
3326 boolean mRequested = true;
3327
3328 private void initializeGL() {
3329 initializeGLInner();
3330 int err = mEgl.eglGetError();
3331 if (err != EGL10.EGL_SUCCESS) {
3332 destroyGL();
3333 mRequested = false;
3334 }
3335 }
3336
3337 private void initializeGLInner() {
3338 final EGL10 egl = (EGL10) EGLContext.getEGL();
3339 mEgl = egl;
3340
3341 final EGLDisplay eglDisplay = egl.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY);
3342 mEglDisplay = eglDisplay;
3343
3344 int[] version = new int[2];
3345 egl.eglInitialize(eglDisplay, version);
3346
3347 final int[] configSpec = {
3348 EGL10.EGL_RED_SIZE, 8,
3349 EGL10.EGL_GREEN_SIZE, 8,
3350 EGL10.EGL_BLUE_SIZE, 8,
3351 EGL10.EGL_DEPTH_SIZE, 0,
3352 EGL10.EGL_NONE
3353 };
3354 final EGLConfig[] configs = new EGLConfig[1];
3355 final int[] numConfig = new int[1];
3356 egl.eglChooseConfig(eglDisplay, configSpec, configs, 1, numConfig);
3357 final EGLConfig config = configs[0];
3358
3359 /*
3360 * Create an OpenGL ES context. This must be done only once, an
3361 * OpenGL context is a somewhat heavy object.
3362 */
3363 final EGLContext context = egl.eglCreateContext(eglDisplay, config,
3364 EGL10.EGL_NO_CONTEXT, null);
3365 mEglContext = context;
3366
3367 /*
3368 * Create an EGL surface we can render into.
3369 */
3370 EGLSurface surface = egl.eglCreateWindowSurface(eglDisplay, config, mHolder, null);
3371 mEglSurface = surface;
3372
3373 /*
3374 * Before we can issue GL commands, we need to make sure
3375 * the context is current and bound to a surface.
3376 */
3377 egl.eglMakeCurrent(eglDisplay, surface, surface, context);
3378
3379 /*
3380 * Get to the appropriate GL interface.
3381 * This is simply done by casting the GL context to either
3382 * GL10 or GL11.
3383 */
3384 final GL11 gl = (GL11) context.getGL();
3385 mGL = gl;
3386 mGlCanvas = new Canvas(gl);
3387 mEnabled = true;
3388 }
3389
3390 void destroyGL() {
3391 if (!mEnabled) return;
3392
3393 // inform skia that the context is gone
3394 nativeAbandonGlCaches();
3395
3396 mEgl.eglMakeCurrent(mEglDisplay, EGL10.EGL_NO_SURFACE,
3397 EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_CONTEXT);
3398 mEgl.eglDestroyContext(mEglDisplay, mEglContext);
3399 mEgl.eglDestroySurface(mEglDisplay, mEglSurface);
3400 mEgl.eglTerminate(mEglDisplay);
3401
3402 mEglContext = null;
3403 mEglSurface = null;
3404 mEglDisplay = null;
3405 mEgl = null;
3406 mGlCanvas = null;
3407 mGL = null;
3408
3409 mEnabled = false;
3410 }
3411
3412 private void checkErrors() {
3413 if (mEnabled) {
3414 int err = mEgl.eglGetError();
3415 if (err != EGL10.EGL_SUCCESS) {
3416 // something bad has happened revert to
3417 // normal rendering.
3418 destroyGL();
3419 if (err != EGL11.EGL_CONTEXT_LOST) {
3420 // we'll try again if it was context lost
3421 mRequested = false;
3422 }
3423 }
3424 }
3425 }
3426
3427 boolean initialize() {
3428 if (mRequested && !mEnabled) {
3429 initializeGL();
3430 return mGlCanvas != null;
3431 }
3432 return false;
3433 }
3434
3435 void setup(float appScale) {
3436 mGlCanvas.setViewport((int) (mWidth * appScale + 0.5f),
3437 (int) (mHeight * appScale + 0.5f));
3438 }
3439
3440 void draw(int yoff, boolean scalingRequired) {
3441 Canvas canvas = mGlCanvas;
3442 if (mGL != null && canvas != null) {
3443 mGL.glDisable(GL_SCISSOR_TEST);
3444 mGL.glClearColor(0, 0, 0, 0);
3445 mGL.glClear(GL_COLOR_BUFFER_BIT);
3446 mGL.glEnable(GL_SCISSOR_TEST);
3447
3448 mAttachInfo.mDrawingTime = SystemClock.uptimeMillis();
3449 mAttachInfo.mIgnoreDirtyState = true;
3450 mView.mPrivateFlags |= View.DRAWN;
3451
3452 int saveCount = canvas.save(Canvas.MATRIX_SAVE_FLAG);
3453 try {
3454 canvas.translate(0, -yoff);
3455 if (mTranslator != null) {
3456 mTranslator.translateCanvas(canvas);
3457 }
3458 canvas.setScreenDensity(scalingRequired ?
3459 DisplayMetrics.DENSITY_DEVICE : 0);
3460
3461 mView.draw(canvas);
3462
3463 } finally {
3464 canvas.restoreToCount(saveCount);
3465 }
3466
3467 mAttachInfo.mIgnoreDirtyState = false;
3468
3469 mEgl.eglSwapBuffers(mEglDisplay, mEglSurface);
3470 checkErrors();
3471 }
3472 }
3473
3474 void initializeAndSetup() {
3475 if (mRequested) {
3476 checkErrors();
3477 // we lost the gl context, so recreate it.
3478 if (mRequested && !mEnabled) {
3479 initializeGL();
3480 if (mGlCanvas != null) {
3481 float appScale = mAttachInfo.mApplicationScale;
3482 mGlCanvas.setViewport((int) (mWidth * appScale + 0.5f),
3483 (int) (mHeight * appScale + 0.5f));
3484 }
3485 }
3486 }
3487 }
3488 }
3489
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003490 private static native void nativeShowFPS(Canvas canvas, int durationMillis);
3491
3492 // inform skia to just abandon its texture cache IDs
3493 // doesn't call glDeleteTextures
3494 private static native void nativeAbandonGlCaches();
3495}