blob: 4561e1aec3d876da5d273143e99979578840dbb2 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 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 com.android.server;
18
19import static android.os.LocalPowerManager.CHEEK_EVENT;
20import static android.os.LocalPowerManager.OTHER_EVENT;
21import static android.os.LocalPowerManager.TOUCH_EVENT;
Joe Onoratoe68ffcb2009-03-24 19:11:13 -070022import static android.os.LocalPowerManager.LONG_TOUCH_EVENT;
23import static android.os.LocalPowerManager.TOUCH_UP_EVENT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080024import static android.view.WindowManager.LayoutParams.FIRST_APPLICATION_WINDOW;
25import static android.view.WindowManager.LayoutParams.FIRST_SUB_WINDOW;
26import static android.view.WindowManager.LayoutParams.FLAG_BLUR_BEHIND;
27import static android.view.WindowManager.LayoutParams.FLAG_DIM_BEHIND;
28import static android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
29import static android.view.WindowManager.LayoutParams.FLAG_SYSTEM_ERROR;
30import static android.view.WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
31import static android.view.WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM;
32import static android.view.WindowManager.LayoutParams.LAST_APPLICATION_WINDOW;
33import static android.view.WindowManager.LayoutParams.LAST_SUB_WINDOW;
34import static android.view.WindowManager.LayoutParams.MEMORY_TYPE_GPU;
35import static android.view.WindowManager.LayoutParams.MEMORY_TYPE_HARDWARE;
36import static android.view.WindowManager.LayoutParams.MEMORY_TYPE_PUSH_BUFFERS;
37import static android.view.WindowManager.LayoutParams.TYPE_APPLICATION_STARTING;
38import static android.view.WindowManager.LayoutParams.TYPE_BASE_APPLICATION;
39import static android.view.WindowManager.LayoutParams.TYPE_INPUT_METHOD;
40import static android.view.WindowManager.LayoutParams.TYPE_INPUT_METHOD_DIALOG;
41
42import com.android.internal.app.IBatteryStats;
43import com.android.internal.policy.PolicyManager;
44import com.android.internal.view.IInputContext;
45import com.android.internal.view.IInputMethodClient;
46import com.android.internal.view.IInputMethodManager;
47import com.android.server.KeyInputQueue.QueuedEvent;
48import com.android.server.am.BatteryStatsService;
49
50import android.Manifest;
51import android.app.ActivityManagerNative;
52import android.app.IActivityManager;
53import android.content.Context;
54import android.content.pm.ActivityInfo;
55import android.content.pm.PackageManager;
56import android.content.res.Configuration;
57import android.graphics.Matrix;
58import android.graphics.PixelFormat;
59import android.graphics.Rect;
60import android.graphics.Region;
61import android.os.BatteryStats;
62import android.os.Binder;
63import android.os.Debug;
64import android.os.Handler;
65import android.os.IBinder;
Michael Chan53071d62009-05-13 17:29:48 -070066import android.os.LatencyTimer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080067import android.os.LocalPowerManager;
68import android.os.Looper;
69import android.os.Message;
70import android.os.Parcel;
71import android.os.ParcelFileDescriptor;
72import android.os.Power;
73import android.os.PowerManager;
74import android.os.Process;
75import android.os.RemoteException;
76import android.os.ServiceManager;
77import android.os.SystemClock;
78import android.os.SystemProperties;
79import android.os.TokenWatcher;
80import android.provider.Settings;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080081import android.util.EventLog;
82import android.util.Log;
83import android.util.SparseIntArray;
84import android.view.Display;
85import android.view.Gravity;
86import android.view.IApplicationToken;
87import android.view.IOnKeyguardExitResult;
88import android.view.IRotationWatcher;
89import android.view.IWindow;
90import android.view.IWindowManager;
91import android.view.IWindowSession;
92import android.view.KeyEvent;
93import android.view.MotionEvent;
94import android.view.RawInputEvent;
95import android.view.Surface;
96import android.view.SurfaceSession;
97import android.view.View;
98import android.view.ViewTreeObserver;
99import android.view.WindowManager;
100import android.view.WindowManagerImpl;
101import android.view.WindowManagerPolicy;
102import android.view.WindowManager.LayoutParams;
103import android.view.animation.Animation;
104import android.view.animation.AnimationUtils;
105import android.view.animation.Transformation;
106
107import java.io.BufferedWriter;
108import java.io.File;
109import java.io.FileDescriptor;
110import java.io.IOException;
111import java.io.OutputStream;
112import java.io.OutputStreamWriter;
113import java.io.PrintWriter;
114import java.io.StringWriter;
115import java.net.Socket;
116import java.util.ArrayList;
117import java.util.HashMap;
118import java.util.HashSet;
119import java.util.Iterator;
120import java.util.List;
121
122/** {@hide} */
123public class WindowManagerService extends IWindowManager.Stub implements Watchdog.Monitor {
124 static final String TAG = "WindowManager";
125 static final boolean DEBUG = false;
126 static final boolean DEBUG_FOCUS = false;
127 static final boolean DEBUG_ANIM = false;
128 static final boolean DEBUG_LAYERS = false;
129 static final boolean DEBUG_INPUT = false;
130 static final boolean DEBUG_INPUT_METHOD = false;
131 static final boolean DEBUG_VISIBILITY = false;
132 static final boolean DEBUG_ORIENTATION = false;
133 static final boolean DEBUG_APP_TRANSITIONS = false;
134 static final boolean DEBUG_STARTING_WINDOW = false;
135 static final boolean DEBUG_REORDER = false;
136 static final boolean SHOW_TRANSACTIONS = false;
Michael Chan53071d62009-05-13 17:29:48 -0700137 static final boolean MEASURE_LATENCY = false;
138 static private LatencyTimer lt;
139
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800140 static final boolean PROFILE_ORIENTATION = false;
141 static final boolean BLUR = true;
Dave Bortcfe65242009-04-09 14:51:04 -0700142 static final boolean localLOGV = DEBUG;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800143
144 static final int LOG_WM_NO_SURFACE_MEMORY = 31000;
145
146 /** How long to wait for first key repeat, in milliseconds */
147 static final int KEY_REPEAT_FIRST_DELAY = 750;
148
149 /** How long to wait for subsequent key repeats, in milliseconds */
150 static final int KEY_REPEAT_DELAY = 50;
151
152 /** How much to multiply the policy's type layer, to reserve room
153 * for multiple windows of the same type and Z-ordering adjustment
154 * with TYPE_LAYER_OFFSET. */
155 static final int TYPE_LAYER_MULTIPLIER = 10000;
156
157 /** Offset from TYPE_LAYER_MULTIPLIER for moving a group of windows above
158 * or below others in the same layer. */
159 static final int TYPE_LAYER_OFFSET = 1000;
160
161 /** How much to increment the layer for each window, to reserve room
162 * for effect surfaces between them.
163 */
164 static final int WINDOW_LAYER_MULTIPLIER = 5;
165
166 /** The maximum length we will accept for a loaded animation duration:
167 * this is 10 seconds.
168 */
169 static final int MAX_ANIMATION_DURATION = 10*1000;
170
171 /** Amount of time (in milliseconds) to animate the dim surface from one
172 * value to another, when no window animation is driving it.
173 */
174 static final int DEFAULT_DIM_DURATION = 200;
175
176 /** Adjustment to time to perform a dim, to make it more dramatic.
177 */
178 static final int DIM_DURATION_MULTIPLIER = 6;
179
180 static final int UPDATE_FOCUS_NORMAL = 0;
181 static final int UPDATE_FOCUS_WILL_ASSIGN_LAYERS = 1;
182 static final int UPDATE_FOCUS_PLACING_SURFACES = 2;
183 static final int UPDATE_FOCUS_WILL_PLACE_SURFACES = 3;
184
Michael Chane96440f2009-05-06 10:27:36 -0700185 /** The minimum time between dispatching touch events. */
186 int mMinWaitTimeBetweenTouchEvents = 1000 / 35;
187
188 // Last touch event time
189 long mLastTouchEventTime = 0;
190
191 // Last touch event type
192 int mLastTouchEventType = OTHER_EVENT;
193
194 // Time to wait before calling useractivity again. This saves CPU usage
195 // when we get a flood of touch events.
196 static final int MIN_TIME_BETWEEN_USERACTIVITIES = 1000;
197
198 // Last time we call user activity
199 long mLastUserActivityCallTime = 0;
200
201 // Last time we updated battery stats
202 long mLastBatteryStatsCallTime = 0;
203
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800204 private static final String SYSTEM_SECURE = "ro.secure";
205
206 /**
207 * Condition waited on by {@link #reenableKeyguard} to know the call to
208 * the window policy has finished.
209 */
210 private boolean mWaitingUntilKeyguardReenabled = false;
211
212
213 final TokenWatcher mKeyguardDisabled = new TokenWatcher(
214 new Handler(), "WindowManagerService.mKeyguardDisabled") {
215 public void acquired() {
216 mPolicy.enableKeyguard(false);
217 }
218 public void released() {
219 synchronized (mKeyguardDisabled) {
220 mPolicy.enableKeyguard(true);
221 mWaitingUntilKeyguardReenabled = false;
222 mKeyguardDisabled.notifyAll();
223 }
224 }
225 };
226
227 final Context mContext;
228
229 final boolean mHaveInputMethods;
230
231 final boolean mLimitedAlphaCompositing;
232
233 final WindowManagerPolicy mPolicy = PolicyManager.makeNewWindowManager();
234
235 final IActivityManager mActivityManager;
236
237 final IBatteryStats mBatteryStats;
238
239 /**
240 * All currently active sessions with clients.
241 */
242 final HashSet<Session> mSessions = new HashSet<Session>();
243
244 /**
245 * Mapping from an IWindow IBinder to the server's Window object.
246 * This is also used as the lock for all of our state.
247 */
248 final HashMap<IBinder, WindowState> mWindowMap = new HashMap<IBinder, WindowState>();
249
250 /**
251 * Mapping from a token IBinder to a WindowToken object.
252 */
253 final HashMap<IBinder, WindowToken> mTokenMap =
254 new HashMap<IBinder, WindowToken>();
255
256 /**
257 * The same tokens as mTokenMap, stored in a list for efficient iteration
258 * over them.
259 */
260 final ArrayList<WindowToken> mTokenList = new ArrayList<WindowToken>();
261
262 /**
263 * Window tokens that are in the process of exiting, but still
264 * on screen for animations.
265 */
266 final ArrayList<WindowToken> mExitingTokens = new ArrayList<WindowToken>();
267
268 /**
269 * Z-ordered (bottom-most first) list of all application tokens, for
270 * controlling the ordering of windows in different applications. This
271 * contains WindowToken objects.
272 */
273 final ArrayList<AppWindowToken> mAppTokens = new ArrayList<AppWindowToken>();
274
275 /**
276 * Application tokens that are in the process of exiting, but still
277 * on screen for animations.
278 */
279 final ArrayList<AppWindowToken> mExitingAppTokens = new ArrayList<AppWindowToken>();
280
281 /**
282 * List of window tokens that have finished starting their application,
283 * and now need to have the policy remove their windows.
284 */
285 final ArrayList<AppWindowToken> mFinishedStarting = new ArrayList<AppWindowToken>();
286
287 /**
288 * Z-ordered (bottom-most first) list of all Window objects.
289 */
290 final ArrayList mWindows = new ArrayList();
291
292 /**
293 * Windows that are being resized. Used so we can tell the client about
294 * the resize after closing the transaction in which we resized the
295 * underlying surface.
296 */
297 final ArrayList<WindowState> mResizingWindows = new ArrayList<WindowState>();
298
299 /**
300 * Windows whose animations have ended and now must be removed.
301 */
302 final ArrayList<WindowState> mPendingRemove = new ArrayList<WindowState>();
303
304 /**
305 * Windows whose surface should be destroyed.
306 */
307 final ArrayList<WindowState> mDestroySurface = new ArrayList<WindowState>();
308
309 /**
310 * Windows that have lost input focus and are waiting for the new
311 * focus window to be displayed before they are told about this.
312 */
313 ArrayList<WindowState> mLosingFocus = new ArrayList<WindowState>();
314
315 /**
316 * This is set when we have run out of memory, and will either be an empty
317 * list or contain windows that need to be force removed.
318 */
319 ArrayList<WindowState> mForceRemoves;
320
321 IInputMethodManager mInputMethodManager;
322
323 SurfaceSession mFxSession;
324 Surface mDimSurface;
325 boolean mDimShown;
326 float mDimCurrentAlpha;
327 float mDimTargetAlpha;
328 float mDimDeltaPerMs;
329 long mLastDimAnimTime;
330 Surface mBlurSurface;
331 boolean mBlurShown;
332
333 int mTransactionSequence = 0;
334
335 final float[] mTmpFloats = new float[9];
336
337 boolean mSafeMode;
338 boolean mDisplayEnabled = false;
339 boolean mSystemBooted = false;
340 int mRotation = 0;
341 int mRequestedRotation = 0;
342 int mForcedAppOrientation = ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
Dianne Hackborn321ae682009-03-27 16:16:03 -0700343 int mLastRotationFlags;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800344 ArrayList<IRotationWatcher> mRotationWatchers
345 = new ArrayList<IRotationWatcher>();
346
347 boolean mLayoutNeeded = true;
348 boolean mAnimationPending = false;
349 boolean mDisplayFrozen = false;
350 boolean mWindowsFreezingScreen = false;
351 long mFreezeGcPending = 0;
352 int mAppsFreezingScreen = 0;
353
354 // This is held as long as we have the screen frozen, to give us time to
355 // perform a rotation animation when turning off shows the lock screen which
356 // changes the orientation.
357 PowerManager.WakeLock mScreenFrozenLock;
358
359 // State management of app transitions. When we are preparing for a
360 // transition, mNextAppTransition will be the kind of transition to
361 // perform or TRANSIT_NONE if we are not waiting. If we are waiting,
362 // mOpeningApps and mClosingApps are the lists of tokens that will be
363 // made visible or hidden at the next transition.
364 int mNextAppTransition = WindowManagerPolicy.TRANSIT_NONE;
365 boolean mAppTransitionReady = false;
366 boolean mAppTransitionTimeout = false;
367 boolean mStartingIconInTransition = false;
368 boolean mSkipAppTransitionAnimation = false;
369 final ArrayList<AppWindowToken> mOpeningApps = new ArrayList<AppWindowToken>();
370 final ArrayList<AppWindowToken> mClosingApps = new ArrayList<AppWindowToken>();
371
372 //flag to detect fat touch events
373 boolean mFatTouch = false;
374 Display mDisplay;
375
376 H mH = new H();
377
378 WindowState mCurrentFocus = null;
379 WindowState mLastFocus = null;
380
381 // This just indicates the window the input method is on top of, not
382 // necessarily the window its input is going to.
383 WindowState mInputMethodTarget = null;
384 WindowState mUpcomingInputMethodTarget = null;
385 boolean mInputMethodTargetWaitingAnim;
386 int mInputMethodAnimLayerAdjustment;
387
388 WindowState mInputMethodWindow = null;
389 final ArrayList<WindowState> mInputMethodDialogs = new ArrayList<WindowState>();
390
391 AppWindowToken mFocusedApp = null;
392
393 PowerManagerService mPowerManager;
394
395 float mWindowAnimationScale = 1.0f;
396 float mTransitionAnimationScale = 1.0f;
397
398 final KeyWaiter mKeyWaiter = new KeyWaiter();
399 final KeyQ mQueue;
400 final InputDispatcherThread mInputThread;
401
402 // Who is holding the screen on.
403 Session mHoldingScreenOn;
404
405 /**
406 * Whether the UI is currently running in touch mode (not showing
407 * navigational focus because the user is directly pressing the screen).
408 */
409 boolean mInTouchMode = false;
410
411 private ViewServer mViewServer;
412
413 final Rect mTempRect = new Rect();
414
Dianne Hackbornc485a602009-03-24 22:39:49 -0700415 final Configuration mTempConfiguration = new Configuration();
416
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800417 public static WindowManagerService main(Context context,
418 PowerManagerService pm, boolean haveInputMethods) {
419 WMThread thr = new WMThread(context, pm, haveInputMethods);
420 thr.start();
421
422 synchronized (thr) {
423 while (thr.mService == null) {
424 try {
425 thr.wait();
426 } catch (InterruptedException e) {
427 }
428 }
429 }
430
431 return thr.mService;
432 }
433
434 static class WMThread extends Thread {
435 WindowManagerService mService;
436
437 private final Context mContext;
438 private final PowerManagerService mPM;
439 private final boolean mHaveInputMethods;
440
441 public WMThread(Context context, PowerManagerService pm,
442 boolean haveInputMethods) {
443 super("WindowManager");
444 mContext = context;
445 mPM = pm;
446 mHaveInputMethods = haveInputMethods;
447 }
448
449 public void run() {
450 Looper.prepare();
451 WindowManagerService s = new WindowManagerService(mContext, mPM,
452 mHaveInputMethods);
453 android.os.Process.setThreadPriority(
454 android.os.Process.THREAD_PRIORITY_DISPLAY);
455
456 synchronized (this) {
457 mService = s;
458 notifyAll();
459 }
460
461 Looper.loop();
462 }
463 }
464
465 static class PolicyThread extends Thread {
466 private final WindowManagerPolicy mPolicy;
467 private final WindowManagerService mService;
468 private final Context mContext;
469 private final PowerManagerService mPM;
470 boolean mRunning = false;
471
472 public PolicyThread(WindowManagerPolicy policy,
473 WindowManagerService service, Context context,
474 PowerManagerService pm) {
475 super("WindowManagerPolicy");
476 mPolicy = policy;
477 mService = service;
478 mContext = context;
479 mPM = pm;
480 }
481
482 public void run() {
483 Looper.prepare();
484 //Looper.myLooper().setMessageLogging(new LogPrinter(
485 // Log.VERBOSE, "WindowManagerPolicy"));
486 android.os.Process.setThreadPriority(
487 android.os.Process.THREAD_PRIORITY_FOREGROUND);
488 mPolicy.init(mContext, mService, mPM);
489
490 synchronized (this) {
491 mRunning = true;
492 notifyAll();
493 }
494
495 Looper.loop();
496 }
497 }
498
499 private WindowManagerService(Context context, PowerManagerService pm,
500 boolean haveInputMethods) {
Michael Chan53071d62009-05-13 17:29:48 -0700501 if (MEASURE_LATENCY) {
502 lt = new LatencyTimer(100, 1000);
503 }
504
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800505 mContext = context;
506 mHaveInputMethods = haveInputMethods;
507 mLimitedAlphaCompositing = context.getResources().getBoolean(
508 com.android.internal.R.bool.config_sf_limitedAlpha);
509
510 mPowerManager = pm;
511 mPowerManager.setPolicy(mPolicy);
512 PowerManager pmc = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
513 mScreenFrozenLock = pmc.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
514 "SCREEN_FROZEN");
515 mScreenFrozenLock.setReferenceCounted(false);
516
517 mActivityManager = ActivityManagerNative.getDefault();
518 mBatteryStats = BatteryStatsService.getService();
519
520 // Get persisted window scale setting
521 mWindowAnimationScale = Settings.System.getFloat(context.getContentResolver(),
522 Settings.System.WINDOW_ANIMATION_SCALE, mWindowAnimationScale);
523 mTransitionAnimationScale = Settings.System.getFloat(context.getContentResolver(),
524 Settings.System.TRANSITION_ANIMATION_SCALE, mTransitionAnimationScale);
525
526 mQueue = new KeyQ();
527
528 mInputThread = new InputDispatcherThread();
529
530 PolicyThread thr = new PolicyThread(mPolicy, this, context, pm);
531 thr.start();
532
533 synchronized (thr) {
534 while (!thr.mRunning) {
535 try {
536 thr.wait();
537 } catch (InterruptedException e) {
538 }
539 }
540 }
541
542 mInputThread.start();
543
544 // Add ourself to the Watchdog monitors.
545 Watchdog.getInstance().addMonitor(this);
546 }
547
548 @Override
549 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
550 throws RemoteException {
551 try {
552 return super.onTransact(code, data, reply, flags);
553 } catch (RuntimeException e) {
554 // The window manager only throws security exceptions, so let's
555 // log all others.
556 if (!(e instanceof SecurityException)) {
557 Log.e(TAG, "Window Manager Crash", e);
558 }
559 throw e;
560 }
561 }
562
563 private void placeWindowAfter(Object pos, WindowState window) {
564 final int i = mWindows.indexOf(pos);
565 if (localLOGV || DEBUG_FOCUS) Log.v(
566 TAG, "Adding window " + window + " at "
567 + (i+1) + " of " + mWindows.size() + " (after " + pos + ")");
568 mWindows.add(i+1, window);
569 }
570
571 private void placeWindowBefore(Object pos, WindowState window) {
572 final int i = mWindows.indexOf(pos);
573 if (localLOGV || DEBUG_FOCUS) Log.v(
574 TAG, "Adding window " + window + " at "
575 + i + " of " + mWindows.size() + " (before " + pos + ")");
576 mWindows.add(i, window);
577 }
578
579 //This method finds out the index of a window that has the same app token as
580 //win. used for z ordering the windows in mWindows
581 private int findIdxBasedOnAppTokens(WindowState win) {
582 //use a local variable to cache mWindows
583 ArrayList localmWindows = mWindows;
584 int jmax = localmWindows.size();
585 if(jmax == 0) {
586 return -1;
587 }
588 for(int j = (jmax-1); j >= 0; j--) {
589 WindowState wentry = (WindowState)localmWindows.get(j);
590 if(wentry.mAppToken == win.mAppToken) {
591 return j;
592 }
593 }
594 return -1;
595 }
596
597 private void addWindowToListInOrderLocked(WindowState win, boolean addToToken) {
598 final IWindow client = win.mClient;
599 final WindowToken token = win.mToken;
600 final ArrayList localmWindows = mWindows;
601
602 final int N = localmWindows.size();
603 final WindowState attached = win.mAttachedWindow;
604 int i;
605 if (attached == null) {
606 int tokenWindowsPos = token.windows.size();
607 if (token.appWindowToken != null) {
608 int index = tokenWindowsPos-1;
609 if (index >= 0) {
610 // If this application has existing windows, we
611 // simply place the new window on top of them... but
612 // keep the starting window on top.
613 if (win.mAttrs.type == TYPE_BASE_APPLICATION) {
614 // Base windows go behind everything else.
615 placeWindowBefore(token.windows.get(0), win);
616 tokenWindowsPos = 0;
617 } else {
618 AppWindowToken atoken = win.mAppToken;
619 if (atoken != null &&
620 token.windows.get(index) == atoken.startingWindow) {
621 placeWindowBefore(token.windows.get(index), win);
622 tokenWindowsPos--;
623 } else {
624 int newIdx = findIdxBasedOnAppTokens(win);
625 if(newIdx != -1) {
626 //there is a window above this one associated with the same
627 //apptoken note that the window could be a floating window
628 //that was created later or a window at the top of the list of
629 //windows associated with this token.
630 localmWindows.add(newIdx+1, win);
631 }
632 }
633 }
634 } else {
635 if (localLOGV) Log.v(
636 TAG, "Figuring out where to add app window "
637 + client.asBinder() + " (token=" + token + ")");
638 // Figure out where the window should go, based on the
639 // order of applications.
640 final int NA = mAppTokens.size();
641 Object pos = null;
642 for (i=NA-1; i>=0; i--) {
643 AppWindowToken t = mAppTokens.get(i);
644 if (t == token) {
645 i--;
646 break;
647 }
648 if (t.windows.size() > 0) {
649 pos = t.windows.get(0);
650 }
651 }
652 // We now know the index into the apps. If we found
653 // an app window above, that gives us the position; else
654 // we need to look some more.
655 if (pos != null) {
656 // Move behind any windows attached to this one.
657 WindowToken atoken =
658 mTokenMap.get(((WindowState)pos).mClient.asBinder());
659 if (atoken != null) {
660 final int NC = atoken.windows.size();
661 if (NC > 0) {
662 WindowState bottom = atoken.windows.get(0);
663 if (bottom.mSubLayer < 0) {
664 pos = bottom;
665 }
666 }
667 }
668 placeWindowBefore(pos, win);
669 } else {
670 while (i >= 0) {
671 AppWindowToken t = mAppTokens.get(i);
672 final int NW = t.windows.size();
673 if (NW > 0) {
674 pos = t.windows.get(NW-1);
675 break;
676 }
677 i--;
678 }
679 if (pos != null) {
680 // Move in front of any windows attached to this
681 // one.
682 WindowToken atoken =
683 mTokenMap.get(((WindowState)pos).mClient.asBinder());
684 if (atoken != null) {
685 final int NC = atoken.windows.size();
686 if (NC > 0) {
687 WindowState top = atoken.windows.get(NC-1);
688 if (top.mSubLayer >= 0) {
689 pos = top;
690 }
691 }
692 }
693 placeWindowAfter(pos, win);
694 } else {
695 // Just search for the start of this layer.
696 final int myLayer = win.mBaseLayer;
697 for (i=0; i<N; i++) {
698 WindowState w = (WindowState)localmWindows.get(i);
699 if (w.mBaseLayer > myLayer) {
700 break;
701 }
702 }
703 if (localLOGV || DEBUG_FOCUS) Log.v(
704 TAG, "Adding window " + win + " at "
705 + i + " of " + N);
706 localmWindows.add(i, win);
707 }
708 }
709 }
710 } else {
711 // Figure out where window should go, based on layer.
712 final int myLayer = win.mBaseLayer;
713 for (i=N-1; i>=0; i--) {
714 if (((WindowState)localmWindows.get(i)).mBaseLayer <= myLayer) {
715 i++;
716 break;
717 }
718 }
719 if (i < 0) i = 0;
720 if (localLOGV || DEBUG_FOCUS) Log.v(
721 TAG, "Adding window " + win + " at "
722 + i + " of " + N);
723 localmWindows.add(i, win);
724 }
725 if (addToToken) {
726 token.windows.add(tokenWindowsPos, win);
727 }
728
729 } else {
730 // Figure out this window's ordering relative to the window
731 // it is attached to.
732 final int NA = token.windows.size();
733 final int sublayer = win.mSubLayer;
734 int largestSublayer = Integer.MIN_VALUE;
735 WindowState windowWithLargestSublayer = null;
736 for (i=0; i<NA; i++) {
737 WindowState w = token.windows.get(i);
738 final int wSublayer = w.mSubLayer;
739 if (wSublayer >= largestSublayer) {
740 largestSublayer = wSublayer;
741 windowWithLargestSublayer = w;
742 }
743 if (sublayer < 0) {
744 // For negative sublayers, we go below all windows
745 // in the same sublayer.
746 if (wSublayer >= sublayer) {
747 if (addToToken) {
748 token.windows.add(i, win);
749 }
750 placeWindowBefore(
751 wSublayer >= 0 ? attached : w, win);
752 break;
753 }
754 } else {
755 // For positive sublayers, we go above all windows
756 // in the same sublayer.
757 if (wSublayer > sublayer) {
758 if (addToToken) {
759 token.windows.add(i, win);
760 }
761 placeWindowBefore(w, win);
762 break;
763 }
764 }
765 }
766 if (i >= NA) {
767 if (addToToken) {
768 token.windows.add(win);
769 }
770 if (sublayer < 0) {
771 placeWindowBefore(attached, win);
772 } else {
773 placeWindowAfter(largestSublayer >= 0
774 ? windowWithLargestSublayer
775 : attached,
776 win);
777 }
778 }
779 }
780
781 if (win.mAppToken != null && addToToken) {
782 win.mAppToken.allAppWindows.add(win);
783 }
784 }
785
786 static boolean canBeImeTarget(WindowState w) {
787 final int fl = w.mAttrs.flags
788 & (FLAG_NOT_FOCUSABLE|FLAG_ALT_FOCUSABLE_IM);
789 if (fl == 0 || fl == (FLAG_NOT_FOCUSABLE|FLAG_ALT_FOCUSABLE_IM)) {
790 return w.isVisibleOrAdding();
791 }
792 return false;
793 }
794
795 int findDesiredInputMethodWindowIndexLocked(boolean willMove) {
796 final ArrayList localmWindows = mWindows;
797 final int N = localmWindows.size();
798 WindowState w = null;
799 int i = N;
800 while (i > 0) {
801 i--;
802 w = (WindowState)localmWindows.get(i);
803
804 //Log.i(TAG, "Checking window @" + i + " " + w + " fl=0x"
805 // + Integer.toHexString(w.mAttrs.flags));
806 if (canBeImeTarget(w)) {
807 //Log.i(TAG, "Putting input method here!");
808
809 // Yet more tricksyness! If this window is a "starting"
810 // window, we do actually want to be on top of it, but
811 // it is not -really- where input will go. So if the caller
812 // is not actually looking to move the IME, look down below
813 // for a real window to target...
814 if (!willMove
815 && w.mAttrs.type == WindowManager.LayoutParams.TYPE_APPLICATION_STARTING
816 && i > 0) {
817 WindowState wb = (WindowState)localmWindows.get(i-1);
818 if (wb.mAppToken == w.mAppToken && canBeImeTarget(wb)) {
819 i--;
820 w = wb;
821 }
822 }
823 break;
824 }
825 }
826
827 mUpcomingInputMethodTarget = w;
828
829 if (DEBUG_INPUT_METHOD) Log.v(TAG, "Desired input method target="
830 + w + " willMove=" + willMove);
831
832 if (willMove && w != null) {
833 final WindowState curTarget = mInputMethodTarget;
834 if (curTarget != null && curTarget.mAppToken != null) {
835
836 // Now some fun for dealing with window animations that
837 // modify the Z order. We need to look at all windows below
838 // the current target that are in this app, finding the highest
839 // visible one in layering.
840 AppWindowToken token = curTarget.mAppToken;
841 WindowState highestTarget = null;
842 int highestPos = 0;
843 if (token.animating || token.animation != null) {
844 int pos = 0;
845 pos = localmWindows.indexOf(curTarget);
846 while (pos >= 0) {
847 WindowState win = (WindowState)localmWindows.get(pos);
848 if (win.mAppToken != token) {
849 break;
850 }
851 if (!win.mRemoved) {
852 if (highestTarget == null || win.mAnimLayer >
853 highestTarget.mAnimLayer) {
854 highestTarget = win;
855 highestPos = pos;
856 }
857 }
858 pos--;
859 }
860 }
861
862 if (highestTarget != null) {
863 if (DEBUG_INPUT_METHOD) Log.v(TAG, "mNextAppTransition="
864 + mNextAppTransition + " " + highestTarget
865 + " animating=" + highestTarget.isAnimating()
866 + " layer=" + highestTarget.mAnimLayer
867 + " new layer=" + w.mAnimLayer);
868
869 if (mNextAppTransition != WindowManagerPolicy.TRANSIT_NONE) {
870 // If we are currently setting up for an animation,
871 // hold everything until we can find out what will happen.
872 mInputMethodTargetWaitingAnim = true;
873 mInputMethodTarget = highestTarget;
874 return highestPos + 1;
875 } else if (highestTarget.isAnimating() &&
876 highestTarget.mAnimLayer > w.mAnimLayer) {
877 // If the window we are currently targeting is involved
878 // with an animation, and it is on top of the next target
879 // we will be over, then hold off on moving until
880 // that is done.
881 mInputMethodTarget = highestTarget;
882 return highestPos + 1;
883 }
884 }
885 }
886 }
887
888 //Log.i(TAG, "Placing input method @" + (i+1));
889 if (w != null) {
890 if (willMove) {
891 RuntimeException e = new RuntimeException();
892 e.fillInStackTrace();
893 if (DEBUG_INPUT_METHOD) Log.w(TAG, "Moving IM target from "
894 + mInputMethodTarget + " to " + w, e);
895 mInputMethodTarget = w;
896 if (w.mAppToken != null) {
897 setInputMethodAnimLayerAdjustment(w.mAppToken.animLayerAdjustment);
898 } else {
899 setInputMethodAnimLayerAdjustment(0);
900 }
901 }
902 return i+1;
903 }
904 if (willMove) {
905 RuntimeException e = new RuntimeException();
906 e.fillInStackTrace();
907 if (DEBUG_INPUT_METHOD) Log.w(TAG, "Moving IM target from "
908 + mInputMethodTarget + " to null", e);
909 mInputMethodTarget = null;
910 setInputMethodAnimLayerAdjustment(0);
911 }
912 return -1;
913 }
914
915 void addInputMethodWindowToListLocked(WindowState win) {
916 int pos = findDesiredInputMethodWindowIndexLocked(true);
917 if (pos >= 0) {
918 win.mTargetAppToken = mInputMethodTarget.mAppToken;
919 mWindows.add(pos, win);
920 moveInputMethodDialogsLocked(pos+1);
921 return;
922 }
923 win.mTargetAppToken = null;
924 addWindowToListInOrderLocked(win, true);
925 moveInputMethodDialogsLocked(pos);
926 }
927
928 void setInputMethodAnimLayerAdjustment(int adj) {
929 if (DEBUG_LAYERS) Log.v(TAG, "Setting im layer adj to " + adj);
930 mInputMethodAnimLayerAdjustment = adj;
931 WindowState imw = mInputMethodWindow;
932 if (imw != null) {
933 imw.mAnimLayer = imw.mLayer + adj;
934 if (DEBUG_LAYERS) Log.v(TAG, "IM win " + imw
935 + " anim layer: " + imw.mAnimLayer);
936 int wi = imw.mChildWindows.size();
937 while (wi > 0) {
938 wi--;
939 WindowState cw = (WindowState)imw.mChildWindows.get(wi);
940 cw.mAnimLayer = cw.mLayer + adj;
941 if (DEBUG_LAYERS) Log.v(TAG, "IM win " + cw
942 + " anim layer: " + cw.mAnimLayer);
943 }
944 }
945 int di = mInputMethodDialogs.size();
946 while (di > 0) {
947 di --;
948 imw = mInputMethodDialogs.get(di);
949 imw.mAnimLayer = imw.mLayer + adj;
950 if (DEBUG_LAYERS) Log.v(TAG, "IM win " + imw
951 + " anim layer: " + imw.mAnimLayer);
952 }
953 }
954
955 private int tmpRemoveWindowLocked(int interestingPos, WindowState win) {
956 int wpos = mWindows.indexOf(win);
957 if (wpos >= 0) {
958 if (wpos < interestingPos) interestingPos--;
959 mWindows.remove(wpos);
960 int NC = win.mChildWindows.size();
961 while (NC > 0) {
962 NC--;
963 WindowState cw = (WindowState)win.mChildWindows.get(NC);
964 int cpos = mWindows.indexOf(cw);
965 if (cpos >= 0) {
966 if (cpos < interestingPos) interestingPos--;
967 mWindows.remove(cpos);
968 }
969 }
970 }
971 return interestingPos;
972 }
973
974 private void reAddWindowToListInOrderLocked(WindowState win) {
975 addWindowToListInOrderLocked(win, false);
976 // This is a hack to get all of the child windows added as well
977 // at the right position. Child windows should be rare and
978 // this case should be rare, so it shouldn't be that big a deal.
979 int wpos = mWindows.indexOf(win);
980 if (wpos >= 0) {
981 mWindows.remove(wpos);
982 reAddWindowLocked(wpos, win);
983 }
984 }
985
986 void logWindowList(String prefix) {
987 int N = mWindows.size();
988 while (N > 0) {
989 N--;
990 Log.v(TAG, prefix + "#" + N + ": " + mWindows.get(N));
991 }
992 }
993
994 void moveInputMethodDialogsLocked(int pos) {
995 ArrayList<WindowState> dialogs = mInputMethodDialogs;
996
997 final int N = dialogs.size();
998 if (DEBUG_INPUT_METHOD) Log.v(TAG, "Removing " + N + " dialogs w/pos=" + pos);
999 for (int i=0; i<N; i++) {
1000 pos = tmpRemoveWindowLocked(pos, dialogs.get(i));
1001 }
1002 if (DEBUG_INPUT_METHOD) {
1003 Log.v(TAG, "Window list w/pos=" + pos);
1004 logWindowList(" ");
1005 }
1006
1007 if (pos >= 0) {
1008 final AppWindowToken targetAppToken = mInputMethodTarget.mAppToken;
1009 if (pos < mWindows.size()) {
1010 WindowState wp = (WindowState)mWindows.get(pos);
1011 if (wp == mInputMethodWindow) {
1012 pos++;
1013 }
1014 }
1015 if (DEBUG_INPUT_METHOD) Log.v(TAG, "Adding " + N + " dialogs at pos=" + pos);
1016 for (int i=0; i<N; i++) {
1017 WindowState win = dialogs.get(i);
1018 win.mTargetAppToken = targetAppToken;
1019 pos = reAddWindowLocked(pos, win);
1020 }
1021 if (DEBUG_INPUT_METHOD) {
1022 Log.v(TAG, "Final window list:");
1023 logWindowList(" ");
1024 }
1025 return;
1026 }
1027 for (int i=0; i<N; i++) {
1028 WindowState win = dialogs.get(i);
1029 win.mTargetAppToken = null;
1030 reAddWindowToListInOrderLocked(win);
1031 if (DEBUG_INPUT_METHOD) {
1032 Log.v(TAG, "No IM target, final list:");
1033 logWindowList(" ");
1034 }
1035 }
1036 }
1037
1038 boolean moveInputMethodWindowsIfNeededLocked(boolean needAssignLayers) {
1039 final WindowState imWin = mInputMethodWindow;
1040 final int DN = mInputMethodDialogs.size();
1041 if (imWin == null && DN == 0) {
1042 return false;
1043 }
1044
1045 int imPos = findDesiredInputMethodWindowIndexLocked(true);
1046 if (imPos >= 0) {
1047 // In this case, the input method windows are to be placed
1048 // immediately above the window they are targeting.
1049
1050 // First check to see if the input method windows are already
1051 // located here, and contiguous.
1052 final int N = mWindows.size();
1053 WindowState firstImWin = imPos < N
1054 ? (WindowState)mWindows.get(imPos) : null;
1055
1056 // Figure out the actual input method window that should be
1057 // at the bottom of their stack.
1058 WindowState baseImWin = imWin != null
1059 ? imWin : mInputMethodDialogs.get(0);
1060 if (baseImWin.mChildWindows.size() > 0) {
1061 WindowState cw = (WindowState)baseImWin.mChildWindows.get(0);
1062 if (cw.mSubLayer < 0) baseImWin = cw;
1063 }
1064
1065 if (firstImWin == baseImWin) {
1066 // The windows haven't moved... but are they still contiguous?
1067 // First find the top IM window.
1068 int pos = imPos+1;
1069 while (pos < N) {
1070 if (!((WindowState)mWindows.get(pos)).mIsImWindow) {
1071 break;
1072 }
1073 pos++;
1074 }
1075 pos++;
1076 // Now there should be no more input method windows above.
1077 while (pos < N) {
1078 if (((WindowState)mWindows.get(pos)).mIsImWindow) {
1079 break;
1080 }
1081 pos++;
1082 }
1083 if (pos >= N) {
1084 // All is good!
1085 return false;
1086 }
1087 }
1088
1089 if (imWin != null) {
1090 if (DEBUG_INPUT_METHOD) {
1091 Log.v(TAG, "Moving IM from " + imPos);
1092 logWindowList(" ");
1093 }
1094 imPos = tmpRemoveWindowLocked(imPos, imWin);
1095 if (DEBUG_INPUT_METHOD) {
1096 Log.v(TAG, "List after moving with new pos " + imPos + ":");
1097 logWindowList(" ");
1098 }
1099 imWin.mTargetAppToken = mInputMethodTarget.mAppToken;
1100 reAddWindowLocked(imPos, imWin);
1101 if (DEBUG_INPUT_METHOD) {
1102 Log.v(TAG, "List after moving IM to " + imPos + ":");
1103 logWindowList(" ");
1104 }
1105 if (DN > 0) moveInputMethodDialogsLocked(imPos+1);
1106 } else {
1107 moveInputMethodDialogsLocked(imPos);
1108 }
1109
1110 } else {
1111 // In this case, the input method windows go in a fixed layer,
1112 // because they aren't currently associated with a focus window.
1113
1114 if (imWin != null) {
1115 if (DEBUG_INPUT_METHOD) Log.v(TAG, "Moving IM from " + imPos);
1116 tmpRemoveWindowLocked(0, imWin);
1117 imWin.mTargetAppToken = null;
1118 reAddWindowToListInOrderLocked(imWin);
1119 if (DEBUG_INPUT_METHOD) {
1120 Log.v(TAG, "List with no IM target:");
1121 logWindowList(" ");
1122 }
1123 if (DN > 0) moveInputMethodDialogsLocked(-1);;
1124 } else {
1125 moveInputMethodDialogsLocked(-1);;
1126 }
1127
1128 }
1129
1130 if (needAssignLayers) {
1131 assignLayersLocked();
1132 }
1133
1134 return true;
1135 }
1136
1137 void adjustInputMethodDialogsLocked() {
1138 moveInputMethodDialogsLocked(findDesiredInputMethodWindowIndexLocked(true));
1139 }
1140
1141 public int addWindow(Session session, IWindow client,
1142 WindowManager.LayoutParams attrs, int viewVisibility,
1143 Rect outContentInsets) {
1144 int res = mPolicy.checkAddPermission(attrs);
1145 if (res != WindowManagerImpl.ADD_OKAY) {
1146 return res;
1147 }
1148
1149 boolean reportNewConfig = false;
1150 WindowState attachedWindow = null;
1151 WindowState win = null;
1152
1153 synchronized(mWindowMap) {
1154 // Instantiating a Display requires talking with the simulator,
1155 // so don't do it until we know the system is mostly up and
1156 // running.
1157 if (mDisplay == null) {
1158 WindowManager wm = (WindowManager)mContext.getSystemService(Context.WINDOW_SERVICE);
1159 mDisplay = wm.getDefaultDisplay();
1160 mQueue.setDisplay(mDisplay);
1161 reportNewConfig = true;
1162 }
1163
1164 if (mWindowMap.containsKey(client.asBinder())) {
1165 Log.w(TAG, "Window " + client + " is already added");
1166 return WindowManagerImpl.ADD_DUPLICATE_ADD;
1167 }
1168
1169 if (attrs.type >= FIRST_SUB_WINDOW && attrs.type <= LAST_SUB_WINDOW) {
1170 attachedWindow = windowForClientLocked(null, attrs.token);
1171 if (attachedWindow == null) {
1172 Log.w(TAG, "Attempted to add window with token that is not a window: "
1173 + attrs.token + ". Aborting.");
1174 return WindowManagerImpl.ADD_BAD_SUBWINDOW_TOKEN;
1175 }
1176 if (attachedWindow.mAttrs.type >= FIRST_SUB_WINDOW
1177 && attachedWindow.mAttrs.type <= LAST_SUB_WINDOW) {
1178 Log.w(TAG, "Attempted to add window with token that is a sub-window: "
1179 + attrs.token + ". Aborting.");
1180 return WindowManagerImpl.ADD_BAD_SUBWINDOW_TOKEN;
1181 }
1182 }
1183
1184 boolean addToken = false;
1185 WindowToken token = mTokenMap.get(attrs.token);
1186 if (token == null) {
1187 if (attrs.type >= FIRST_APPLICATION_WINDOW
1188 && attrs.type <= LAST_APPLICATION_WINDOW) {
1189 Log.w(TAG, "Attempted to add application window with unknown token "
1190 + attrs.token + ". Aborting.");
1191 return WindowManagerImpl.ADD_BAD_APP_TOKEN;
1192 }
1193 if (attrs.type == TYPE_INPUT_METHOD) {
1194 Log.w(TAG, "Attempted to add input method window with unknown token "
1195 + attrs.token + ". Aborting.");
1196 return WindowManagerImpl.ADD_BAD_APP_TOKEN;
1197 }
1198 token = new WindowToken(attrs.token, -1, false);
1199 addToken = true;
1200 } else if (attrs.type >= FIRST_APPLICATION_WINDOW
1201 && attrs.type <= LAST_APPLICATION_WINDOW) {
1202 AppWindowToken atoken = token.appWindowToken;
1203 if (atoken == null) {
1204 Log.w(TAG, "Attempted to add window with non-application token "
1205 + token + ". Aborting.");
1206 return WindowManagerImpl.ADD_NOT_APP_TOKEN;
1207 } else if (atoken.removed) {
1208 Log.w(TAG, "Attempted to add window with exiting application token "
1209 + token + ". Aborting.");
1210 return WindowManagerImpl.ADD_APP_EXITING;
1211 }
1212 if (attrs.type == TYPE_APPLICATION_STARTING && atoken.firstWindowDrawn) {
1213 // No need for this guy!
1214 if (localLOGV) Log.v(
1215 TAG, "**** NO NEED TO START: " + attrs.getTitle());
1216 return WindowManagerImpl.ADD_STARTING_NOT_NEEDED;
1217 }
1218 } else if (attrs.type == TYPE_INPUT_METHOD) {
1219 if (token.windowType != TYPE_INPUT_METHOD) {
1220 Log.w(TAG, "Attempted to add input method window with bad token "
1221 + attrs.token + ". Aborting.");
1222 return WindowManagerImpl.ADD_BAD_APP_TOKEN;
1223 }
1224 }
1225
1226 win = new WindowState(session, client, token,
1227 attachedWindow, attrs, viewVisibility);
1228 if (win.mDeathRecipient == null) {
1229 // Client has apparently died, so there is no reason to
1230 // continue.
1231 Log.w(TAG, "Adding window client " + client.asBinder()
1232 + " that is dead, aborting.");
1233 return WindowManagerImpl.ADD_APP_EXITING;
1234 }
1235
1236 mPolicy.adjustWindowParamsLw(win.mAttrs);
1237
1238 res = mPolicy.prepareAddWindowLw(win, attrs);
1239 if (res != WindowManagerImpl.ADD_OKAY) {
1240 return res;
1241 }
1242
1243 // From now on, no exceptions or errors allowed!
1244
1245 res = WindowManagerImpl.ADD_OKAY;
1246
1247 final long origId = Binder.clearCallingIdentity();
1248
1249 if (addToken) {
1250 mTokenMap.put(attrs.token, token);
1251 mTokenList.add(token);
1252 }
1253 win.attach();
1254 mWindowMap.put(client.asBinder(), win);
1255
1256 if (attrs.type == TYPE_APPLICATION_STARTING &&
1257 token.appWindowToken != null) {
1258 token.appWindowToken.startingWindow = win;
1259 }
1260
1261 boolean imMayMove = true;
1262
1263 if (attrs.type == TYPE_INPUT_METHOD) {
1264 mInputMethodWindow = win;
1265 addInputMethodWindowToListLocked(win);
1266 imMayMove = false;
1267 } else if (attrs.type == TYPE_INPUT_METHOD_DIALOG) {
1268 mInputMethodDialogs.add(win);
1269 addWindowToListInOrderLocked(win, true);
1270 adjustInputMethodDialogsLocked();
1271 imMayMove = false;
1272 } else {
1273 addWindowToListInOrderLocked(win, true);
1274 }
1275
1276 win.mEnterAnimationPending = true;
1277
1278 mPolicy.getContentInsetHintLw(attrs, outContentInsets);
1279
1280 if (mInTouchMode) {
1281 res |= WindowManagerImpl.ADD_FLAG_IN_TOUCH_MODE;
1282 }
1283 if (win == null || win.mAppToken == null || !win.mAppToken.clientHidden) {
1284 res |= WindowManagerImpl.ADD_FLAG_APP_VISIBLE;
1285 }
1286
The Android Open Source Projectc474dec2009-03-04 09:49:09 -08001287 boolean focusChanged = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001288 if (win.canReceiveKeys()) {
The Android Open Source Projectc474dec2009-03-04 09:49:09 -08001289 if ((focusChanged=updateFocusedWindowLocked(UPDATE_FOCUS_WILL_ASSIGN_LAYERS))
1290 == true) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001291 imMayMove = false;
1292 }
1293 }
1294
1295 if (imMayMove) {
1296 moveInputMethodWindowsIfNeededLocked(false);
1297 }
1298
1299 assignLayersLocked();
1300 // Don't do layout here, the window must call
1301 // relayout to be displayed, so we'll do it there.
1302
1303 //dump();
1304
The Android Open Source Projectc474dec2009-03-04 09:49:09 -08001305 if (focusChanged) {
1306 if (mCurrentFocus != null) {
1307 mKeyWaiter.handleNewWindowLocked(mCurrentFocus);
1308 }
1309 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001310 if (localLOGV) Log.v(
1311 TAG, "New client " + client.asBinder()
1312 + ": window=" + win);
1313 }
1314
1315 // sendNewConfiguration() checks caller permissions so we must call it with
1316 // privilege. updateOrientationFromAppTokens() clears and resets the caller
1317 // identity anyway, so it's safe to just clear & restore around this whole
1318 // block.
1319 final long origId = Binder.clearCallingIdentity();
1320 if (reportNewConfig) {
1321 sendNewConfiguration();
1322 } else {
1323 // Update Orientation after adding a window, only if the window needs to be
1324 // displayed right away
1325 if (win.isVisibleOrAdding()) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001326 if (updateOrientationFromAppTokens(null, null) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001327 sendNewConfiguration();
1328 }
1329 }
1330 }
1331 Binder.restoreCallingIdentity(origId);
1332
1333 return res;
1334 }
1335
1336 public void removeWindow(Session session, IWindow client) {
1337 synchronized(mWindowMap) {
1338 WindowState win = windowForClientLocked(session, client);
1339 if (win == null) {
1340 return;
1341 }
1342 removeWindowLocked(session, win);
1343 }
1344 }
1345
1346 public void removeWindowLocked(Session session, WindowState win) {
1347
1348 if (localLOGV || DEBUG_FOCUS) Log.v(
1349 TAG, "Remove " + win + " client="
1350 + Integer.toHexString(System.identityHashCode(
1351 win.mClient.asBinder()))
1352 + ", surface=" + win.mSurface);
1353
1354 final long origId = Binder.clearCallingIdentity();
1355
1356 if (DEBUG_APP_TRANSITIONS) Log.v(
1357 TAG, "Remove " + win + ": mSurface=" + win.mSurface
1358 + " mExiting=" + win.mExiting
1359 + " isAnimating=" + win.isAnimating()
1360 + " app-animation="
1361 + (win.mAppToken != null ? win.mAppToken.animation : null)
1362 + " inPendingTransaction="
1363 + (win.mAppToken != null ? win.mAppToken.inPendingTransaction : false)
1364 + " mDisplayFrozen=" + mDisplayFrozen);
1365 // Visibility of the removed window. Will be used later to update orientation later on.
1366 boolean wasVisible = false;
1367 // First, see if we need to run an animation. If we do, we have
1368 // to hold off on removing the window until the animation is done.
1369 // If the display is frozen, just remove immediately, since the
1370 // animation wouldn't be seen.
1371 if (win.mSurface != null && !mDisplayFrozen) {
1372 // If we are not currently running the exit animation, we
1373 // need to see about starting one.
1374 if (wasVisible=win.isWinVisibleLw()) {
1375
1376 int transit = WindowManagerPolicy.TRANSIT_EXIT;
1377 if (win.getAttrs().type == TYPE_APPLICATION_STARTING) {
1378 transit = WindowManagerPolicy.TRANSIT_PREVIEW_DONE;
1379 }
1380 // Try starting an animation.
1381 if (applyAnimationLocked(win, transit, false)) {
1382 win.mExiting = true;
1383 }
1384 }
1385 if (win.mExiting || win.isAnimating()) {
1386 // The exit animation is running... wait for it!
1387 //Log.i(TAG, "*** Running exit animation...");
1388 win.mExiting = true;
1389 win.mRemoveOnExit = true;
1390 mLayoutNeeded = true;
1391 updateFocusedWindowLocked(UPDATE_FOCUS_WILL_PLACE_SURFACES);
1392 performLayoutAndPlaceSurfacesLocked();
1393 if (win.mAppToken != null) {
1394 win.mAppToken.updateReportedVisibilityLocked();
1395 }
1396 //dump();
1397 Binder.restoreCallingIdentity(origId);
1398 return;
1399 }
1400 }
1401
1402 removeWindowInnerLocked(session, win);
1403 // Removing a visible window will effect the computed orientation
1404 // So just update orientation if needed.
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07001405 if (wasVisible && computeForcedAppOrientationLocked()
1406 != mForcedAppOrientation) {
1407 mH.sendMessage(mH.obtainMessage(H.COMPUTE_AND_SEND_NEW_CONFIGURATION));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001408 }
1409 updateFocusedWindowLocked(UPDATE_FOCUS_NORMAL);
1410 Binder.restoreCallingIdentity(origId);
1411 }
1412
1413 private void removeWindowInnerLocked(Session session, WindowState win) {
1414 mKeyWaiter.releasePendingPointerLocked(win.mSession);
1415 mKeyWaiter.releasePendingTrackballLocked(win.mSession);
1416
1417 win.mRemoved = true;
1418
1419 if (mInputMethodTarget == win) {
1420 moveInputMethodWindowsIfNeededLocked(false);
1421 }
1422
1423 mPolicy.removeWindowLw(win);
1424 win.removeLocked();
1425
1426 mWindowMap.remove(win.mClient.asBinder());
1427 mWindows.remove(win);
1428
1429 if (mInputMethodWindow == win) {
1430 mInputMethodWindow = null;
1431 } else if (win.mAttrs.type == TYPE_INPUT_METHOD_DIALOG) {
1432 mInputMethodDialogs.remove(win);
1433 }
1434
1435 final WindowToken token = win.mToken;
1436 final AppWindowToken atoken = win.mAppToken;
1437 token.windows.remove(win);
1438 if (atoken != null) {
1439 atoken.allAppWindows.remove(win);
1440 }
1441 if (localLOGV) Log.v(
1442 TAG, "**** Removing window " + win + ": count="
1443 + token.windows.size());
1444 if (token.windows.size() == 0) {
1445 if (!token.explicit) {
1446 mTokenMap.remove(token.token);
1447 mTokenList.remove(token);
1448 } else if (atoken != null) {
1449 atoken.firstWindowDrawn = false;
1450 }
1451 }
1452
1453 if (atoken != null) {
1454 if (atoken.startingWindow == win) {
1455 atoken.startingWindow = null;
1456 } else if (atoken.allAppWindows.size() == 0 && atoken.startingData != null) {
1457 // If this is the last window and we had requested a starting
1458 // transition window, well there is no point now.
1459 atoken.startingData = null;
1460 } else if (atoken.allAppWindows.size() == 1 && atoken.startingView != null) {
1461 // If this is the last window except for a starting transition
1462 // window, we need to get rid of the starting transition.
1463 if (DEBUG_STARTING_WINDOW) {
1464 Log.v(TAG, "Schedule remove starting " + token
1465 + ": no more real windows");
1466 }
1467 Message m = mH.obtainMessage(H.REMOVE_STARTING, atoken);
1468 mH.sendMessage(m);
1469 }
1470 }
1471
1472 if (!mInLayout) {
1473 assignLayersLocked();
1474 mLayoutNeeded = true;
1475 performLayoutAndPlaceSurfacesLocked();
1476 if (win.mAppToken != null) {
1477 win.mAppToken.updateReportedVisibilityLocked();
1478 }
1479 }
1480 }
1481
1482 private void setTransparentRegionWindow(Session session, IWindow client, Region region) {
1483 long origId = Binder.clearCallingIdentity();
1484 try {
1485 synchronized (mWindowMap) {
1486 WindowState w = windowForClientLocked(session, client);
1487 if ((w != null) && (w.mSurface != null)) {
1488 Surface.openTransaction();
1489 try {
1490 w.mSurface.setTransparentRegionHint(region);
1491 } finally {
1492 Surface.closeTransaction();
1493 }
1494 }
1495 }
1496 } finally {
1497 Binder.restoreCallingIdentity(origId);
1498 }
1499 }
1500
1501 void setInsetsWindow(Session session, IWindow client,
1502 int touchableInsets, Rect contentInsets,
1503 Rect visibleInsets) {
1504 long origId = Binder.clearCallingIdentity();
1505 try {
1506 synchronized (mWindowMap) {
1507 WindowState w = windowForClientLocked(session, client);
1508 if (w != null) {
1509 w.mGivenInsetsPending = false;
1510 w.mGivenContentInsets.set(contentInsets);
1511 w.mGivenVisibleInsets.set(visibleInsets);
1512 w.mTouchableInsets = touchableInsets;
1513 mLayoutNeeded = true;
1514 performLayoutAndPlaceSurfacesLocked();
1515 }
1516 }
1517 } finally {
1518 Binder.restoreCallingIdentity(origId);
1519 }
1520 }
1521
1522 public void getWindowDisplayFrame(Session session, IWindow client,
1523 Rect outDisplayFrame) {
1524 synchronized(mWindowMap) {
1525 WindowState win = windowForClientLocked(session, client);
1526 if (win == null) {
1527 outDisplayFrame.setEmpty();
1528 return;
1529 }
1530 outDisplayFrame.set(win.mDisplayFrame);
1531 }
1532 }
1533
1534 public int relayoutWindow(Session session, IWindow client,
1535 WindowManager.LayoutParams attrs, int requestedWidth,
1536 int requestedHeight, int viewVisibility, boolean insetsPending,
1537 Rect outFrame, Rect outContentInsets, Rect outVisibleInsets,
1538 Surface outSurface) {
1539 boolean displayed = false;
1540 boolean inTouchMode;
1541 Configuration newConfig = null;
1542 long origId = Binder.clearCallingIdentity();
1543
1544 synchronized(mWindowMap) {
1545 WindowState win = windowForClientLocked(session, client);
1546 if (win == null) {
1547 return 0;
1548 }
1549 win.mRequestedWidth = requestedWidth;
1550 win.mRequestedHeight = requestedHeight;
1551
1552 if (attrs != null) {
1553 mPolicy.adjustWindowParamsLw(attrs);
1554 }
1555
1556 int attrChanges = 0;
1557 int flagChanges = 0;
1558 if (attrs != null) {
1559 flagChanges = win.mAttrs.flags ^= attrs.flags;
1560 attrChanges = win.mAttrs.copyFrom(attrs);
1561 }
1562
1563 if (localLOGV) Log.v(
1564 TAG, "Relayout given client " + client.asBinder()
1565 + " (" + win.mAttrs.getTitle() + ")");
1566
1567
1568 if ((attrChanges & WindowManager.LayoutParams.ALPHA_CHANGED) != 0) {
1569 win.mAlpha = attrs.alpha;
1570 }
1571
1572 final boolean scaledWindow =
1573 ((win.mAttrs.flags & WindowManager.LayoutParams.FLAG_SCALED) != 0);
1574
1575 if (scaledWindow) {
1576 // requested{Width|Height} Surface's physical size
1577 // attrs.{width|height} Size on screen
1578 win.mHScale = (attrs.width != requestedWidth) ?
1579 (attrs.width / (float)requestedWidth) : 1.0f;
1580 win.mVScale = (attrs.height != requestedHeight) ?
1581 (attrs.height / (float)requestedHeight) : 1.0f;
1582 }
1583
1584 boolean imMayMove = (flagChanges&(
1585 WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM |
1586 WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE)) != 0;
1587
1588 boolean focusMayChange = win.mViewVisibility != viewVisibility
1589 || ((flagChanges&WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE) != 0)
1590 || (!win.mRelayoutCalled);
1591
1592 win.mRelayoutCalled = true;
1593 final int oldVisibility = win.mViewVisibility;
1594 win.mViewVisibility = viewVisibility;
1595 if (viewVisibility == View.VISIBLE &&
1596 (win.mAppToken == null || !win.mAppToken.clientHidden)) {
1597 displayed = !win.isVisibleLw();
1598 if (win.mExiting) {
1599 win.mExiting = false;
1600 win.mAnimation = null;
1601 }
1602 if (win.mDestroying) {
1603 win.mDestroying = false;
1604 mDestroySurface.remove(win);
1605 }
1606 if (oldVisibility == View.GONE) {
1607 win.mEnterAnimationPending = true;
1608 }
1609 if (displayed && win.mSurface != null && !win.mDrawPending
1610 && !win.mCommitDrawPending && !mDisplayFrozen) {
1611 applyEnterAnimationLocked(win);
1612 }
1613 if ((attrChanges&WindowManager.LayoutParams.FORMAT_CHANGED) != 0) {
1614 // To change the format, we need to re-build the surface.
1615 win.destroySurfaceLocked();
1616 displayed = true;
1617 }
1618 try {
1619 Surface surface = win.createSurfaceLocked();
1620 if (surface != null) {
1621 outSurface.copyFrom(surface);
1622 } else {
1623 outSurface.clear();
1624 }
1625 } catch (Exception e) {
1626 Log.w(TAG, "Exception thrown when creating surface for client "
1627 + client + " (" + win.mAttrs.getTitle() + ")",
1628 e);
1629 Binder.restoreCallingIdentity(origId);
1630 return 0;
1631 }
1632 if (displayed) {
1633 focusMayChange = true;
1634 }
1635 if (win.mAttrs.type == TYPE_INPUT_METHOD
1636 && mInputMethodWindow == null) {
1637 mInputMethodWindow = win;
1638 imMayMove = true;
1639 }
1640 } else {
1641 win.mEnterAnimationPending = false;
1642 if (win.mSurface != null) {
1643 // If we are not currently running the exit animation, we
1644 // need to see about starting one.
1645 if (!win.mExiting) {
1646 // Try starting an animation; if there isn't one, we
1647 // can destroy the surface right away.
1648 int transit = WindowManagerPolicy.TRANSIT_EXIT;
1649 if (win.getAttrs().type == TYPE_APPLICATION_STARTING) {
1650 transit = WindowManagerPolicy.TRANSIT_PREVIEW_DONE;
1651 }
1652 if (win.isWinVisibleLw() &&
1653 applyAnimationLocked(win, transit, false)) {
1654 win.mExiting = true;
1655 mKeyWaiter.finishedKey(session, client, true,
1656 KeyWaiter.RETURN_NOTHING);
1657 } else if (win.isAnimating()) {
1658 // Currently in a hide animation... turn this into
1659 // an exit.
1660 win.mExiting = true;
1661 } else {
1662 if (mInputMethodWindow == win) {
1663 mInputMethodWindow = null;
1664 }
1665 win.destroySurfaceLocked();
1666 }
1667 }
1668 }
1669 outSurface.clear();
1670 }
1671
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001672 if (focusMayChange) {
1673 //System.out.println("Focus may change: " + win.mAttrs.getTitle());
1674 if (updateFocusedWindowLocked(UPDATE_FOCUS_WILL_PLACE_SURFACES)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001675 imMayMove = false;
1676 }
1677 //System.out.println("Relayout " + win + ": focus=" + mCurrentFocus);
1678 }
1679
The Android Open Source Projectc474dec2009-03-04 09:49:09 -08001680 // updateFocusedWindowLocked() already assigned layers so we only need to
1681 // reassign them at this point if the IM window state gets shuffled
1682 boolean assignLayers = false;
1683
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001684 if (imMayMove) {
1685 if (moveInputMethodWindowsIfNeededLocked(false)) {
1686 assignLayers = true;
1687 }
1688 }
1689
1690 mLayoutNeeded = true;
1691 win.mGivenInsetsPending = insetsPending;
1692 if (assignLayers) {
1693 assignLayersLocked();
1694 }
The Android Open Source Project10592532009-03-18 17:39:46 -07001695 newConfig = updateOrientationFromAppTokensLocked(null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001696 performLayoutAndPlaceSurfacesLocked();
1697 if (win.mAppToken != null) {
1698 win.mAppToken.updateReportedVisibilityLocked();
1699 }
1700 outFrame.set(win.mFrame);
1701 outContentInsets.set(win.mContentInsets);
1702 outVisibleInsets.set(win.mVisibleInsets);
1703 if (localLOGV) Log.v(
1704 TAG, "Relayout given client " + client.asBinder()
1705 + ", requestedWidth=" + requestedWidth
1706 + ", requestedHeight=" + requestedHeight
1707 + ", viewVisibility=" + viewVisibility
1708 + "\nRelayout returning frame=" + outFrame
1709 + ", surface=" + outSurface);
1710
1711 if (localLOGV || DEBUG_FOCUS) Log.v(
1712 TAG, "Relayout of " + win + ": focusMayChange=" + focusMayChange);
1713
1714 inTouchMode = mInTouchMode;
1715 }
1716
1717 if (newConfig != null) {
1718 sendNewConfiguration();
1719 }
1720
1721 Binder.restoreCallingIdentity(origId);
1722
1723 return (inTouchMode ? WindowManagerImpl.RELAYOUT_IN_TOUCH_MODE : 0)
1724 | (displayed ? WindowManagerImpl.RELAYOUT_FIRST_TIME : 0);
1725 }
1726
1727 public void finishDrawingWindow(Session session, IWindow client) {
1728 final long origId = Binder.clearCallingIdentity();
1729 synchronized(mWindowMap) {
1730 WindowState win = windowForClientLocked(session, client);
1731 if (win != null && win.finishDrawingLocked()) {
1732 mLayoutNeeded = true;
1733 performLayoutAndPlaceSurfacesLocked();
1734 }
1735 }
1736 Binder.restoreCallingIdentity(origId);
1737 }
1738
1739 private AttributeCache.Entry getCachedAnimations(WindowManager.LayoutParams lp) {
1740 if (DEBUG_ANIM) Log.v(TAG, "Loading animations: params package="
1741 + (lp != null ? lp.packageName : null)
1742 + " resId=0x" + (lp != null ? Integer.toHexString(lp.windowAnimations) : null));
1743 if (lp != null && lp.windowAnimations != 0) {
1744 // If this is a system resource, don't try to load it from the
1745 // application resources. It is nice to avoid loading application
1746 // resources if we can.
1747 String packageName = lp.packageName != null ? lp.packageName : "android";
1748 int resId = lp.windowAnimations;
1749 if ((resId&0xFF000000) == 0x01000000) {
1750 packageName = "android";
1751 }
1752 if (DEBUG_ANIM) Log.v(TAG, "Loading animations: picked package="
1753 + packageName);
1754 return AttributeCache.instance().get(packageName, resId,
1755 com.android.internal.R.styleable.WindowAnimation);
1756 }
1757 return null;
1758 }
1759
1760 private void applyEnterAnimationLocked(WindowState win) {
1761 int transit = WindowManagerPolicy.TRANSIT_SHOW;
1762 if (win.mEnterAnimationPending) {
1763 win.mEnterAnimationPending = false;
1764 transit = WindowManagerPolicy.TRANSIT_ENTER;
1765 }
1766
1767 applyAnimationLocked(win, transit, true);
1768 }
1769
1770 private boolean applyAnimationLocked(WindowState win,
1771 int transit, boolean isEntrance) {
1772 if (win.mLocalAnimating && win.mAnimationIsEntrance == isEntrance) {
1773 // If we are trying to apply an animation, but already running
1774 // an animation of the same type, then just leave that one alone.
1775 return true;
1776 }
1777
1778 // Only apply an animation if the display isn't frozen. If it is
1779 // frozen, there is no reason to animate and it can cause strange
1780 // artifacts when we unfreeze the display if some different animation
1781 // is running.
1782 if (!mDisplayFrozen) {
1783 int anim = mPolicy.selectAnimationLw(win, transit);
1784 int attr = -1;
1785 Animation a = null;
1786 if (anim != 0) {
1787 a = AnimationUtils.loadAnimation(mContext, anim);
1788 } else {
1789 switch (transit) {
1790 case WindowManagerPolicy.TRANSIT_ENTER:
1791 attr = com.android.internal.R.styleable.WindowAnimation_windowEnterAnimation;
1792 break;
1793 case WindowManagerPolicy.TRANSIT_EXIT:
1794 attr = com.android.internal.R.styleable.WindowAnimation_windowExitAnimation;
1795 break;
1796 case WindowManagerPolicy.TRANSIT_SHOW:
1797 attr = com.android.internal.R.styleable.WindowAnimation_windowShowAnimation;
1798 break;
1799 case WindowManagerPolicy.TRANSIT_HIDE:
1800 attr = com.android.internal.R.styleable.WindowAnimation_windowHideAnimation;
1801 break;
1802 }
1803 if (attr >= 0) {
1804 a = loadAnimation(win.mAttrs, attr);
1805 }
1806 }
1807 if (DEBUG_ANIM) Log.v(TAG, "applyAnimation: win=" + win
1808 + " anim=" + anim + " attr=0x" + Integer.toHexString(attr)
1809 + " mAnimation=" + win.mAnimation
1810 + " isEntrance=" + isEntrance);
1811 if (a != null) {
1812 if (DEBUG_ANIM) {
1813 RuntimeException e = new RuntimeException();
1814 e.fillInStackTrace();
1815 Log.v(TAG, "Loaded animation " + a + " for " + win, e);
1816 }
1817 win.setAnimation(a);
1818 win.mAnimationIsEntrance = isEntrance;
1819 }
1820 } else {
1821 win.clearAnimation();
1822 }
1823
1824 return win.mAnimation != null;
1825 }
1826
1827 private Animation loadAnimation(WindowManager.LayoutParams lp, int animAttr) {
1828 int anim = 0;
1829 Context context = mContext;
1830 if (animAttr >= 0) {
1831 AttributeCache.Entry ent = getCachedAnimations(lp);
1832 if (ent != null) {
1833 context = ent.context;
1834 anim = ent.array.getResourceId(animAttr, 0);
1835 }
1836 }
1837 if (anim != 0) {
1838 return AnimationUtils.loadAnimation(context, anim);
1839 }
1840 return null;
1841 }
1842
1843 private boolean applyAnimationLocked(AppWindowToken wtoken,
1844 WindowManager.LayoutParams lp, int transit, boolean enter) {
1845 // Only apply an animation if the display isn't frozen. If it is
1846 // frozen, there is no reason to animate and it can cause strange
1847 // artifacts when we unfreeze the display if some different animation
1848 // is running.
1849 if (!mDisplayFrozen) {
1850 int animAttr = 0;
1851 switch (transit) {
1852 case WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN:
1853 animAttr = enter
1854 ? com.android.internal.R.styleable.WindowAnimation_activityOpenEnterAnimation
1855 : com.android.internal.R.styleable.WindowAnimation_activityOpenExitAnimation;
1856 break;
1857 case WindowManagerPolicy.TRANSIT_ACTIVITY_CLOSE:
1858 animAttr = enter
1859 ? com.android.internal.R.styleable.WindowAnimation_activityCloseEnterAnimation
1860 : com.android.internal.R.styleable.WindowAnimation_activityCloseExitAnimation;
1861 break;
1862 case WindowManagerPolicy.TRANSIT_TASK_OPEN:
1863 animAttr = enter
1864 ? com.android.internal.R.styleable.WindowAnimation_taskOpenEnterAnimation
1865 : com.android.internal.R.styleable.WindowAnimation_taskOpenExitAnimation;
1866 break;
1867 case WindowManagerPolicy.TRANSIT_TASK_CLOSE:
1868 animAttr = enter
1869 ? com.android.internal.R.styleable.WindowAnimation_taskCloseEnterAnimation
1870 : com.android.internal.R.styleable.WindowAnimation_taskCloseExitAnimation;
1871 break;
1872 case WindowManagerPolicy.TRANSIT_TASK_TO_FRONT:
1873 animAttr = enter
1874 ? com.android.internal.R.styleable.WindowAnimation_taskToFrontEnterAnimation
1875 : com.android.internal.R.styleable.WindowAnimation_taskToFrontExitAnimation;
1876 break;
1877 case WindowManagerPolicy.TRANSIT_TASK_TO_BACK:
1878 animAttr = enter
1879 ? com.android.internal.R.styleable.WindowAnimation_taskToBackEnterAnimation
1880 : com.android.internal.R.styleable.WindowAnimation_taskToBackExitAnimation;
1881 break;
1882 }
1883 Animation a = loadAnimation(lp, animAttr);
1884 if (DEBUG_ANIM) Log.v(TAG, "applyAnimation: wtoken=" + wtoken
1885 + " anim=" + a
1886 + " animAttr=0x" + Integer.toHexString(animAttr)
1887 + " transit=" + transit);
1888 if (a != null) {
1889 if (DEBUG_ANIM) {
1890 RuntimeException e = new RuntimeException();
1891 e.fillInStackTrace();
1892 Log.v(TAG, "Loaded animation " + a + " for " + wtoken, e);
1893 }
1894 wtoken.setAnimation(a);
1895 }
1896 } else {
1897 wtoken.clearAnimation();
1898 }
1899
1900 return wtoken.animation != null;
1901 }
1902
1903 // -------------------------------------------------------------
1904 // Application Window Tokens
1905 // -------------------------------------------------------------
1906
1907 public void validateAppTokens(List tokens) {
1908 int v = tokens.size()-1;
1909 int m = mAppTokens.size()-1;
1910 while (v >= 0 && m >= 0) {
1911 AppWindowToken wtoken = mAppTokens.get(m);
1912 if (wtoken.removed) {
1913 m--;
1914 continue;
1915 }
1916 if (tokens.get(v) != wtoken.token) {
1917 Log.w(TAG, "Tokens out of sync: external is " + tokens.get(v)
1918 + " @ " + v + ", internal is " + wtoken.token + " @ " + m);
1919 }
1920 v--;
1921 m--;
1922 }
1923 while (v >= 0) {
1924 Log.w(TAG, "External token not found: " + tokens.get(v) + " @ " + v);
1925 v--;
1926 }
1927 while (m >= 0) {
1928 AppWindowToken wtoken = mAppTokens.get(m);
1929 if (!wtoken.removed) {
1930 Log.w(TAG, "Invalid internal token: " + wtoken.token + " @ " + m);
1931 }
1932 m--;
1933 }
1934 }
1935
1936 boolean checkCallingPermission(String permission, String func) {
1937 // Quick check: if the calling permission is me, it's all okay.
1938 if (Binder.getCallingPid() == Process.myPid()) {
1939 return true;
1940 }
1941
1942 if (mContext.checkCallingPermission(permission)
1943 == PackageManager.PERMISSION_GRANTED) {
1944 return true;
1945 }
1946 String msg = "Permission Denial: " + func + " from pid="
1947 + Binder.getCallingPid()
1948 + ", uid=" + Binder.getCallingUid()
1949 + " requires " + permission;
1950 Log.w(TAG, msg);
1951 return false;
1952 }
1953
1954 AppWindowToken findAppWindowToken(IBinder token) {
1955 WindowToken wtoken = mTokenMap.get(token);
1956 if (wtoken == null) {
1957 return null;
1958 }
1959 return wtoken.appWindowToken;
1960 }
1961
1962 public void addWindowToken(IBinder token, int type) {
1963 if (!checkCallingPermission(android.Manifest.permission.MANAGE_APP_TOKENS,
1964 "addWindowToken()")) {
1965 return;
1966 }
1967
1968 synchronized(mWindowMap) {
1969 WindowToken wtoken = mTokenMap.get(token);
1970 if (wtoken != null) {
1971 Log.w(TAG, "Attempted to add existing input method token: " + token);
1972 return;
1973 }
1974 wtoken = new WindowToken(token, type, true);
1975 mTokenMap.put(token, wtoken);
1976 mTokenList.add(wtoken);
1977 }
1978 }
1979
1980 public void removeWindowToken(IBinder token) {
1981 if (!checkCallingPermission(android.Manifest.permission.MANAGE_APP_TOKENS,
1982 "removeWindowToken()")) {
1983 return;
1984 }
1985
1986 final long origId = Binder.clearCallingIdentity();
1987 synchronized(mWindowMap) {
1988 WindowToken wtoken = mTokenMap.remove(token);
1989 mTokenList.remove(wtoken);
1990 if (wtoken != null) {
1991 boolean delayed = false;
1992 if (!wtoken.hidden) {
1993 wtoken.hidden = true;
1994
1995 final int N = wtoken.windows.size();
1996 boolean changed = false;
1997
1998 for (int i=0; i<N; i++) {
1999 WindowState win = wtoken.windows.get(i);
2000
2001 if (win.isAnimating()) {
2002 delayed = true;
2003 }
2004
2005 if (win.isVisibleNow()) {
2006 applyAnimationLocked(win,
2007 WindowManagerPolicy.TRANSIT_EXIT, false);
2008 mKeyWaiter.finishedKey(win.mSession, win.mClient, true,
2009 KeyWaiter.RETURN_NOTHING);
2010 changed = true;
2011 }
2012 }
2013
2014 if (changed) {
2015 mLayoutNeeded = true;
2016 performLayoutAndPlaceSurfacesLocked();
2017 updateFocusedWindowLocked(UPDATE_FOCUS_NORMAL);
2018 }
2019
2020 if (delayed) {
2021 mExitingTokens.add(wtoken);
2022 }
2023 }
2024
2025 } else {
2026 Log.w(TAG, "Attempted to remove non-existing token: " + token);
2027 }
2028 }
2029 Binder.restoreCallingIdentity(origId);
2030 }
2031
2032 public void addAppToken(int addPos, IApplicationToken token,
2033 int groupId, int requestedOrientation, boolean fullscreen) {
2034 if (!checkCallingPermission(android.Manifest.permission.MANAGE_APP_TOKENS,
2035 "addAppToken()")) {
2036 return;
2037 }
2038
2039 synchronized(mWindowMap) {
2040 AppWindowToken wtoken = findAppWindowToken(token.asBinder());
2041 if (wtoken != null) {
2042 Log.w(TAG, "Attempted to add existing app token: " + token);
2043 return;
2044 }
2045 wtoken = new AppWindowToken(token);
2046 wtoken.groupId = groupId;
2047 wtoken.appFullscreen = fullscreen;
2048 wtoken.requestedOrientation = requestedOrientation;
2049 mAppTokens.add(addPos, wtoken);
Dave Bortcfe65242009-04-09 14:51:04 -07002050 if (localLOGV) Log.v(TAG, "Adding new app token: " + wtoken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002051 mTokenMap.put(token.asBinder(), wtoken);
2052 mTokenList.add(wtoken);
2053
2054 // Application tokens start out hidden.
2055 wtoken.hidden = true;
2056 wtoken.hiddenRequested = true;
2057
2058 //dump();
2059 }
2060 }
2061
2062 public void setAppGroupId(IBinder token, int groupId) {
2063 if (!checkCallingPermission(android.Manifest.permission.MANAGE_APP_TOKENS,
2064 "setAppStartingIcon()")) {
2065 return;
2066 }
2067
2068 synchronized(mWindowMap) {
2069 AppWindowToken wtoken = findAppWindowToken(token);
2070 if (wtoken == null) {
2071 Log.w(TAG, "Attempted to set group id of non-existing app token: " + token);
2072 return;
2073 }
2074 wtoken.groupId = groupId;
2075 }
2076 }
2077
2078 public int getOrientationFromWindowsLocked() {
2079 int pos = mWindows.size() - 1;
2080 while (pos >= 0) {
2081 WindowState wtoken = (WindowState) mWindows.get(pos);
2082 pos--;
2083 if (wtoken.mAppToken != null) {
2084 // We hit an application window. so the orientation will be determined by the
2085 // app window. No point in continuing further.
2086 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
2087 }
2088 if (!wtoken.isVisibleLw()) {
2089 continue;
2090 }
2091 int req = wtoken.mAttrs.screenOrientation;
2092 if((req == ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED) ||
2093 (req == ActivityInfo.SCREEN_ORIENTATION_BEHIND)){
2094 continue;
2095 } else {
2096 return req;
2097 }
2098 }
2099 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
2100 }
2101
2102 public int getOrientationFromAppTokensLocked() {
2103 int pos = mAppTokens.size() - 1;
2104 int curGroup = 0;
2105 int lastOrientation = ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
Owen Lin3413b892009-05-01 17:12:32 -07002106 boolean findingBehind = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002107 boolean haveGroup = false;
The Android Open Source Project4df24232009-03-05 14:34:35 -08002108 boolean lastFullscreen = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002109 while (pos >= 0) {
2110 AppWindowToken wtoken = mAppTokens.get(pos);
2111 pos--;
Owen Lin3413b892009-05-01 17:12:32 -07002112 // if we're about to tear down this window and not seek for
2113 // the behind activity, don't use it for orientation
2114 if (!findingBehind
2115 && (!wtoken.hidden && wtoken.hiddenRequested)) {
The Android Open Source Project10592532009-03-18 17:39:46 -07002116 continue;
2117 }
2118
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002119 if (!haveGroup) {
2120 // We ignore any hidden applications on the top.
2121 if (wtoken.hiddenRequested || wtoken.willBeHidden) {
2122 continue;
2123 }
2124 haveGroup = true;
2125 curGroup = wtoken.groupId;
2126 lastOrientation = wtoken.requestedOrientation;
2127 } else if (curGroup != wtoken.groupId) {
2128 // If we have hit a new application group, and the bottom
2129 // of the previous group didn't explicitly say to use
The Android Open Source Project4df24232009-03-05 14:34:35 -08002130 // the orientation behind it, and the last app was
2131 // full screen, then we'll stick with the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002132 // user's orientation.
The Android Open Source Project4df24232009-03-05 14:34:35 -08002133 if (lastOrientation != ActivityInfo.SCREEN_ORIENTATION_BEHIND
2134 && lastFullscreen) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002135 return lastOrientation;
2136 }
2137 }
2138 int or = wtoken.requestedOrientation;
Owen Lin3413b892009-05-01 17:12:32 -07002139 // If this application is fullscreen, and didn't explicitly say
2140 // to use the orientation behind it, then just take whatever
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002141 // orientation it has and ignores whatever is under it.
The Android Open Source Project4df24232009-03-05 14:34:35 -08002142 lastFullscreen = wtoken.appFullscreen;
Owen Lin3413b892009-05-01 17:12:32 -07002143 if (lastFullscreen
2144 && or != ActivityInfo.SCREEN_ORIENTATION_BEHIND) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002145 return or;
2146 }
2147 // If this application has requested an explicit orientation,
2148 // then use it.
2149 if (or == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE ||
2150 or == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT ||
2151 or == ActivityInfo.SCREEN_ORIENTATION_SENSOR ||
2152 or == ActivityInfo.SCREEN_ORIENTATION_NOSENSOR ||
2153 or == ActivityInfo.SCREEN_ORIENTATION_USER) {
2154 return or;
2155 }
Owen Lin3413b892009-05-01 17:12:32 -07002156 findingBehind |= (or == ActivityInfo.SCREEN_ORIENTATION_BEHIND);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002157 }
2158 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
2159 }
2160
2161 public Configuration updateOrientationFromAppTokens(
The Android Open Source Project10592532009-03-18 17:39:46 -07002162 Configuration currentConfig, IBinder freezeThisOneIfNeeded) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002163 Configuration config;
2164 long ident = Binder.clearCallingIdentity();
2165 synchronized(mWindowMap) {
The Android Open Source Project10592532009-03-18 17:39:46 -07002166 config = updateOrientationFromAppTokensLocked(currentConfig, freezeThisOneIfNeeded);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002167 }
2168 if (config != null) {
2169 mLayoutNeeded = true;
2170 performLayoutAndPlaceSurfacesLocked();
2171 }
2172 Binder.restoreCallingIdentity(ident);
2173 return config;
2174 }
2175
2176 /*
2177 * The orientation is computed from non-application windows first. If none of
2178 * the non-application windows specify orientation, the orientation is computed from
2179 * application tokens.
2180 * @see android.view.IWindowManager#updateOrientationFromAppTokens(
2181 * android.os.IBinder)
2182 */
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07002183 Configuration updateOrientationFromAppTokensLocked(
The Android Open Source Project10592532009-03-18 17:39:46 -07002184 Configuration appConfig, IBinder freezeThisOneIfNeeded) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002185 boolean changed = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002186 long ident = Binder.clearCallingIdentity();
2187 try {
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07002188 int req = computeForcedAppOrientationLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002189
2190 if (req != mForcedAppOrientation) {
2191 changed = true;
2192 mForcedAppOrientation = req;
2193 //send a message to Policy indicating orientation change to take
2194 //action like disabling/enabling sensors etc.,
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07002195 mPolicy.setCurrentOrientationLw(req);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002196 }
2197
2198 if (changed) {
2199 changed = setRotationUncheckedLocked(
Dianne Hackborn321ae682009-03-27 16:16:03 -07002200 WindowManagerPolicy.USE_LAST_ROTATION,
2201 mLastRotationFlags & (~Surface.FLAGS_ORIENTATION_ANIMATION_DISABLE));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002202 if (changed) {
2203 if (freezeThisOneIfNeeded != null) {
2204 AppWindowToken wtoken = findAppWindowToken(
2205 freezeThisOneIfNeeded);
2206 if (wtoken != null) {
2207 startAppFreezingScreenLocked(wtoken,
2208 ActivityInfo.CONFIG_ORIENTATION);
2209 }
2210 }
Dianne Hackbornc485a602009-03-24 22:39:49 -07002211 return computeNewConfigurationLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002212 }
2213 }
The Android Open Source Project10592532009-03-18 17:39:46 -07002214
2215 // No obvious action we need to take, but if our current
2216 // state mismatches the activity maanager's, update it
2217 if (appConfig != null) {
Dianne Hackbornc485a602009-03-24 22:39:49 -07002218 mTempConfiguration.setToDefaults();
2219 if (computeNewConfigurationLocked(mTempConfiguration)) {
2220 if (appConfig.diff(mTempConfiguration) != 0) {
2221 Log.i(TAG, "Config changed: " + mTempConfiguration);
2222 return new Configuration(mTempConfiguration);
2223 }
The Android Open Source Project10592532009-03-18 17:39:46 -07002224 }
2225 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002226 } finally {
2227 Binder.restoreCallingIdentity(ident);
2228 }
2229
2230 return null;
2231 }
2232
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07002233 int computeForcedAppOrientationLocked() {
2234 int req = getOrientationFromWindowsLocked();
2235 if (req == ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED) {
2236 req = getOrientationFromAppTokensLocked();
2237 }
2238 return req;
2239 }
2240
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002241 public void setAppOrientation(IApplicationToken token, int requestedOrientation) {
2242 if (!checkCallingPermission(android.Manifest.permission.MANAGE_APP_TOKENS,
2243 "setAppOrientation()")) {
2244 return;
2245 }
2246
2247 synchronized(mWindowMap) {
2248 AppWindowToken wtoken = findAppWindowToken(token.asBinder());
2249 if (wtoken == null) {
2250 Log.w(TAG, "Attempted to set orientation of non-existing app token: " + token);
2251 return;
2252 }
2253
2254 wtoken.requestedOrientation = requestedOrientation;
2255 }
2256 }
2257
2258 public int getAppOrientation(IApplicationToken token) {
2259 synchronized(mWindowMap) {
2260 AppWindowToken wtoken = findAppWindowToken(token.asBinder());
2261 if (wtoken == null) {
2262 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
2263 }
2264
2265 return wtoken.requestedOrientation;
2266 }
2267 }
2268
2269 public void setFocusedApp(IBinder token, boolean moveFocusNow) {
2270 if (!checkCallingPermission(android.Manifest.permission.MANAGE_APP_TOKENS,
2271 "setFocusedApp()")) {
2272 return;
2273 }
2274
2275 synchronized(mWindowMap) {
2276 boolean changed = false;
2277 if (token == null) {
2278 if (DEBUG_FOCUS) Log.v(TAG, "Clearing focused app, was " + mFocusedApp);
2279 changed = mFocusedApp != null;
2280 mFocusedApp = null;
2281 mKeyWaiter.tickle();
2282 } else {
2283 AppWindowToken newFocus = findAppWindowToken(token);
2284 if (newFocus == null) {
2285 Log.w(TAG, "Attempted to set focus to non-existing app token: " + token);
2286 return;
2287 }
2288 changed = mFocusedApp != newFocus;
2289 mFocusedApp = newFocus;
2290 if (DEBUG_FOCUS) Log.v(TAG, "Set focused app to: " + mFocusedApp);
2291 mKeyWaiter.tickle();
2292 }
2293
2294 if (moveFocusNow && changed) {
2295 final long origId = Binder.clearCallingIdentity();
2296 updateFocusedWindowLocked(UPDATE_FOCUS_NORMAL);
2297 Binder.restoreCallingIdentity(origId);
2298 }
2299 }
2300 }
2301
2302 public void prepareAppTransition(int transit) {
2303 if (!checkCallingPermission(android.Manifest.permission.MANAGE_APP_TOKENS,
2304 "prepareAppTransition()")) {
2305 return;
2306 }
2307
2308 synchronized(mWindowMap) {
2309 if (DEBUG_APP_TRANSITIONS) Log.v(
2310 TAG, "Prepare app transition: transit=" + transit
2311 + " mNextAppTransition=" + mNextAppTransition);
2312 if (!mDisplayFrozen) {
2313 if (mNextAppTransition == WindowManagerPolicy.TRANSIT_NONE) {
2314 mNextAppTransition = transit;
2315 }
2316 mAppTransitionReady = false;
2317 mAppTransitionTimeout = false;
2318 mStartingIconInTransition = false;
2319 mSkipAppTransitionAnimation = false;
2320 mH.removeMessages(H.APP_TRANSITION_TIMEOUT);
2321 mH.sendMessageDelayed(mH.obtainMessage(H.APP_TRANSITION_TIMEOUT),
2322 5000);
2323 }
2324 }
2325 }
2326
2327 public int getPendingAppTransition() {
2328 return mNextAppTransition;
2329 }
2330
2331 public void executeAppTransition() {
2332 if (!checkCallingPermission(android.Manifest.permission.MANAGE_APP_TOKENS,
2333 "executeAppTransition()")) {
2334 return;
2335 }
2336
2337 synchronized(mWindowMap) {
2338 if (DEBUG_APP_TRANSITIONS) Log.v(
2339 TAG, "Execute app transition: mNextAppTransition=" + mNextAppTransition);
2340 if (mNextAppTransition != WindowManagerPolicy.TRANSIT_NONE) {
2341 mAppTransitionReady = true;
2342 final long origId = Binder.clearCallingIdentity();
2343 performLayoutAndPlaceSurfacesLocked();
2344 Binder.restoreCallingIdentity(origId);
2345 }
2346 }
2347 }
2348
2349 public void setAppStartingWindow(IBinder token, String pkg,
2350 int theme, CharSequence nonLocalizedLabel, int labelRes, int icon,
2351 IBinder transferFrom, boolean createIfNeeded) {
2352 if (!checkCallingPermission(android.Manifest.permission.MANAGE_APP_TOKENS,
2353 "setAppStartingIcon()")) {
2354 return;
2355 }
2356
2357 synchronized(mWindowMap) {
2358 if (DEBUG_STARTING_WINDOW) Log.v(
2359 TAG, "setAppStartingIcon: token=" + token + " pkg=" + pkg
2360 + " transferFrom=" + transferFrom);
2361
2362 AppWindowToken wtoken = findAppWindowToken(token);
2363 if (wtoken == null) {
2364 Log.w(TAG, "Attempted to set icon of non-existing app token: " + token);
2365 return;
2366 }
2367
2368 // If the display is frozen, we won't do anything until the
2369 // actual window is displayed so there is no reason to put in
2370 // the starting window.
2371 if (mDisplayFrozen) {
2372 return;
2373 }
2374
2375 if (wtoken.startingData != null) {
2376 return;
2377 }
2378
2379 if (transferFrom != null) {
2380 AppWindowToken ttoken = findAppWindowToken(transferFrom);
2381 if (ttoken != null) {
2382 WindowState startingWindow = ttoken.startingWindow;
2383 if (startingWindow != null) {
2384 if (mStartingIconInTransition) {
2385 // In this case, the starting icon has already
2386 // been displayed, so start letting windows get
2387 // shown immediately without any more transitions.
2388 mSkipAppTransitionAnimation = true;
2389 }
2390 if (DEBUG_STARTING_WINDOW) Log.v(TAG,
2391 "Moving existing starting from " + ttoken
2392 + " to " + wtoken);
2393 final long origId = Binder.clearCallingIdentity();
2394
2395 // Transfer the starting window over to the new
2396 // token.
2397 wtoken.startingData = ttoken.startingData;
2398 wtoken.startingView = ttoken.startingView;
2399 wtoken.startingWindow = startingWindow;
2400 ttoken.startingData = null;
2401 ttoken.startingView = null;
2402 ttoken.startingWindow = null;
2403 ttoken.startingMoved = true;
2404 startingWindow.mToken = wtoken;
Dianne Hackbornef49c572009-03-24 19:27:32 -07002405 startingWindow.mRootToken = wtoken;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002406 startingWindow.mAppToken = wtoken;
2407 mWindows.remove(startingWindow);
2408 ttoken.windows.remove(startingWindow);
2409 ttoken.allAppWindows.remove(startingWindow);
2410 addWindowToListInOrderLocked(startingWindow, true);
2411 wtoken.allAppWindows.add(startingWindow);
2412
2413 // Propagate other interesting state between the
2414 // tokens. If the old token is displayed, we should
2415 // immediately force the new one to be displayed. If
2416 // it is animating, we need to move that animation to
2417 // the new one.
2418 if (ttoken.allDrawn) {
2419 wtoken.allDrawn = true;
2420 }
2421 if (ttoken.firstWindowDrawn) {
2422 wtoken.firstWindowDrawn = true;
2423 }
2424 if (!ttoken.hidden) {
2425 wtoken.hidden = false;
2426 wtoken.hiddenRequested = false;
2427 wtoken.willBeHidden = false;
2428 }
2429 if (wtoken.clientHidden != ttoken.clientHidden) {
2430 wtoken.clientHidden = ttoken.clientHidden;
2431 wtoken.sendAppVisibilityToClients();
2432 }
2433 if (ttoken.animation != null) {
2434 wtoken.animation = ttoken.animation;
2435 wtoken.animating = ttoken.animating;
2436 wtoken.animLayerAdjustment = ttoken.animLayerAdjustment;
2437 ttoken.animation = null;
2438 ttoken.animLayerAdjustment = 0;
2439 wtoken.updateLayers();
2440 ttoken.updateLayers();
2441 }
2442
2443 updateFocusedWindowLocked(UPDATE_FOCUS_WILL_PLACE_SURFACES);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002444 mLayoutNeeded = true;
2445 performLayoutAndPlaceSurfacesLocked();
2446 Binder.restoreCallingIdentity(origId);
2447 return;
2448 } else if (ttoken.startingData != null) {
2449 // The previous app was getting ready to show a
2450 // starting window, but hasn't yet done so. Steal it!
2451 if (DEBUG_STARTING_WINDOW) Log.v(TAG,
2452 "Moving pending starting from " + ttoken
2453 + " to " + wtoken);
2454 wtoken.startingData = ttoken.startingData;
2455 ttoken.startingData = null;
2456 ttoken.startingMoved = true;
2457 Message m = mH.obtainMessage(H.ADD_STARTING, wtoken);
2458 // Note: we really want to do sendMessageAtFrontOfQueue() because we
2459 // want to process the message ASAP, before any other queued
2460 // messages.
2461 mH.sendMessageAtFrontOfQueue(m);
2462 return;
2463 }
2464 }
2465 }
2466
2467 // There is no existing starting window, and the caller doesn't
2468 // want us to create one, so that's it!
2469 if (!createIfNeeded) {
2470 return;
2471 }
2472
2473 mStartingIconInTransition = true;
2474 wtoken.startingData = new StartingData(
2475 pkg, theme, nonLocalizedLabel,
2476 labelRes, icon);
2477 Message m = mH.obtainMessage(H.ADD_STARTING, wtoken);
2478 // Note: we really want to do sendMessageAtFrontOfQueue() because we
2479 // want to process the message ASAP, before any other queued
2480 // messages.
2481 mH.sendMessageAtFrontOfQueue(m);
2482 }
2483 }
2484
2485 public void setAppWillBeHidden(IBinder token) {
2486 if (!checkCallingPermission(android.Manifest.permission.MANAGE_APP_TOKENS,
2487 "setAppWillBeHidden()")) {
2488 return;
2489 }
2490
2491 AppWindowToken wtoken;
2492
2493 synchronized(mWindowMap) {
2494 wtoken = findAppWindowToken(token);
2495 if (wtoken == null) {
2496 Log.w(TAG, "Attempted to set will be hidden of non-existing app token: " + token);
2497 return;
2498 }
2499 wtoken.willBeHidden = true;
2500 }
2501 }
2502
2503 boolean setTokenVisibilityLocked(AppWindowToken wtoken, WindowManager.LayoutParams lp,
2504 boolean visible, int transit, boolean performLayout) {
2505 boolean delayed = false;
2506
2507 if (wtoken.clientHidden == visible) {
2508 wtoken.clientHidden = !visible;
2509 wtoken.sendAppVisibilityToClients();
2510 }
2511
2512 wtoken.willBeHidden = false;
2513 if (wtoken.hidden == visible) {
2514 final int N = wtoken.allAppWindows.size();
2515 boolean changed = false;
2516 if (DEBUG_APP_TRANSITIONS) Log.v(
2517 TAG, "Changing app " + wtoken + " hidden=" + wtoken.hidden
2518 + " performLayout=" + performLayout);
2519
2520 boolean runningAppAnimation = false;
2521
2522 if (transit != WindowManagerPolicy.TRANSIT_NONE) {
2523 if (wtoken.animation == sDummyAnimation) {
2524 wtoken.animation = null;
2525 }
2526 applyAnimationLocked(wtoken, lp, transit, visible);
2527 changed = true;
2528 if (wtoken.animation != null) {
2529 delayed = runningAppAnimation = true;
2530 }
2531 }
2532
2533 for (int i=0; i<N; i++) {
2534 WindowState win = wtoken.allAppWindows.get(i);
2535 if (win == wtoken.startingWindow) {
2536 continue;
2537 }
2538
2539 if (win.isAnimating()) {
2540 delayed = true;
2541 }
2542
2543 //Log.i(TAG, "Window " + win + ": vis=" + win.isVisible());
2544 //win.dump(" ");
2545 if (visible) {
2546 if (!win.isVisibleNow()) {
2547 if (!runningAppAnimation) {
2548 applyAnimationLocked(win,
2549 WindowManagerPolicy.TRANSIT_ENTER, true);
2550 }
2551 changed = true;
2552 }
2553 } else if (win.isVisibleNow()) {
2554 if (!runningAppAnimation) {
2555 applyAnimationLocked(win,
2556 WindowManagerPolicy.TRANSIT_EXIT, false);
2557 }
2558 mKeyWaiter.finishedKey(win.mSession, win.mClient, true,
2559 KeyWaiter.RETURN_NOTHING);
2560 changed = true;
2561 }
2562 }
2563
2564 wtoken.hidden = wtoken.hiddenRequested = !visible;
2565 if (!visible) {
2566 unsetAppFreezingScreenLocked(wtoken, true, true);
2567 } else {
2568 // If we are being set visible, and the starting window is
2569 // not yet displayed, then make sure it doesn't get displayed.
2570 WindowState swin = wtoken.startingWindow;
2571 if (swin != null && (swin.mDrawPending
2572 || swin.mCommitDrawPending)) {
2573 swin.mPolicyVisibility = false;
2574 swin.mPolicyVisibilityAfterAnim = false;
2575 }
2576 }
2577
2578 if (DEBUG_APP_TRANSITIONS) Log.v(TAG, "setTokenVisibilityLocked: " + wtoken
2579 + ": hidden=" + wtoken.hidden + " hiddenRequested="
2580 + wtoken.hiddenRequested);
2581
2582 if (changed && performLayout) {
2583 mLayoutNeeded = true;
2584 updateFocusedWindowLocked(UPDATE_FOCUS_WILL_PLACE_SURFACES);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002585 performLayoutAndPlaceSurfacesLocked();
2586 }
2587 }
2588
2589 if (wtoken.animation != null) {
2590 delayed = true;
2591 }
2592
2593 return delayed;
2594 }
2595
2596 public void setAppVisibility(IBinder token, boolean visible) {
2597 if (!checkCallingPermission(android.Manifest.permission.MANAGE_APP_TOKENS,
2598 "setAppVisibility()")) {
2599 return;
2600 }
2601
2602 AppWindowToken wtoken;
2603
2604 synchronized(mWindowMap) {
2605 wtoken = findAppWindowToken(token);
2606 if (wtoken == null) {
2607 Log.w(TAG, "Attempted to set visibility of non-existing app token: " + token);
2608 return;
2609 }
2610
2611 if (DEBUG_APP_TRANSITIONS || DEBUG_ORIENTATION) {
2612 RuntimeException e = new RuntimeException();
2613 e.fillInStackTrace();
2614 Log.v(TAG, "setAppVisibility(" + token + ", " + visible
2615 + "): mNextAppTransition=" + mNextAppTransition
2616 + " hidden=" + wtoken.hidden
2617 + " hiddenRequested=" + wtoken.hiddenRequested, e);
2618 }
2619
2620 // If we are preparing an app transition, then delay changing
2621 // the visibility of this token until we execute that transition.
2622 if (!mDisplayFrozen && mNextAppTransition != WindowManagerPolicy.TRANSIT_NONE) {
2623 // Already in requested state, don't do anything more.
2624 if (wtoken.hiddenRequested != visible) {
2625 return;
2626 }
2627 wtoken.hiddenRequested = !visible;
2628
2629 if (DEBUG_APP_TRANSITIONS) Log.v(
2630 TAG, "Setting dummy animation on: " + wtoken);
2631 wtoken.setDummyAnimation();
2632 mOpeningApps.remove(wtoken);
2633 mClosingApps.remove(wtoken);
2634 wtoken.inPendingTransaction = true;
2635 if (visible) {
2636 mOpeningApps.add(wtoken);
2637 wtoken.allDrawn = false;
2638 wtoken.startingDisplayed = false;
2639 wtoken.startingMoved = false;
2640
2641 if (wtoken.clientHidden) {
2642 // In the case where we are making an app visible
2643 // but holding off for a transition, we still need
2644 // to tell the client to make its windows visible so
2645 // they get drawn. Otherwise, we will wait on
2646 // performing the transition until all windows have
2647 // been drawn, they never will be, and we are sad.
2648 wtoken.clientHidden = false;
2649 wtoken.sendAppVisibilityToClients();
2650 }
2651 } else {
2652 mClosingApps.add(wtoken);
2653 }
2654 return;
2655 }
2656
2657 final long origId = Binder.clearCallingIdentity();
2658 setTokenVisibilityLocked(wtoken, null, visible, WindowManagerPolicy.TRANSIT_NONE, true);
2659 wtoken.updateReportedVisibilityLocked();
2660 Binder.restoreCallingIdentity(origId);
2661 }
2662 }
2663
2664 void unsetAppFreezingScreenLocked(AppWindowToken wtoken,
2665 boolean unfreezeSurfaceNow, boolean force) {
2666 if (wtoken.freezingScreen) {
2667 if (DEBUG_ORIENTATION) Log.v(TAG, "Clear freezing of " + wtoken
2668 + " force=" + force);
2669 final int N = wtoken.allAppWindows.size();
2670 boolean unfrozeWindows = false;
2671 for (int i=0; i<N; i++) {
2672 WindowState w = wtoken.allAppWindows.get(i);
2673 if (w.mAppFreezing) {
2674 w.mAppFreezing = false;
2675 if (w.mSurface != null && !w.mOrientationChanging) {
2676 w.mOrientationChanging = true;
2677 }
2678 unfrozeWindows = true;
2679 }
2680 }
2681 if (force || unfrozeWindows) {
2682 if (DEBUG_ORIENTATION) Log.v(TAG, "No longer freezing: " + wtoken);
2683 wtoken.freezingScreen = false;
2684 mAppsFreezingScreen--;
2685 }
2686 if (unfreezeSurfaceNow) {
2687 if (unfrozeWindows) {
2688 mLayoutNeeded = true;
2689 performLayoutAndPlaceSurfacesLocked();
2690 }
2691 if (mAppsFreezingScreen == 0 && !mWindowsFreezingScreen) {
2692 stopFreezingDisplayLocked();
2693 }
2694 }
2695 }
2696 }
2697
2698 public void startAppFreezingScreenLocked(AppWindowToken wtoken,
2699 int configChanges) {
2700 if (DEBUG_ORIENTATION) {
2701 RuntimeException e = new RuntimeException();
2702 e.fillInStackTrace();
2703 Log.i(TAG, "Set freezing of " + wtoken.appToken
2704 + ": hidden=" + wtoken.hidden + " freezing="
2705 + wtoken.freezingScreen, e);
2706 }
2707 if (!wtoken.hiddenRequested) {
2708 if (!wtoken.freezingScreen) {
2709 wtoken.freezingScreen = true;
2710 mAppsFreezingScreen++;
2711 if (mAppsFreezingScreen == 1) {
2712 startFreezingDisplayLocked();
2713 mH.removeMessages(H.APP_FREEZE_TIMEOUT);
2714 mH.sendMessageDelayed(mH.obtainMessage(H.APP_FREEZE_TIMEOUT),
2715 5000);
2716 }
2717 }
2718 final int N = wtoken.allAppWindows.size();
2719 for (int i=0; i<N; i++) {
2720 WindowState w = wtoken.allAppWindows.get(i);
2721 w.mAppFreezing = true;
2722 }
2723 }
2724 }
2725
2726 public void startAppFreezingScreen(IBinder token, int configChanges) {
2727 if (!checkCallingPermission(android.Manifest.permission.MANAGE_APP_TOKENS,
2728 "setAppFreezingScreen()")) {
2729 return;
2730 }
2731
2732 synchronized(mWindowMap) {
2733 if (configChanges == 0 && !mDisplayFrozen) {
2734 if (DEBUG_ORIENTATION) Log.v(TAG, "Skipping set freeze of " + token);
2735 return;
2736 }
2737
2738 AppWindowToken wtoken = findAppWindowToken(token);
2739 if (wtoken == null || wtoken.appToken == null) {
2740 Log.w(TAG, "Attempted to freeze screen with non-existing app token: " + wtoken);
2741 return;
2742 }
2743 final long origId = Binder.clearCallingIdentity();
2744 startAppFreezingScreenLocked(wtoken, configChanges);
2745 Binder.restoreCallingIdentity(origId);
2746 }
2747 }
2748
2749 public void stopAppFreezingScreen(IBinder token, boolean force) {
2750 if (!checkCallingPermission(android.Manifest.permission.MANAGE_APP_TOKENS,
2751 "setAppFreezingScreen()")) {
2752 return;
2753 }
2754
2755 synchronized(mWindowMap) {
2756 AppWindowToken wtoken = findAppWindowToken(token);
2757 if (wtoken == null || wtoken.appToken == null) {
2758 return;
2759 }
2760 final long origId = Binder.clearCallingIdentity();
2761 if (DEBUG_ORIENTATION) Log.v(TAG, "Clear freezing of " + token
2762 + ": hidden=" + wtoken.hidden + " freezing=" + wtoken.freezingScreen);
2763 unsetAppFreezingScreenLocked(wtoken, true, force);
2764 Binder.restoreCallingIdentity(origId);
2765 }
2766 }
2767
2768 public void removeAppToken(IBinder token) {
2769 if (!checkCallingPermission(android.Manifest.permission.MANAGE_APP_TOKENS,
2770 "removeAppToken()")) {
2771 return;
2772 }
2773
2774 AppWindowToken wtoken = null;
2775 AppWindowToken startingToken = null;
2776 boolean delayed = false;
2777
2778 final long origId = Binder.clearCallingIdentity();
2779 synchronized(mWindowMap) {
2780 WindowToken basewtoken = mTokenMap.remove(token);
2781 mTokenList.remove(basewtoken);
2782 if (basewtoken != null && (wtoken=basewtoken.appWindowToken) != null) {
2783 if (DEBUG_APP_TRANSITIONS) Log.v(TAG, "Removing app token: " + wtoken);
2784 delayed = setTokenVisibilityLocked(wtoken, null, false, WindowManagerPolicy.TRANSIT_NONE, true);
2785 wtoken.inPendingTransaction = false;
2786 mOpeningApps.remove(wtoken);
2787 if (mClosingApps.contains(wtoken)) {
2788 delayed = true;
2789 } else if (mNextAppTransition != WindowManagerPolicy.TRANSIT_NONE) {
2790 mClosingApps.add(wtoken);
2791 delayed = true;
2792 }
2793 if (DEBUG_APP_TRANSITIONS) Log.v(
2794 TAG, "Removing app " + wtoken + " delayed=" + delayed
2795 + " animation=" + wtoken.animation
2796 + " animating=" + wtoken.animating);
2797 if (delayed) {
2798 // set the token aside because it has an active animation to be finished
2799 mExitingAppTokens.add(wtoken);
2800 }
2801 mAppTokens.remove(wtoken);
2802 wtoken.removed = true;
2803 if (wtoken.startingData != null) {
2804 startingToken = wtoken;
2805 }
2806 unsetAppFreezingScreenLocked(wtoken, true, true);
2807 if (mFocusedApp == wtoken) {
2808 if (DEBUG_FOCUS) Log.v(TAG, "Removing focused app token:" + wtoken);
2809 mFocusedApp = null;
2810 updateFocusedWindowLocked(UPDATE_FOCUS_NORMAL);
2811 mKeyWaiter.tickle();
2812 }
2813 } else {
2814 Log.w(TAG, "Attempted to remove non-existing app token: " + token);
2815 }
2816
2817 if (!delayed && wtoken != null) {
2818 wtoken.updateReportedVisibilityLocked();
2819 }
2820 }
2821 Binder.restoreCallingIdentity(origId);
2822
2823 if (startingToken != null) {
2824 if (DEBUG_STARTING_WINDOW) Log.v(TAG, "Schedule remove starting "
2825 + startingToken + ": app token removed");
2826 Message m = mH.obtainMessage(H.REMOVE_STARTING, startingToken);
2827 mH.sendMessage(m);
2828 }
2829 }
2830
2831 private boolean tmpRemoveAppWindowsLocked(WindowToken token) {
2832 final int NW = token.windows.size();
2833 for (int i=0; i<NW; i++) {
2834 WindowState win = token.windows.get(i);
2835 mWindows.remove(win);
2836 int j = win.mChildWindows.size();
2837 while (j > 0) {
2838 j--;
2839 mWindows.remove(win.mChildWindows.get(j));
2840 }
2841 }
2842 return NW > 0;
2843 }
2844
2845 void dumpAppTokensLocked() {
2846 for (int i=mAppTokens.size()-1; i>=0; i--) {
2847 Log.v(TAG, " #" + i + ": " + mAppTokens.get(i).token);
2848 }
2849 }
2850
2851 void dumpWindowsLocked() {
2852 for (int i=mWindows.size()-1; i>=0; i--) {
2853 Log.v(TAG, " #" + i + ": " + mWindows.get(i));
2854 }
2855 }
2856
2857 private int findWindowOffsetLocked(int tokenPos) {
2858 final int NW = mWindows.size();
2859
2860 if (tokenPos >= mAppTokens.size()) {
2861 int i = NW;
2862 while (i > 0) {
2863 i--;
2864 WindowState win = (WindowState)mWindows.get(i);
2865 if (win.getAppToken() != null) {
2866 return i+1;
2867 }
2868 }
2869 }
2870
2871 while (tokenPos > 0) {
2872 // Find the first app token below the new position that has
2873 // a window displayed.
2874 final AppWindowToken wtoken = mAppTokens.get(tokenPos-1);
2875 if (DEBUG_REORDER) Log.v(TAG, "Looking for lower windows @ "
2876 + tokenPos + " -- " + wtoken.token);
2877 int i = wtoken.windows.size();
2878 while (i > 0) {
2879 i--;
2880 WindowState win = wtoken.windows.get(i);
2881 int j = win.mChildWindows.size();
2882 while (j > 0) {
2883 j--;
2884 WindowState cwin = (WindowState)win.mChildWindows.get(j);
2885 if (cwin.mSubLayer >= 0 ) {
2886 for (int pos=NW-1; pos>=0; pos--) {
2887 if (mWindows.get(pos) == cwin) {
2888 if (DEBUG_REORDER) Log.v(TAG,
2889 "Found child win @" + (pos+1));
2890 return pos+1;
2891 }
2892 }
2893 }
2894 }
2895 for (int pos=NW-1; pos>=0; pos--) {
2896 if (mWindows.get(pos) == win) {
2897 if (DEBUG_REORDER) Log.v(TAG, "Found win @" + (pos+1));
2898 return pos+1;
2899 }
2900 }
2901 }
2902 tokenPos--;
2903 }
2904
2905 return 0;
2906 }
2907
2908 private final int reAddWindowLocked(int index, WindowState win) {
2909 final int NCW = win.mChildWindows.size();
2910 boolean added = false;
2911 for (int j=0; j<NCW; j++) {
2912 WindowState cwin = (WindowState)win.mChildWindows.get(j);
2913 if (!added && cwin.mSubLayer >= 0) {
2914 mWindows.add(index, win);
2915 index++;
2916 added = true;
2917 }
2918 mWindows.add(index, cwin);
2919 index++;
2920 }
2921 if (!added) {
2922 mWindows.add(index, win);
2923 index++;
2924 }
2925 return index;
2926 }
2927
2928 private final int reAddAppWindowsLocked(int index, WindowToken token) {
2929 final int NW = token.windows.size();
2930 for (int i=0; i<NW; i++) {
2931 index = reAddWindowLocked(index, token.windows.get(i));
2932 }
2933 return index;
2934 }
2935
2936 public void moveAppToken(int index, IBinder token) {
2937 if (!checkCallingPermission(android.Manifest.permission.MANAGE_APP_TOKENS,
2938 "moveAppToken()")) {
2939 return;
2940 }
2941
2942 synchronized(mWindowMap) {
2943 if (DEBUG_REORDER) Log.v(TAG, "Initial app tokens:");
2944 if (DEBUG_REORDER) dumpAppTokensLocked();
2945 final AppWindowToken wtoken = findAppWindowToken(token);
2946 if (wtoken == null || !mAppTokens.remove(wtoken)) {
2947 Log.w(TAG, "Attempting to reorder token that doesn't exist: "
2948 + token + " (" + wtoken + ")");
2949 return;
2950 }
2951 mAppTokens.add(index, wtoken);
2952 if (DEBUG_REORDER) Log.v(TAG, "Moved " + token + " to " + index + ":");
2953 if (DEBUG_REORDER) dumpAppTokensLocked();
2954
2955 final long origId = Binder.clearCallingIdentity();
2956 if (DEBUG_REORDER) Log.v(TAG, "Removing windows in " + token + ":");
2957 if (DEBUG_REORDER) dumpWindowsLocked();
2958 if (tmpRemoveAppWindowsLocked(wtoken)) {
2959 if (DEBUG_REORDER) Log.v(TAG, "Adding windows back in:");
2960 if (DEBUG_REORDER) dumpWindowsLocked();
2961 reAddAppWindowsLocked(findWindowOffsetLocked(index), wtoken);
2962 if (DEBUG_REORDER) Log.v(TAG, "Final window list:");
2963 if (DEBUG_REORDER) dumpWindowsLocked();
2964 updateFocusedWindowLocked(UPDATE_FOCUS_WILL_PLACE_SURFACES);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002965 mLayoutNeeded = true;
2966 performLayoutAndPlaceSurfacesLocked();
2967 }
2968 Binder.restoreCallingIdentity(origId);
2969 }
2970 }
2971
2972 private void removeAppTokensLocked(List<IBinder> tokens) {
2973 // XXX This should be done more efficiently!
2974 // (take advantage of the fact that both lists should be
2975 // ordered in the same way.)
2976 int N = tokens.size();
2977 for (int i=0; i<N; i++) {
2978 IBinder token = tokens.get(i);
2979 final AppWindowToken wtoken = findAppWindowToken(token);
2980 if (!mAppTokens.remove(wtoken)) {
2981 Log.w(TAG, "Attempting to reorder token that doesn't exist: "
2982 + token + " (" + wtoken + ")");
2983 i--;
2984 N--;
2985 }
2986 }
2987 }
2988
2989 private void moveAppWindowsLocked(List<IBinder> tokens, int tokenPos) {
2990 // First remove all of the windows from the list.
2991 final int N = tokens.size();
2992 int i;
2993 for (i=0; i<N; i++) {
2994 WindowToken token = mTokenMap.get(tokens.get(i));
2995 if (token != null) {
2996 tmpRemoveAppWindowsLocked(token);
2997 }
2998 }
2999
3000 // Where to start adding?
3001 int pos = findWindowOffsetLocked(tokenPos);
3002
3003 // And now add them back at the correct place.
3004 for (i=0; i<N; i++) {
3005 WindowToken token = mTokenMap.get(tokens.get(i));
3006 if (token != null) {
3007 pos = reAddAppWindowsLocked(pos, token);
3008 }
3009 }
3010
3011 updateFocusedWindowLocked(UPDATE_FOCUS_WILL_PLACE_SURFACES);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003012 mLayoutNeeded = true;
3013 performLayoutAndPlaceSurfacesLocked();
3014
3015 //dump();
3016 }
3017
3018 public void moveAppTokensToTop(List<IBinder> tokens) {
3019 if (!checkCallingPermission(android.Manifest.permission.MANAGE_APP_TOKENS,
3020 "moveAppTokensToTop()")) {
3021 return;
3022 }
3023
3024 final long origId = Binder.clearCallingIdentity();
3025 synchronized(mWindowMap) {
3026 removeAppTokensLocked(tokens);
3027 final int N = tokens.size();
3028 for (int i=0; i<N; i++) {
3029 AppWindowToken wt = findAppWindowToken(tokens.get(i));
3030 if (wt != null) {
3031 mAppTokens.add(wt);
3032 }
3033 }
3034 moveAppWindowsLocked(tokens, mAppTokens.size());
3035 }
3036 Binder.restoreCallingIdentity(origId);
3037 }
3038
3039 public void moveAppTokensToBottom(List<IBinder> tokens) {
3040 if (!checkCallingPermission(android.Manifest.permission.MANAGE_APP_TOKENS,
3041 "moveAppTokensToBottom()")) {
3042 return;
3043 }
3044
3045 final long origId = Binder.clearCallingIdentity();
3046 synchronized(mWindowMap) {
3047 removeAppTokensLocked(tokens);
3048 final int N = tokens.size();
3049 int pos = 0;
3050 for (int i=0; i<N; i++) {
3051 AppWindowToken wt = findAppWindowToken(tokens.get(i));
3052 if (wt != null) {
3053 mAppTokens.add(pos, wt);
3054 pos++;
3055 }
3056 }
3057 moveAppWindowsLocked(tokens, 0);
3058 }
3059 Binder.restoreCallingIdentity(origId);
3060 }
3061
3062 // -------------------------------------------------------------
3063 // Misc IWindowSession methods
3064 // -------------------------------------------------------------
3065
3066 public void disableKeyguard(IBinder token, String tag) {
3067 if (mContext.checkCallingPermission(android.Manifest.permission.DISABLE_KEYGUARD)
3068 != PackageManager.PERMISSION_GRANTED) {
3069 throw new SecurityException("Requires DISABLE_KEYGUARD permission");
3070 }
3071 mKeyguardDisabled.acquire(token, tag);
3072 }
3073
3074 public void reenableKeyguard(IBinder token) {
3075 if (mContext.checkCallingPermission(android.Manifest.permission.DISABLE_KEYGUARD)
3076 != PackageManager.PERMISSION_GRANTED) {
3077 throw new SecurityException("Requires DISABLE_KEYGUARD permission");
3078 }
3079 synchronized (mKeyguardDisabled) {
3080 mKeyguardDisabled.release(token);
3081
3082 if (!mKeyguardDisabled.isAcquired()) {
3083 // if we are the last one to reenable the keyguard wait until
3084 // we have actaully finished reenabling until returning
3085 mWaitingUntilKeyguardReenabled = true;
3086 while (mWaitingUntilKeyguardReenabled) {
3087 try {
3088 mKeyguardDisabled.wait();
3089 } catch (InterruptedException e) {
3090 Thread.currentThread().interrupt();
3091 }
3092 }
3093 }
3094 }
3095 }
3096
3097 /**
3098 * @see android.app.KeyguardManager#exitKeyguardSecurely
3099 */
3100 public void exitKeyguardSecurely(final IOnKeyguardExitResult callback) {
3101 if (mContext.checkCallingPermission(android.Manifest.permission.DISABLE_KEYGUARD)
3102 != PackageManager.PERMISSION_GRANTED) {
3103 throw new SecurityException("Requires DISABLE_KEYGUARD permission");
3104 }
3105 mPolicy.exitKeyguardSecurely(new WindowManagerPolicy.OnKeyguardExitResult() {
3106 public void onKeyguardExitResult(boolean success) {
3107 try {
3108 callback.onKeyguardExitResult(success);
3109 } catch (RemoteException e) {
3110 // Client has died, we don't care.
3111 }
3112 }
3113 });
3114 }
3115
3116 public boolean inKeyguardRestrictedInputMode() {
3117 return mPolicy.inKeyguardRestrictedKeyInputMode();
3118 }
3119
3120 static float fixScale(float scale) {
3121 if (scale < 0) scale = 0;
3122 else if (scale > 20) scale = 20;
3123 return Math.abs(scale);
3124 }
3125
3126 public void setAnimationScale(int which, float scale) {
3127 if (!checkCallingPermission(android.Manifest.permission.SET_ANIMATION_SCALE,
3128 "setAnimationScale()")) {
3129 return;
3130 }
3131
3132 if (scale < 0) scale = 0;
3133 else if (scale > 20) scale = 20;
3134 scale = Math.abs(scale);
3135 switch (which) {
3136 case 0: mWindowAnimationScale = fixScale(scale); break;
3137 case 1: mTransitionAnimationScale = fixScale(scale); break;
3138 }
3139
3140 // Persist setting
3141 mH.obtainMessage(H.PERSIST_ANIMATION_SCALE).sendToTarget();
3142 }
3143
3144 public void setAnimationScales(float[] scales) {
3145 if (!checkCallingPermission(android.Manifest.permission.SET_ANIMATION_SCALE,
3146 "setAnimationScale()")) {
3147 return;
3148 }
3149
3150 if (scales != null) {
3151 if (scales.length >= 1) {
3152 mWindowAnimationScale = fixScale(scales[0]);
3153 }
3154 if (scales.length >= 2) {
3155 mTransitionAnimationScale = fixScale(scales[1]);
3156 }
3157 }
3158
3159 // Persist setting
3160 mH.obtainMessage(H.PERSIST_ANIMATION_SCALE).sendToTarget();
3161 }
3162
3163 public float getAnimationScale(int which) {
3164 switch (which) {
3165 case 0: return mWindowAnimationScale;
3166 case 1: return mTransitionAnimationScale;
3167 }
3168 return 0;
3169 }
3170
3171 public float[] getAnimationScales() {
3172 return new float[] { mWindowAnimationScale, mTransitionAnimationScale };
3173 }
3174
3175 public int getSwitchState(int sw) {
3176 if (!checkCallingPermission(android.Manifest.permission.READ_INPUT_STATE,
3177 "getSwitchState()")) {
3178 return -1;
3179 }
3180 return KeyInputQueue.getSwitchState(sw);
3181 }
3182
3183 public int getSwitchStateForDevice(int devid, int sw) {
3184 if (!checkCallingPermission(android.Manifest.permission.READ_INPUT_STATE,
3185 "getSwitchStateForDevice()")) {
3186 return -1;
3187 }
3188 return KeyInputQueue.getSwitchState(devid, sw);
3189 }
3190
3191 public int getScancodeState(int sw) {
3192 if (!checkCallingPermission(android.Manifest.permission.READ_INPUT_STATE,
3193 "getScancodeState()")) {
3194 return -1;
3195 }
3196 return KeyInputQueue.getScancodeState(sw);
3197 }
3198
3199 public int getScancodeStateForDevice(int devid, int sw) {
3200 if (!checkCallingPermission(android.Manifest.permission.READ_INPUT_STATE,
3201 "getScancodeStateForDevice()")) {
3202 return -1;
3203 }
3204 return KeyInputQueue.getScancodeState(devid, sw);
3205 }
3206
3207 public int getKeycodeState(int sw) {
3208 if (!checkCallingPermission(android.Manifest.permission.READ_INPUT_STATE,
3209 "getKeycodeState()")) {
3210 return -1;
3211 }
3212 return KeyInputQueue.getKeycodeState(sw);
3213 }
3214
3215 public int getKeycodeStateForDevice(int devid, int sw) {
3216 if (!checkCallingPermission(android.Manifest.permission.READ_INPUT_STATE,
3217 "getKeycodeStateForDevice()")) {
3218 return -1;
3219 }
3220 return KeyInputQueue.getKeycodeState(devid, sw);
3221 }
3222
3223 public boolean hasKeys(int[] keycodes, boolean[] keyExists) {
3224 return KeyInputQueue.hasKeys(keycodes, keyExists);
3225 }
3226
3227 public void enableScreenAfterBoot() {
3228 synchronized(mWindowMap) {
3229 if (mSystemBooted) {
3230 return;
3231 }
3232 mSystemBooted = true;
3233 }
3234
3235 performEnableScreen();
3236 }
3237
3238 public void enableScreenIfNeededLocked() {
3239 if (mDisplayEnabled) {
3240 return;
3241 }
3242 if (!mSystemBooted) {
3243 return;
3244 }
3245 mH.sendMessage(mH.obtainMessage(H.ENABLE_SCREEN));
3246 }
3247
3248 public void performEnableScreen() {
3249 synchronized(mWindowMap) {
3250 if (mDisplayEnabled) {
3251 return;
3252 }
3253 if (!mSystemBooted) {
3254 return;
3255 }
3256
3257 // Don't enable the screen until all existing windows
3258 // have been drawn.
3259 final int N = mWindows.size();
3260 for (int i=0; i<N; i++) {
3261 WindowState w = (WindowState)mWindows.get(i);
3262 if (w.isVisibleLw() && !w.isDisplayedLw()) {
3263 return;
3264 }
3265 }
3266
3267 mDisplayEnabled = true;
3268 if (false) {
3269 Log.i(TAG, "ENABLING SCREEN!");
3270 StringWriter sw = new StringWriter();
3271 PrintWriter pw = new PrintWriter(sw);
3272 this.dump(null, pw, null);
3273 Log.i(TAG, sw.toString());
3274 }
3275 try {
3276 IBinder surfaceFlinger = ServiceManager.getService("SurfaceFlinger");
3277 if (surfaceFlinger != null) {
3278 //Log.i(TAG, "******* TELLING SURFACE FLINGER WE ARE BOOTED!");
3279 Parcel data = Parcel.obtain();
3280 data.writeInterfaceToken("android.ui.ISurfaceComposer");
3281 surfaceFlinger.transact(IBinder.FIRST_CALL_TRANSACTION,
3282 data, null, 0);
3283 data.recycle();
3284 }
3285 } catch (RemoteException ex) {
3286 Log.e(TAG, "Boot completed: SurfaceFlinger is dead!");
3287 }
3288 }
3289
3290 mPolicy.enableScreenAfterBoot();
3291
3292 // Make sure the last requested orientation has been applied.
Dianne Hackborn321ae682009-03-27 16:16:03 -07003293 setRotationUnchecked(WindowManagerPolicy.USE_LAST_ROTATION, false,
3294 mLastRotationFlags | Surface.FLAGS_ORIENTATION_ANIMATION_DISABLE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003295 }
3296
3297 public void setInTouchMode(boolean mode) {
3298 synchronized(mWindowMap) {
3299 mInTouchMode = mode;
3300 }
3301 }
3302
3303 public void setRotation(int rotation,
Dianne Hackborn1e880db2009-03-27 16:04:08 -07003304 boolean alwaysSendConfiguration, int animFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003305 if (!checkCallingPermission(android.Manifest.permission.SET_ORIENTATION,
Dianne Hackborn1e880db2009-03-27 16:04:08 -07003306 "setRotation()")) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003307 return;
3308 }
3309
Dianne Hackborn1e880db2009-03-27 16:04:08 -07003310 setRotationUnchecked(rotation, alwaysSendConfiguration, animFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003311 }
3312
Dianne Hackborn1e880db2009-03-27 16:04:08 -07003313 public void setRotationUnchecked(int rotation,
3314 boolean alwaysSendConfiguration, int animFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003315 if(DEBUG_ORIENTATION) Log.v(TAG,
3316 "alwaysSendConfiguration set to "+alwaysSendConfiguration);
3317
3318 long origId = Binder.clearCallingIdentity();
3319 boolean changed;
3320 synchronized(mWindowMap) {
Dianne Hackborn1e880db2009-03-27 16:04:08 -07003321 changed = setRotationUncheckedLocked(rotation, animFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003322 }
3323
3324 if (changed) {
3325 sendNewConfiguration();
3326 synchronized(mWindowMap) {
3327 mLayoutNeeded = true;
3328 performLayoutAndPlaceSurfacesLocked();
3329 }
3330 } else if (alwaysSendConfiguration) {
3331 //update configuration ignoring orientation change
3332 sendNewConfiguration();
3333 }
3334
3335 Binder.restoreCallingIdentity(origId);
3336 }
3337
Dianne Hackborn1e880db2009-03-27 16:04:08 -07003338 public boolean setRotationUncheckedLocked(int rotation, int animFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003339 boolean changed;
3340 if (rotation == WindowManagerPolicy.USE_LAST_ROTATION) {
3341 rotation = mRequestedRotation;
3342 } else {
3343 mRequestedRotation = rotation;
Dianne Hackborn321ae682009-03-27 16:16:03 -07003344 mLastRotationFlags = animFlags;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003345 }
3346 if (DEBUG_ORIENTATION) Log.v(TAG, "Overwriting rotation value from " + rotation);
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07003347 rotation = mPolicy.rotationForOrientationLw(mForcedAppOrientation,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003348 mRotation, mDisplayEnabled);
3349 if (DEBUG_ORIENTATION) Log.v(TAG, "new rotation is set to " + rotation);
3350 changed = mDisplayEnabled && mRotation != rotation;
3351
3352 if (changed) {
3353 if (DEBUG_ORIENTATION) Log.v(TAG,
3354 "Rotation changed to " + rotation
3355 + " from " + mRotation
3356 + " (forceApp=" + mForcedAppOrientation
3357 + ", req=" + mRequestedRotation + ")");
3358 mRotation = rotation;
3359 mWindowsFreezingScreen = true;
3360 mH.removeMessages(H.WINDOW_FREEZE_TIMEOUT);
3361 mH.sendMessageDelayed(mH.obtainMessage(H.WINDOW_FREEZE_TIMEOUT),
3362 2000);
3363 startFreezingDisplayLocked();
Dianne Hackborn1e880db2009-03-27 16:04:08 -07003364 Log.i(TAG, "Setting rotation to " + rotation + ", animFlags=" + animFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003365 mQueue.setOrientation(rotation);
3366 if (mDisplayEnabled) {
Dianne Hackborn321ae682009-03-27 16:16:03 -07003367 Surface.setOrientation(0, rotation, animFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003368 }
3369 for (int i=mWindows.size()-1; i>=0; i--) {
3370 WindowState w = (WindowState)mWindows.get(i);
3371 if (w.mSurface != null) {
3372 w.mOrientationChanging = true;
3373 }
3374 }
3375 for (int i=mRotationWatchers.size()-1; i>=0; i--) {
3376 try {
3377 mRotationWatchers.get(i).onRotationChanged(rotation);
3378 } catch (RemoteException e) {
3379 }
3380 }
3381 } //end if changed
3382
3383 return changed;
3384 }
3385
3386 public int getRotation() {
3387 return mRotation;
3388 }
3389
3390 public int watchRotation(IRotationWatcher watcher) {
3391 final IBinder watcherBinder = watcher.asBinder();
3392 IBinder.DeathRecipient dr = new IBinder.DeathRecipient() {
3393 public void binderDied() {
3394 synchronized (mWindowMap) {
3395 for (int i=0; i<mRotationWatchers.size(); i++) {
3396 if (watcherBinder == mRotationWatchers.get(i).asBinder()) {
3397 mRotationWatchers.remove(i);
3398 i--;
3399 }
3400 }
3401 }
3402 }
3403 };
3404
3405 synchronized (mWindowMap) {
3406 try {
3407 watcher.asBinder().linkToDeath(dr, 0);
3408 mRotationWatchers.add(watcher);
3409 } catch (RemoteException e) {
3410 // Client died, no cleanup needed.
3411 }
3412
3413 return mRotation;
3414 }
3415 }
3416
3417 /**
3418 * Starts the view server on the specified port.
3419 *
3420 * @param port The port to listener to.
3421 *
3422 * @return True if the server was successfully started, false otherwise.
3423 *
3424 * @see com.android.server.ViewServer
3425 * @see com.android.server.ViewServer#VIEW_SERVER_DEFAULT_PORT
3426 */
3427 public boolean startViewServer(int port) {
3428 if ("1".equals(SystemProperties.get(SYSTEM_SECURE, "0"))) {
3429 return false;
3430 }
3431
3432 if (!checkCallingPermission(Manifest.permission.DUMP, "startViewServer")) {
3433 return false;
3434 }
3435
3436 if (port < 1024) {
3437 return false;
3438 }
3439
3440 if (mViewServer != null) {
3441 if (!mViewServer.isRunning()) {
3442 try {
3443 return mViewServer.start();
3444 } catch (IOException e) {
3445 Log.w(TAG, "View server did not start");
3446 }
3447 }
3448 return false;
3449 }
3450
3451 try {
3452 mViewServer = new ViewServer(this, port);
3453 return mViewServer.start();
3454 } catch (IOException e) {
3455 Log.w(TAG, "View server did not start");
3456 }
3457 return false;
3458 }
3459
3460 /**
3461 * Stops the view server if it exists.
3462 *
3463 * @return True if the server stopped, false if it wasn't started or
3464 * couldn't be stopped.
3465 *
3466 * @see com.android.server.ViewServer
3467 */
3468 public boolean stopViewServer() {
3469 if ("1".equals(SystemProperties.get(SYSTEM_SECURE, "0"))) {
3470 return false;
3471 }
3472
3473 if (!checkCallingPermission(Manifest.permission.DUMP, "stopViewServer")) {
3474 return false;
3475 }
3476
3477 if (mViewServer != null) {
3478 return mViewServer.stop();
3479 }
3480 return false;
3481 }
3482
3483 /**
3484 * Indicates whether the view server is running.
3485 *
3486 * @return True if the server is running, false otherwise.
3487 *
3488 * @see com.android.server.ViewServer
3489 */
3490 public boolean isViewServerRunning() {
3491 if ("1".equals(SystemProperties.get(SYSTEM_SECURE, "0"))) {
3492 return false;
3493 }
3494
3495 if (!checkCallingPermission(Manifest.permission.DUMP, "isViewServerRunning")) {
3496 return false;
3497 }
3498
3499 return mViewServer != null && mViewServer.isRunning();
3500 }
3501
3502 /**
3503 * Lists all availble windows in the system. The listing is written in the
3504 * specified Socket's output stream with the following syntax:
3505 * windowHashCodeInHexadecimal windowName
3506 * Each line of the ouput represents a different window.
3507 *
3508 * @param client The remote client to send the listing to.
3509 * @return False if an error occured, true otherwise.
3510 */
3511 boolean viewServerListWindows(Socket client) {
3512 if ("1".equals(SystemProperties.get(SYSTEM_SECURE, "0"))) {
3513 return false;
3514 }
3515
3516 boolean result = true;
3517
3518 Object[] windows;
3519 synchronized (mWindowMap) {
3520 windows = new Object[mWindows.size()];
3521 //noinspection unchecked
3522 windows = mWindows.toArray(windows);
3523 }
3524
3525 BufferedWriter out = null;
3526
3527 // Any uncaught exception will crash the system process
3528 try {
3529 OutputStream clientStream = client.getOutputStream();
3530 out = new BufferedWriter(new OutputStreamWriter(clientStream), 8 * 1024);
3531
3532 final int count = windows.length;
3533 for (int i = 0; i < count; i++) {
3534 final WindowState w = (WindowState) windows[i];
3535 out.write(Integer.toHexString(System.identityHashCode(w)));
3536 out.write(' ');
3537 out.append(w.mAttrs.getTitle());
3538 out.write('\n');
3539 }
3540
3541 out.write("DONE.\n");
3542 out.flush();
3543 } catch (Exception e) {
3544 result = false;
3545 } finally {
3546 if (out != null) {
3547 try {
3548 out.close();
3549 } catch (IOException e) {
3550 result = false;
3551 }
3552 }
3553 }
3554
3555 return result;
3556 }
3557
3558 /**
3559 * Sends a command to a target window. The result of the command, if any, will be
3560 * written in the output stream of the specified socket.
3561 *
3562 * The parameters must follow this syntax:
3563 * windowHashcode extra
3564 *
3565 * Where XX is the length in characeters of the windowTitle.
3566 *
3567 * The first parameter is the target window. The window with the specified hashcode
3568 * will be the target. If no target can be found, nothing happens. The extra parameters
3569 * will be delivered to the target window and as parameters to the command itself.
3570 *
3571 * @param client The remote client to sent the result, if any, to.
3572 * @param command The command to execute.
3573 * @param parameters The command parameters.
3574 *
3575 * @return True if the command was successfully delivered, false otherwise. This does
3576 * not indicate whether the command itself was successful.
3577 */
3578 boolean viewServerWindowCommand(Socket client, String command, String parameters) {
3579 if ("1".equals(SystemProperties.get(SYSTEM_SECURE, "0"))) {
3580 return false;
3581 }
3582
3583 boolean success = true;
3584 Parcel data = null;
3585 Parcel reply = null;
3586
3587 // Any uncaught exception will crash the system process
3588 try {
3589 // Find the hashcode of the window
3590 int index = parameters.indexOf(' ');
3591 if (index == -1) {
3592 index = parameters.length();
3593 }
3594 final String code = parameters.substring(0, index);
3595 int hashCode = "ffffffff".equals(code) ? -1 : Integer.parseInt(code, 16);
3596
3597 // Extract the command's parameter after the window description
3598 if (index < parameters.length()) {
3599 parameters = parameters.substring(index + 1);
3600 } else {
3601 parameters = "";
3602 }
3603
3604 final WindowManagerService.WindowState window = findWindow(hashCode);
3605 if (window == null) {
3606 return false;
3607 }
3608
3609 data = Parcel.obtain();
3610 data.writeInterfaceToken("android.view.IWindow");
3611 data.writeString(command);
3612 data.writeString(parameters);
3613 data.writeInt(1);
3614 ParcelFileDescriptor.fromSocket(client).writeToParcel(data, 0);
3615
3616 reply = Parcel.obtain();
3617
3618 final IBinder binder = window.mClient.asBinder();
3619 // TODO: GET THE TRANSACTION CODE IN A SAFER MANNER
3620 binder.transact(IBinder.FIRST_CALL_TRANSACTION, data, reply, 0);
3621
3622 reply.readException();
3623
3624 } catch (Exception e) {
3625 Log.w(TAG, "Could not send command " + command + " with parameters " + parameters, e);
3626 success = false;
3627 } finally {
3628 if (data != null) {
3629 data.recycle();
3630 }
3631 if (reply != null) {
3632 reply.recycle();
3633 }
3634 }
3635
3636 return success;
3637 }
3638
3639 private WindowState findWindow(int hashCode) {
3640 if (hashCode == -1) {
3641 return getFocusedWindow();
3642 }
3643
3644 synchronized (mWindowMap) {
3645 final ArrayList windows = mWindows;
3646 final int count = windows.size();
3647
3648 for (int i = 0; i < count; i++) {
3649 WindowState w = (WindowState) windows.get(i);
3650 if (System.identityHashCode(w) == hashCode) {
3651 return w;
3652 }
3653 }
3654 }
3655
3656 return null;
3657 }
3658
3659 /*
3660 * Instruct the Activity Manager to fetch the current configuration and broadcast
3661 * that to config-changed listeners if appropriate.
3662 */
3663 void sendNewConfiguration() {
3664 try {
3665 mActivityManager.updateConfiguration(null);
3666 } catch (RemoteException e) {
3667 }
3668 }
3669
3670 public Configuration computeNewConfiguration() {
3671 synchronized (mWindowMap) {
Dianne Hackbornc485a602009-03-24 22:39:49 -07003672 return computeNewConfigurationLocked();
3673 }
3674 }
3675
3676 Configuration computeNewConfigurationLocked() {
3677 Configuration config = new Configuration();
3678 if (!computeNewConfigurationLocked(config)) {
3679 return null;
3680 }
3681 Log.i(TAG, "Config changed: " + config);
3682 long now = SystemClock.uptimeMillis();
3683 //Log.i(TAG, "Config changing, gc pending: " + mFreezeGcPending + ", now " + now);
3684 if (mFreezeGcPending != 0) {
3685 if (now > (mFreezeGcPending+1000)) {
3686 //Log.i(TAG, "Gc! " + now + " > " + (mFreezeGcPending+1000));
3687 mH.removeMessages(H.FORCE_GC);
3688 Runtime.getRuntime().gc();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003689 mFreezeGcPending = now;
3690 }
Dianne Hackbornc485a602009-03-24 22:39:49 -07003691 } else {
3692 mFreezeGcPending = now;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003693 }
Dianne Hackbornc485a602009-03-24 22:39:49 -07003694 return config;
3695 }
3696
3697 boolean computeNewConfigurationLocked(Configuration config) {
3698 if (mDisplay == null) {
3699 return false;
3700 }
3701 mQueue.getInputConfiguration(config);
3702 final int dw = mDisplay.getWidth();
3703 final int dh = mDisplay.getHeight();
3704 int orientation = Configuration.ORIENTATION_SQUARE;
3705 if (dw < dh) {
3706 orientation = Configuration.ORIENTATION_PORTRAIT;
3707 } else if (dw > dh) {
3708 orientation = Configuration.ORIENTATION_LANDSCAPE;
3709 }
3710 config.orientation = orientation;
3711 config.keyboardHidden = Configuration.KEYBOARDHIDDEN_NO;
3712 config.hardKeyboardHidden = Configuration.HARDKEYBOARDHIDDEN_NO;
3713 mPolicy.adjustConfigurationLw(config);
3714 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003715 }
3716
3717 // -------------------------------------------------------------
3718 // Input Events and Focus Management
3719 // -------------------------------------------------------------
3720
3721 private final void wakeupIfNeeded(WindowState targetWin, int eventType) {
Michael Chane96440f2009-05-06 10:27:36 -07003722 long curTime = SystemClock.uptimeMillis();
3723
Michael Chane10de972009-05-18 11:24:50 -07003724 if (eventType == TOUCH_EVENT || eventType == LONG_TOUCH_EVENT || eventType == CHEEK_EVENT) {
Michael Chane96440f2009-05-06 10:27:36 -07003725 if (mLastTouchEventType == eventType &&
3726 (curTime - mLastUserActivityCallTime) < MIN_TIME_BETWEEN_USERACTIVITIES) {
3727 return;
3728 }
3729 mLastUserActivityCallTime = curTime;
3730 mLastTouchEventType = eventType;
3731 }
3732
3733 if (targetWin == null
3734 || targetWin.mAttrs.type != WindowManager.LayoutParams.TYPE_KEYGUARD) {
3735 mPowerManager.userActivity(curTime, false, eventType, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003736 }
3737 }
3738
3739 // tells if it's a cheek event or not -- this function is stateful
3740 private static final int EVENT_NONE = 0;
3741 private static final int EVENT_UNKNOWN = 0;
3742 private static final int EVENT_CHEEK = 0;
3743 private static final int EVENT_IGNORE_DURATION = 300; // ms
3744 private static final float CHEEK_THRESHOLD = 0.6f;
3745 private int mEventState = EVENT_NONE;
3746 private float mEventSize;
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07003747
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003748 private int eventType(MotionEvent ev) {
3749 float size = ev.getSize();
3750 switch (ev.getAction()) {
3751 case MotionEvent.ACTION_DOWN:
3752 mEventSize = size;
3753 return (mEventSize > CHEEK_THRESHOLD) ? CHEEK_EVENT : TOUCH_EVENT;
3754 case MotionEvent.ACTION_UP:
3755 if (size > mEventSize) mEventSize = size;
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07003756 return (mEventSize > CHEEK_THRESHOLD) ? CHEEK_EVENT : TOUCH_UP_EVENT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003757 case MotionEvent.ACTION_MOVE:
3758 final int N = ev.getHistorySize();
3759 if (size > mEventSize) mEventSize = size;
3760 if (mEventSize > CHEEK_THRESHOLD) return CHEEK_EVENT;
3761 for (int i=0; i<N; i++) {
3762 size = ev.getHistoricalSize(i);
3763 if (size > mEventSize) mEventSize = size;
3764 if (mEventSize > CHEEK_THRESHOLD) return CHEEK_EVENT;
3765 }
3766 if (ev.getEventTime() < ev.getDownTime() + EVENT_IGNORE_DURATION) {
3767 return TOUCH_EVENT;
3768 } else {
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07003769 return LONG_TOUCH_EVENT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003770 }
3771 default:
3772 // not good
3773 return OTHER_EVENT;
3774 }
3775 }
3776
3777 /**
3778 * @return Returns true if event was dispatched, false if it was dropped for any reason
3779 */
3780 private boolean dispatchPointer(QueuedEvent qev, MotionEvent ev, int pid, int uid) {
3781 if (DEBUG_INPUT || WindowManagerPolicy.WATCH_POINTER) Log.v(TAG,
3782 "dispatchPointer " + ev);
3783
Michael Chan53071d62009-05-13 17:29:48 -07003784 if (MEASURE_LATENCY) {
3785 lt.sample("3 Wait for last dispatch ", System.nanoTime() - qev.whenNano);
3786 }
3787
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003788 Object targetObj = mKeyWaiter.waitForNextEventTarget(null, qev,
3789 ev, true, false);
3790
Michael Chan53071d62009-05-13 17:29:48 -07003791 if (MEASURE_LATENCY) {
3792 lt.sample("3 Last dispatch finished ", System.nanoTime() - qev.whenNano);
3793 }
3794
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003795 int action = ev.getAction();
3796
3797 if (action == MotionEvent.ACTION_UP) {
3798 // let go of our target
3799 mKeyWaiter.mMotionTarget = null;
3800 mPowerManager.logPointerUpEvent();
3801 } else if (action == MotionEvent.ACTION_DOWN) {
3802 mPowerManager.logPointerDownEvent();
3803 }
3804
3805 if (targetObj == null) {
3806 // In this case we are either dropping the event, or have received
3807 // a move or up without a down. It is common to receive move
3808 // events in such a way, since this means the user is moving the
3809 // pointer without actually pressing down. All other cases should
3810 // be atypical, so let's log them.
Michael Chane96440f2009-05-06 10:27:36 -07003811 if (action != MotionEvent.ACTION_MOVE) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003812 Log.w(TAG, "No window to dispatch pointer action " + ev.getAction());
3813 }
3814 if (qev != null) {
3815 mQueue.recycleEvent(qev);
3816 }
3817 ev.recycle();
3818 return false;
3819 }
3820 if (targetObj == mKeyWaiter.CONSUMED_EVENT_TOKEN) {
3821 if (qev != null) {
3822 mQueue.recycleEvent(qev);
3823 }
3824 ev.recycle();
3825 return true;
3826 }
3827
3828 WindowState target = (WindowState)targetObj;
3829
3830 final long eventTime = ev.getEventTime();
Michael Chan53071d62009-05-13 17:29:48 -07003831 final long eventTimeNano = ev.getEventTimeNano();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003832
3833 //Log.i(TAG, "Sending " + ev + " to " + target);
3834
3835 if (uid != 0 && uid != target.mSession.mUid) {
3836 if (mContext.checkPermission(
3837 android.Manifest.permission.INJECT_EVENTS, pid, uid)
3838 != PackageManager.PERMISSION_GRANTED) {
3839 Log.w(TAG, "Permission denied: injecting pointer event from pid "
3840 + pid + " uid " + uid + " to window " + target
3841 + " owned by uid " + target.mSession.mUid);
3842 if (qev != null) {
3843 mQueue.recycleEvent(qev);
3844 }
3845 ev.recycle();
3846 return false;
3847 }
3848 }
3849
Michael Chan53071d62009-05-13 17:29:48 -07003850 if (MEASURE_LATENCY) {
3851 lt.sample("4 in dispatchPointer ", System.nanoTime() - eventTimeNano);
3852 }
3853
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003854 if ((target.mAttrs.flags &
3855 WindowManager.LayoutParams.FLAG_IGNORE_CHEEK_PRESSES) != 0) {
3856 //target wants to ignore fat touch events
3857 boolean cheekPress = mPolicy.isCheekPressedAgainstScreen(ev);
3858 //explicit flag to return without processing event further
3859 boolean returnFlag = false;
3860 if((action == MotionEvent.ACTION_DOWN)) {
3861 mFatTouch = false;
3862 if(cheekPress) {
3863 mFatTouch = true;
3864 returnFlag = true;
3865 }
3866 } else {
3867 if(action == MotionEvent.ACTION_UP) {
3868 if(mFatTouch) {
3869 //earlier even was invalid doesnt matter if current up is cheekpress or not
3870 mFatTouch = false;
3871 returnFlag = true;
3872 } else if(cheekPress) {
3873 //cancel the earlier event
3874 ev.setAction(MotionEvent.ACTION_CANCEL);
3875 action = MotionEvent.ACTION_CANCEL;
3876 }
3877 } else if(action == MotionEvent.ACTION_MOVE) {
3878 if(mFatTouch) {
3879 //two cases here
3880 //an invalid down followed by 0 or moves(valid or invalid)
3881 //a valid down, invalid move, more moves. want to ignore till up
3882 returnFlag = true;
3883 } else if(cheekPress) {
3884 //valid down followed by invalid moves
3885 //an invalid move have to cancel earlier action
3886 ev.setAction(MotionEvent.ACTION_CANCEL);
3887 action = MotionEvent.ACTION_CANCEL;
3888 if (DEBUG_INPUT) Log.v(TAG, "Sending cancel for invalid ACTION_MOVE");
3889 //note that the subsequent invalid moves will not get here
3890 mFatTouch = true;
3891 }
3892 }
3893 } //else if action
3894 if(returnFlag) {
3895 //recycle que, ev
3896 if (qev != null) {
3897 mQueue.recycleEvent(qev);
3898 }
3899 ev.recycle();
3900 return false;
3901 }
3902 } //end if target
Michael Chane96440f2009-05-06 10:27:36 -07003903
3904 // TODO remove once we settle on a value or make it app specific
3905 if (action == MotionEvent.ACTION_DOWN) {
3906 int max_events_per_sec = 35;
3907 try {
3908 max_events_per_sec = Integer.parseInt(SystemProperties
3909 .get("windowsmgr.max_events_per_sec"));
3910 if (max_events_per_sec < 1) {
3911 max_events_per_sec = 35;
3912 }
3913 } catch (NumberFormatException e) {
3914 }
3915 mMinWaitTimeBetweenTouchEvents = 1000 / max_events_per_sec;
3916 }
3917
3918 /*
3919 * Throttle events to minimize CPU usage when there's a flood of events
3920 * e.g. constant contact with the screen
3921 */
3922 if (action == MotionEvent.ACTION_MOVE) {
3923 long nextEventTime = mLastTouchEventTime + mMinWaitTimeBetweenTouchEvents;
3924 long now = SystemClock.uptimeMillis();
3925 if (now < nextEventTime) {
3926 try {
3927 Thread.sleep(nextEventTime - now);
3928 } catch (InterruptedException e) {
3929 }
3930 mLastTouchEventTime = nextEventTime;
3931 } else {
3932 mLastTouchEventTime = now;
3933 }
3934 }
3935
Michael Chan53071d62009-05-13 17:29:48 -07003936 if (MEASURE_LATENCY) {
3937 lt.sample("5 in dispatchPointer ", System.nanoTime() - eventTimeNano);
3938 }
3939
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003940 synchronized(mWindowMap) {
3941 if (qev != null && action == MotionEvent.ACTION_MOVE) {
3942 mKeyWaiter.bindTargetWindowLocked(target,
3943 KeyWaiter.RETURN_PENDING_POINTER, qev);
3944 ev = null;
3945 } else {
3946 if (action == MotionEvent.ACTION_DOWN) {
3947 WindowState out = mKeyWaiter.mOutsideTouchTargets;
3948 if (out != null) {
3949 MotionEvent oev = MotionEvent.obtain(ev);
3950 oev.setAction(MotionEvent.ACTION_OUTSIDE);
3951 do {
3952 final Rect frame = out.mFrame;
3953 oev.offsetLocation(-(float)frame.left, -(float)frame.top);
3954 try {
3955 out.mClient.dispatchPointer(oev, eventTime);
3956 } catch (android.os.RemoteException e) {
3957 Log.i(TAG, "WINDOW DIED during outside motion dispatch: " + out);
3958 }
3959 oev.offsetLocation((float)frame.left, (float)frame.top);
3960 out = out.mNextOutsideTouch;
3961 } while (out != null);
3962 mKeyWaiter.mOutsideTouchTargets = null;
3963 }
3964 }
3965 final Rect frame = target.mFrame;
3966 ev.offsetLocation(-(float)frame.left, -(float)frame.top);
3967 mKeyWaiter.bindTargetWindowLocked(target);
3968 }
3969 }
3970
3971 // finally offset the event to the target's coordinate system and
3972 // dispatch the event.
3973 try {
3974 if (DEBUG_INPUT || DEBUG_FOCUS || WindowManagerPolicy.WATCH_POINTER) {
3975 Log.v(TAG, "Delivering pointer " + qev + " to " + target);
3976 }
Michael Chan53071d62009-05-13 17:29:48 -07003977
3978 if (MEASURE_LATENCY) {
3979 lt.sample("6 before svr->client ipc ", System.nanoTime() - eventTimeNano);
3980 }
3981
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003982 target.mClient.dispatchPointer(ev, eventTime);
Michael Chan53071d62009-05-13 17:29:48 -07003983
3984 if (MEASURE_LATENCY) {
3985 lt.sample("7 after svr->client ipc ", System.nanoTime() - eventTimeNano);
3986 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003987 return true;
3988 } catch (android.os.RemoteException e) {
3989 Log.i(TAG, "WINDOW DIED during motion dispatch: " + target);
3990 mKeyWaiter.mMotionTarget = null;
3991 try {
3992 removeWindow(target.mSession, target.mClient);
3993 } catch (java.util.NoSuchElementException ex) {
3994 // This will happen if the window has already been
3995 // removed.
3996 }
3997 }
3998 return false;
3999 }
4000
4001 /**
4002 * @return Returns true if event was dispatched, false if it was dropped for any reason
4003 */
4004 private boolean dispatchTrackball(QueuedEvent qev, MotionEvent ev, int pid, int uid) {
4005 if (DEBUG_INPUT) Log.v(
4006 TAG, "dispatchTrackball [" + ev.getAction() +"] <" + ev.getX() + ", " + ev.getY() + ">");
4007
4008 Object focusObj = mKeyWaiter.waitForNextEventTarget(null, qev,
4009 ev, false, false);
4010 if (focusObj == null) {
4011 Log.w(TAG, "No focus window, dropping trackball: " + ev);
4012 if (qev != null) {
4013 mQueue.recycleEvent(qev);
4014 }
4015 ev.recycle();
4016 return false;
4017 }
4018 if (focusObj == mKeyWaiter.CONSUMED_EVENT_TOKEN) {
4019 if (qev != null) {
4020 mQueue.recycleEvent(qev);
4021 }
4022 ev.recycle();
4023 return true;
4024 }
4025
4026 WindowState focus = (WindowState)focusObj;
4027
4028 if (uid != 0 && uid != focus.mSession.mUid) {
4029 if (mContext.checkPermission(
4030 android.Manifest.permission.INJECT_EVENTS, pid, uid)
4031 != PackageManager.PERMISSION_GRANTED) {
4032 Log.w(TAG, "Permission denied: injecting key event from pid "
4033 + pid + " uid " + uid + " to window " + focus
4034 + " owned by uid " + focus.mSession.mUid);
4035 if (qev != null) {
4036 mQueue.recycleEvent(qev);
4037 }
4038 ev.recycle();
4039 return false;
4040 }
4041 }
4042
4043 final long eventTime = ev.getEventTime();
4044
4045 synchronized(mWindowMap) {
4046 if (qev != null && ev.getAction() == MotionEvent.ACTION_MOVE) {
4047 mKeyWaiter.bindTargetWindowLocked(focus,
4048 KeyWaiter.RETURN_PENDING_TRACKBALL, qev);
4049 // We don't deliver movement events to the client, we hold
4050 // them and wait for them to call back.
4051 ev = null;
4052 } else {
4053 mKeyWaiter.bindTargetWindowLocked(focus);
4054 }
4055 }
4056
4057 try {
4058 focus.mClient.dispatchTrackball(ev, eventTime);
4059 return true;
4060 } catch (android.os.RemoteException e) {
4061 Log.i(TAG, "WINDOW DIED during key dispatch: " + focus);
4062 try {
4063 removeWindow(focus.mSession, focus.mClient);
4064 } catch (java.util.NoSuchElementException ex) {
4065 // This will happen if the window has already been
4066 // removed.
4067 }
4068 }
4069
4070 return false;
4071 }
4072
4073 /**
4074 * @return Returns true if event was dispatched, false if it was dropped for any reason
4075 */
4076 private boolean dispatchKey(KeyEvent event, int pid, int uid) {
4077 if (DEBUG_INPUT) Log.v(TAG, "Dispatch key: " + event);
4078
4079 Object focusObj = mKeyWaiter.waitForNextEventTarget(event, null,
4080 null, false, false);
4081 if (focusObj == null) {
4082 Log.w(TAG, "No focus window, dropping: " + event);
4083 return false;
4084 }
4085 if (focusObj == mKeyWaiter.CONSUMED_EVENT_TOKEN) {
4086 return true;
4087 }
4088
4089 WindowState focus = (WindowState)focusObj;
4090
4091 if (DEBUG_INPUT) Log.v(
4092 TAG, "Dispatching to " + focus + ": " + event);
4093
4094 if (uid != 0 && uid != focus.mSession.mUid) {
4095 if (mContext.checkPermission(
4096 android.Manifest.permission.INJECT_EVENTS, pid, uid)
4097 != PackageManager.PERMISSION_GRANTED) {
4098 Log.w(TAG, "Permission denied: injecting key event from pid "
4099 + pid + " uid " + uid + " to window " + focus
4100 + " owned by uid " + focus.mSession.mUid);
4101 return false;
4102 }
4103 }
4104
4105 synchronized(mWindowMap) {
4106 mKeyWaiter.bindTargetWindowLocked(focus);
4107 }
4108
4109 // NOSHIP extra state logging
4110 mKeyWaiter.recordDispatchState(event, focus);
4111 // END NOSHIP
4112
4113 try {
4114 if (DEBUG_INPUT || DEBUG_FOCUS) {
4115 Log.v(TAG, "Delivering key " + event.getKeyCode()
4116 + " to " + focus);
4117 }
4118 focus.mClient.dispatchKey(event);
4119 return true;
4120 } catch (android.os.RemoteException e) {
4121 Log.i(TAG, "WINDOW DIED during key dispatch: " + focus);
4122 try {
4123 removeWindow(focus.mSession, focus.mClient);
4124 } catch (java.util.NoSuchElementException ex) {
4125 // This will happen if the window has already been
4126 // removed.
4127 }
4128 }
4129
4130 return false;
4131 }
4132
4133 public void pauseKeyDispatching(IBinder _token) {
4134 if (!checkCallingPermission(android.Manifest.permission.MANAGE_APP_TOKENS,
4135 "pauseKeyDispatching()")) {
4136 return;
4137 }
4138
4139 synchronized (mWindowMap) {
4140 WindowToken token = mTokenMap.get(_token);
4141 if (token != null) {
4142 mKeyWaiter.pauseDispatchingLocked(token);
4143 }
4144 }
4145 }
4146
4147 public void resumeKeyDispatching(IBinder _token) {
4148 if (!checkCallingPermission(android.Manifest.permission.MANAGE_APP_TOKENS,
4149 "resumeKeyDispatching()")) {
4150 return;
4151 }
4152
4153 synchronized (mWindowMap) {
4154 WindowToken token = mTokenMap.get(_token);
4155 if (token != null) {
4156 mKeyWaiter.resumeDispatchingLocked(token);
4157 }
4158 }
4159 }
4160
4161 public void setEventDispatching(boolean enabled) {
4162 if (!checkCallingPermission(android.Manifest.permission.MANAGE_APP_TOKENS,
4163 "resumeKeyDispatching()")) {
4164 return;
4165 }
4166
4167 synchronized (mWindowMap) {
4168 mKeyWaiter.setEventDispatchingLocked(enabled);
4169 }
4170 }
4171
4172 /**
4173 * Injects a keystroke event into the UI.
4174 *
4175 * @param ev A motion event describing the keystroke action. (Be sure to use
4176 * {@link SystemClock#uptimeMillis()} as the timebase.)
4177 * @param sync If true, wait for the event to be completed before returning to the caller.
4178 * @return Returns true if event was dispatched, false if it was dropped for any reason
4179 */
4180 public boolean injectKeyEvent(KeyEvent ev, boolean sync) {
4181 long downTime = ev.getDownTime();
4182 long eventTime = ev.getEventTime();
4183
4184 int action = ev.getAction();
4185 int code = ev.getKeyCode();
4186 int repeatCount = ev.getRepeatCount();
4187 int metaState = ev.getMetaState();
4188 int deviceId = ev.getDeviceId();
4189 int scancode = ev.getScanCode();
4190
4191 if (eventTime == 0) eventTime = SystemClock.uptimeMillis();
4192 if (downTime == 0) downTime = eventTime;
4193
4194 KeyEvent newEvent = new KeyEvent(downTime, eventTime, action, code, repeatCount, metaState,
The Android Open Source Project10592532009-03-18 17:39:46 -07004195 deviceId, scancode, KeyEvent.FLAG_FROM_SYSTEM);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004196
4197 boolean result = dispatchKey(newEvent, Binder.getCallingPid(), Binder.getCallingUid());
4198 if (sync) {
4199 mKeyWaiter.waitForNextEventTarget(null, null, null, false, true);
4200 }
4201 return result;
4202 }
4203
4204 /**
4205 * Inject a pointer (touch) event into the UI.
4206 *
4207 * @param ev A motion event describing the pointer (touch) action. (As noted in
4208 * {@link MotionEvent#obtain(long, long, int, float, float, int)}, be sure to use
4209 * {@link SystemClock#uptimeMillis()} as the timebase.)
4210 * @param sync If true, wait for the event to be completed before returning to the caller.
4211 * @return Returns true if event was dispatched, false if it was dropped for any reason
4212 */
4213 public boolean injectPointerEvent(MotionEvent ev, boolean sync) {
4214 boolean result = dispatchPointer(null, ev, Binder.getCallingPid(), Binder.getCallingUid());
4215 if (sync) {
4216 mKeyWaiter.waitForNextEventTarget(null, null, null, false, true);
4217 }
4218 return result;
4219 }
4220
4221 /**
4222 * Inject a trackball (navigation device) event into the UI.
4223 *
4224 * @param ev A motion event describing the trackball action. (As noted in
4225 * {@link MotionEvent#obtain(long, long, int, float, float, int)}, be sure to use
4226 * {@link SystemClock#uptimeMillis()} as the timebase.)
4227 * @param sync If true, wait for the event to be completed before returning to the caller.
4228 * @return Returns true if event was dispatched, false if it was dropped for any reason
4229 */
4230 public boolean injectTrackballEvent(MotionEvent ev, boolean sync) {
4231 boolean result = dispatchTrackball(null, ev, Binder.getCallingPid(), Binder.getCallingUid());
4232 if (sync) {
4233 mKeyWaiter.waitForNextEventTarget(null, null, null, false, true);
4234 }
4235 return result;
4236 }
4237
4238 private WindowState getFocusedWindow() {
4239 synchronized (mWindowMap) {
4240 return getFocusedWindowLocked();
4241 }
4242 }
4243
4244 private WindowState getFocusedWindowLocked() {
4245 return mCurrentFocus;
4246 }
4247
4248 /**
4249 * This class holds the state for dispatching key events. This state
4250 * is protected by the KeyWaiter instance, NOT by the window lock. You
4251 * can be holding the main window lock while acquire the KeyWaiter lock,
4252 * but not the other way around.
4253 */
4254 final class KeyWaiter {
4255 // NOSHIP debugging
4256 public class DispatchState {
4257 private KeyEvent event;
4258 private WindowState focus;
4259 private long time;
4260 private WindowState lastWin;
4261 private IBinder lastBinder;
4262 private boolean finished;
4263 private boolean gotFirstWindow;
4264 private boolean eventDispatching;
4265 private long timeToSwitch;
4266 private boolean wasFrozen;
4267 private boolean focusPaused;
The Android Open Source Projectc474dec2009-03-04 09:49:09 -08004268 private WindowState curFocus;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004269
4270 DispatchState(KeyEvent theEvent, WindowState theFocus) {
4271 focus = theFocus;
4272 event = theEvent;
4273 time = System.currentTimeMillis();
4274 // snapshot KeyWaiter state
4275 lastWin = mLastWin;
4276 lastBinder = mLastBinder;
4277 finished = mFinished;
4278 gotFirstWindow = mGotFirstWindow;
4279 eventDispatching = mEventDispatching;
4280 timeToSwitch = mTimeToSwitch;
4281 wasFrozen = mWasFrozen;
The Android Open Source Projectc474dec2009-03-04 09:49:09 -08004282 curFocus = mCurrentFocus;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004283 // cache the paused state at ctor time as well
4284 if (theFocus == null || theFocus.mToken == null) {
4285 Log.i(TAG, "focus " + theFocus + " mToken is null at event dispatch!");
4286 focusPaused = false;
4287 } else {
4288 focusPaused = theFocus.mToken.paused;
4289 }
4290 }
4291
4292 public String toString() {
4293 return "{{" + event + " to " + focus + " @ " + time
4294 + " lw=" + lastWin + " lb=" + lastBinder
4295 + " fin=" + finished + " gfw=" + gotFirstWindow
4296 + " ed=" + eventDispatching + " tts=" + timeToSwitch
The Android Open Source Projectc474dec2009-03-04 09:49:09 -08004297 + " wf=" + wasFrozen + " fp=" + focusPaused
4298 + " mcf=" + mCurrentFocus + "}}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004299 }
4300 };
4301 private DispatchState mDispatchState = null;
4302 public void recordDispatchState(KeyEvent theEvent, WindowState theFocus) {
4303 mDispatchState = new DispatchState(theEvent, theFocus);
4304 }
4305 // END NOSHIP
4306
4307 public static final int RETURN_NOTHING = 0;
4308 public static final int RETURN_PENDING_POINTER = 1;
4309 public static final int RETURN_PENDING_TRACKBALL = 2;
4310
4311 final Object SKIP_TARGET_TOKEN = new Object();
4312 final Object CONSUMED_EVENT_TOKEN = new Object();
4313
4314 private WindowState mLastWin = null;
4315 private IBinder mLastBinder = null;
4316 private boolean mFinished = true;
4317 private boolean mGotFirstWindow = false;
4318 private boolean mEventDispatching = true;
4319 private long mTimeToSwitch = 0;
4320 /* package */ boolean mWasFrozen = false;
4321
4322 // Target of Motion events
4323 WindowState mMotionTarget;
4324
4325 // Windows above the target who would like to receive an "outside"
4326 // touch event for any down events outside of them.
4327 WindowState mOutsideTouchTargets;
4328
4329 /**
4330 * Wait for the last event dispatch to complete, then find the next
4331 * target that should receive the given event and wait for that one
4332 * to be ready to receive it.
4333 */
4334 Object waitForNextEventTarget(KeyEvent nextKey, QueuedEvent qev,
4335 MotionEvent nextMotion, boolean isPointerEvent,
4336 boolean failIfTimeout) {
4337 long startTime = SystemClock.uptimeMillis();
4338 long keyDispatchingTimeout = 5 * 1000;
4339 long waitedFor = 0;
4340
4341 while (true) {
4342 // Figure out which window we care about. It is either the
4343 // last window we are waiting to have process the event or,
4344 // if none, then the next window we think the event should go
4345 // to. Note: we retrieve mLastWin outside of the lock, so
4346 // it may change before we lock. Thus we must check it again.
4347 WindowState targetWin = mLastWin;
4348 boolean targetIsNew = targetWin == null;
4349 if (DEBUG_INPUT) Log.v(
4350 TAG, "waitForLastKey: mFinished=" + mFinished +
4351 ", mLastWin=" + mLastWin);
4352 if (targetIsNew) {
4353 Object target = findTargetWindow(nextKey, qev, nextMotion,
4354 isPointerEvent);
4355 if (target == SKIP_TARGET_TOKEN) {
4356 // The user has pressed a special key, and we are
4357 // dropping all pending events before it.
4358 if (DEBUG_INPUT) Log.v(TAG, "Skipping: " + nextKey
4359 + " " + nextMotion);
4360 return null;
4361 }
4362 if (target == CONSUMED_EVENT_TOKEN) {
4363 if (DEBUG_INPUT) Log.v(TAG, "Consumed: " + nextKey
4364 + " " + nextMotion);
4365 return target;
4366 }
4367 targetWin = (WindowState)target;
4368 }
4369
4370 AppWindowToken targetApp = null;
4371
4372 // Now: is it okay to send the next event to this window?
4373 synchronized (this) {
4374 // First: did we come here based on the last window not
4375 // being null, but it changed by the time we got here?
4376 // If so, try again.
4377 if (!targetIsNew && mLastWin == null) {
4378 continue;
4379 }
4380
4381 // We never dispatch events if not finished with the
4382 // last one, or the display is frozen.
4383 if (mFinished && !mDisplayFrozen) {
4384 // If event dispatching is disabled, then we
4385 // just consume the events.
4386 if (!mEventDispatching) {
4387 if (DEBUG_INPUT) Log.v(TAG,
4388 "Skipping event; dispatching disabled: "
4389 + nextKey + " " + nextMotion);
4390 return null;
4391 }
4392 if (targetWin != null) {
4393 // If this is a new target, and that target is not
4394 // paused or unresponsive, then all looks good to
4395 // handle the event.
4396 if (targetIsNew && !targetWin.mToken.paused) {
4397 return targetWin;
4398 }
4399
4400 // If we didn't find a target window, and there is no
4401 // focused app window, then just eat the events.
4402 } else if (mFocusedApp == null) {
4403 if (DEBUG_INPUT) Log.v(TAG,
4404 "Skipping event; no focused app: "
4405 + nextKey + " " + nextMotion);
4406 return null;
4407 }
4408 }
4409
4410 if (DEBUG_INPUT) Log.v(
4411 TAG, "Waiting for last key in " + mLastBinder
4412 + " target=" + targetWin
4413 + " mFinished=" + mFinished
4414 + " mDisplayFrozen=" + mDisplayFrozen
4415 + " targetIsNew=" + targetIsNew
4416 + " paused="
4417 + (targetWin != null ? targetWin.mToken.paused : false)
The Android Open Source Projectc474dec2009-03-04 09:49:09 -08004418 + " mFocusedApp=" + mFocusedApp
4419 + " mCurrentFocus=" + mCurrentFocus);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004420
4421 targetApp = targetWin != null
4422 ? targetWin.mAppToken : mFocusedApp;
4423
4424 long curTimeout = keyDispatchingTimeout;
4425 if (mTimeToSwitch != 0) {
4426 long now = SystemClock.uptimeMillis();
4427 if (mTimeToSwitch <= now) {
4428 // If an app switch key has been pressed, and we have
4429 // waited too long for the current app to finish
4430 // processing keys, then wait no more!
4431 doFinishedKeyLocked(true);
4432 continue;
4433 }
4434 long switchTimeout = mTimeToSwitch - now;
4435 if (curTimeout > switchTimeout) {
4436 curTimeout = switchTimeout;
4437 }
4438 }
4439
4440 try {
4441 // after that continue
4442 // processing keys, so we don't get stuck.
4443 if (DEBUG_INPUT) Log.v(
4444 TAG, "Waiting for key dispatch: " + curTimeout);
4445 wait(curTimeout);
4446 if (DEBUG_INPUT) Log.v(TAG, "Finished waiting @"
4447 + SystemClock.uptimeMillis() + " startTime="
The Android Open Source Projectc474dec2009-03-04 09:49:09 -08004448 + startTime + " switchTime=" + mTimeToSwitch
4449 + " target=" + targetWin + " mLW=" + mLastWin
4450 + " mLB=" + mLastBinder + " fin=" + mFinished
4451 + " mCurrentFocus=" + mCurrentFocus);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004452 } catch (InterruptedException e) {
4453 }
4454 }
4455
4456 // If we were frozen during configuration change, restart the
4457 // timeout checks from now; otherwise look at whether we timed
4458 // out before awakening.
4459 if (mWasFrozen) {
4460 waitedFor = 0;
4461 mWasFrozen = false;
4462 } else {
4463 waitedFor = SystemClock.uptimeMillis() - startTime;
4464 }
4465
4466 if (waitedFor >= keyDispatchingTimeout && mTimeToSwitch == 0) {
4467 IApplicationToken at = null;
4468 synchronized (this) {
4469 Log.w(TAG, "Key dispatching timed out sending to " +
4470 (targetWin != null ? targetWin.mAttrs.getTitle()
4471 : "<null>"));
4472 // NOSHIP debugging
4473 Log.w(TAG, "Dispatch state: " + mDispatchState);
4474 Log.w(TAG, "Current state: " + new DispatchState(nextKey, targetWin));
4475 // END NOSHIP
4476 //dump();
4477 if (targetWin != null) {
4478 at = targetWin.getAppToken();
4479 } else if (targetApp != null) {
4480 at = targetApp.appToken;
4481 }
4482 }
4483
4484 boolean abort = true;
4485 if (at != null) {
4486 try {
4487 long timeout = at.getKeyDispatchingTimeout();
4488 if (timeout > waitedFor) {
4489 // we did not wait the proper amount of time for this application.
4490 // set the timeout to be the real timeout and wait again.
4491 keyDispatchingTimeout = timeout - waitedFor;
4492 continue;
4493 } else {
4494 abort = at.keyDispatchingTimedOut();
4495 }
4496 } catch (RemoteException ex) {
4497 }
4498 }
4499
4500 synchronized (this) {
4501 if (abort && (mLastWin == targetWin || targetWin == null)) {
4502 mFinished = true;
4503 if (mLastWin != null) {
4504 if (DEBUG_INPUT) Log.v(TAG,
4505 "Window " + mLastWin +
4506 " timed out on key input");
4507 if (mLastWin.mToken.paused) {
4508 Log.w(TAG, "Un-pausing dispatching to this window");
4509 mLastWin.mToken.paused = false;
4510 }
4511 }
4512 if (mMotionTarget == targetWin) {
4513 mMotionTarget = null;
4514 }
4515 mLastWin = null;
4516 mLastBinder = null;
4517 if (failIfTimeout || targetWin == null) {
4518 return null;
4519 }
4520 } else {
4521 Log.w(TAG, "Continuing to wait for key to be dispatched");
4522 startTime = SystemClock.uptimeMillis();
4523 }
4524 }
4525 }
4526 }
4527 }
4528
4529 Object findTargetWindow(KeyEvent nextKey, QueuedEvent qev,
4530 MotionEvent nextMotion, boolean isPointerEvent) {
4531 mOutsideTouchTargets = null;
4532
4533 if (nextKey != null) {
4534 // Find the target window for a normal key event.
4535 final int keycode = nextKey.getKeyCode();
4536 final int repeatCount = nextKey.getRepeatCount();
4537 final boolean down = nextKey.getAction() != KeyEvent.ACTION_UP;
4538 boolean dispatch = mKeyWaiter.checkShouldDispatchKey(keycode);
4539 if (!dispatch) {
4540 mPolicy.interceptKeyTi(null, keycode,
4541 nextKey.getMetaState(), down, repeatCount);
4542 Log.w(TAG, "Event timeout during app switch: dropping "
4543 + nextKey);
4544 return SKIP_TARGET_TOKEN;
4545 }
4546
4547 // System.out.println("##### [" + SystemClock.uptimeMillis() + "] WindowManagerService.dispatchKey(" + keycode + ", " + down + ", " + repeatCount + ")");
4548
4549 WindowState focus = null;
4550 synchronized(mWindowMap) {
4551 focus = getFocusedWindowLocked();
4552 }
4553
4554 wakeupIfNeeded(focus, LocalPowerManager.BUTTON_EVENT);
4555
4556 if (mPolicy.interceptKeyTi(focus,
4557 keycode, nextKey.getMetaState(), down, repeatCount)) {
4558 return CONSUMED_EVENT_TOKEN;
4559 }
4560
4561 return focus;
4562
4563 } else if (!isPointerEvent) {
4564 boolean dispatch = mKeyWaiter.checkShouldDispatchKey(-1);
4565 if (!dispatch) {
4566 Log.w(TAG, "Event timeout during app switch: dropping trackball "
4567 + nextMotion);
4568 return SKIP_TARGET_TOKEN;
4569 }
4570
4571 WindowState focus = null;
4572 synchronized(mWindowMap) {
4573 focus = getFocusedWindowLocked();
4574 }
4575
4576 wakeupIfNeeded(focus, LocalPowerManager.BUTTON_EVENT);
4577 return focus;
4578 }
4579
4580 if (nextMotion == null) {
4581 return SKIP_TARGET_TOKEN;
4582 }
4583
4584 boolean dispatch = mKeyWaiter.checkShouldDispatchKey(
4585 KeyEvent.KEYCODE_UNKNOWN);
4586 if (!dispatch) {
4587 Log.w(TAG, "Event timeout during app switch: dropping pointer "
4588 + nextMotion);
4589 return SKIP_TARGET_TOKEN;
4590 }
4591
4592 // Find the target window for a pointer event.
4593 int action = nextMotion.getAction();
4594 final float xf = nextMotion.getX();
4595 final float yf = nextMotion.getY();
4596 final long eventTime = nextMotion.getEventTime();
4597
4598 final boolean screenWasOff = qev != null
4599 && (qev.flags&WindowManagerPolicy.FLAG_BRIGHT_HERE) != 0;
4600
4601 WindowState target = null;
4602
4603 synchronized(mWindowMap) {
4604 synchronized (this) {
4605 if (action == MotionEvent.ACTION_DOWN) {
4606 if (mMotionTarget != null) {
4607 // this is weird, we got a pen down, but we thought it was
4608 // already down!
4609 // XXX: We should probably send an ACTION_UP to the current
4610 // target.
4611 Log.w(TAG, "Pointer down received while already down in: "
4612 + mMotionTarget);
4613 mMotionTarget = null;
4614 }
4615
4616 // ACTION_DOWN is special, because we need to lock next events to
4617 // the window we'll land onto.
4618 final int x = (int)xf;
4619 final int y = (int)yf;
4620
4621 final ArrayList windows = mWindows;
4622 final int N = windows.size();
4623 WindowState topErrWindow = null;
4624 final Rect tmpRect = mTempRect;
4625 for (int i=N-1; i>=0; i--) {
4626 WindowState child = (WindowState)windows.get(i);
4627 //Log.i(TAG, "Checking dispatch to: " + child);
4628 final int flags = child.mAttrs.flags;
4629 if ((flags & WindowManager.LayoutParams.FLAG_SYSTEM_ERROR) != 0) {
4630 if (topErrWindow == null) {
4631 topErrWindow = child;
4632 }
4633 }
4634 if (!child.isVisibleLw()) {
4635 //Log.i(TAG, "Not visible!");
4636 continue;
4637 }
4638 if ((flags & WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE) != 0) {
4639 //Log.i(TAG, "Not touchable!");
4640 if ((flags & WindowManager.LayoutParams
4641 .FLAG_WATCH_OUTSIDE_TOUCH) != 0) {
4642 child.mNextOutsideTouch = mOutsideTouchTargets;
4643 mOutsideTouchTargets = child;
4644 }
4645 continue;
4646 }
4647 tmpRect.set(child.mFrame);
4648 if (child.mTouchableInsets == ViewTreeObserver
4649 .InternalInsetsInfo.TOUCHABLE_INSETS_CONTENT) {
4650 // The touch is inside of the window if it is
4651 // inside the frame, AND the content part of that
4652 // frame that was given by the application.
4653 tmpRect.left += child.mGivenContentInsets.left;
4654 tmpRect.top += child.mGivenContentInsets.top;
4655 tmpRect.right -= child.mGivenContentInsets.right;
4656 tmpRect.bottom -= child.mGivenContentInsets.bottom;
4657 } else if (child.mTouchableInsets == ViewTreeObserver
4658 .InternalInsetsInfo.TOUCHABLE_INSETS_VISIBLE) {
4659 // The touch is inside of the window if it is
4660 // inside the frame, AND the visible part of that
4661 // frame that was given by the application.
4662 tmpRect.left += child.mGivenVisibleInsets.left;
4663 tmpRect.top += child.mGivenVisibleInsets.top;
4664 tmpRect.right -= child.mGivenVisibleInsets.right;
4665 tmpRect.bottom -= child.mGivenVisibleInsets.bottom;
4666 }
4667 final int touchFlags = flags &
4668 (WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
4669 |WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL);
4670 if (tmpRect.contains(x, y) || touchFlags == 0) {
4671 //Log.i(TAG, "Using this target!");
4672 if (!screenWasOff || (flags &
4673 WindowManager.LayoutParams.FLAG_TOUCHABLE_WHEN_WAKING) != 0) {
4674 mMotionTarget = child;
4675 } else {
4676 //Log.i(TAG, "Waking, skip!");
4677 mMotionTarget = null;
4678 }
4679 break;
4680 }
4681
4682 if ((flags & WindowManager.LayoutParams
4683 .FLAG_WATCH_OUTSIDE_TOUCH) != 0) {
4684 child.mNextOutsideTouch = mOutsideTouchTargets;
4685 mOutsideTouchTargets = child;
4686 //Log.i(TAG, "Adding to outside target list: " + child);
4687 }
4688 }
4689
4690 // if there's an error window but it's not accepting
4691 // focus (typically because it is not yet visible) just
4692 // wait for it -- any other focused window may in fact
4693 // be in ANR state.
4694 if (topErrWindow != null && mMotionTarget != topErrWindow) {
4695 mMotionTarget = null;
4696 }
4697 }
4698
4699 target = mMotionTarget;
4700 }
4701 }
4702
4703 wakeupIfNeeded(target, eventType(nextMotion));
4704
4705 // Pointer events are a little different -- if there isn't a
4706 // target found for any event, then just drop it.
4707 return target != null ? target : SKIP_TARGET_TOKEN;
4708 }
4709
4710 boolean checkShouldDispatchKey(int keycode) {
4711 synchronized (this) {
4712 if (mPolicy.isAppSwitchKeyTqTiLwLi(keycode)) {
4713 mTimeToSwitch = 0;
4714 return true;
4715 }
4716 if (mTimeToSwitch != 0
4717 && mTimeToSwitch < SystemClock.uptimeMillis()) {
4718 return false;
4719 }
4720 return true;
4721 }
4722 }
4723
4724 void bindTargetWindowLocked(WindowState win,
4725 int pendingWhat, QueuedEvent pendingMotion) {
4726 synchronized (this) {
4727 bindTargetWindowLockedLocked(win, pendingWhat, pendingMotion);
4728 }
4729 }
4730
4731 void bindTargetWindowLocked(WindowState win) {
4732 synchronized (this) {
4733 bindTargetWindowLockedLocked(win, RETURN_NOTHING, null);
4734 }
4735 }
4736
4737 void bindTargetWindowLockedLocked(WindowState win,
4738 int pendingWhat, QueuedEvent pendingMotion) {
4739 mLastWin = win;
4740 mLastBinder = win.mClient.asBinder();
4741 mFinished = false;
4742 if (pendingMotion != null) {
4743 final Session s = win.mSession;
4744 if (pendingWhat == RETURN_PENDING_POINTER) {
4745 releasePendingPointerLocked(s);
4746 s.mPendingPointerMove = pendingMotion;
4747 s.mPendingPointerWindow = win;
4748 if (DEBUG_INPUT) Log.v(TAG,
4749 "bindTargetToWindow " + s.mPendingPointerMove);
4750 } else if (pendingWhat == RETURN_PENDING_TRACKBALL) {
4751 releasePendingTrackballLocked(s);
4752 s.mPendingTrackballMove = pendingMotion;
4753 s.mPendingTrackballWindow = win;
4754 }
4755 }
4756 }
4757
4758 void releasePendingPointerLocked(Session s) {
4759 if (DEBUG_INPUT) Log.v(TAG,
4760 "releasePendingPointer " + s.mPendingPointerMove);
4761 if (s.mPendingPointerMove != null) {
4762 mQueue.recycleEvent(s.mPendingPointerMove);
4763 s.mPendingPointerMove = null;
4764 }
4765 }
4766
4767 void releasePendingTrackballLocked(Session s) {
4768 if (s.mPendingTrackballMove != null) {
4769 mQueue.recycleEvent(s.mPendingTrackballMove);
4770 s.mPendingTrackballMove = null;
4771 }
4772 }
4773
4774 MotionEvent finishedKey(Session session, IWindow client, boolean force,
4775 int returnWhat) {
4776 if (DEBUG_INPUT) Log.v(
4777 TAG, "finishedKey: client=" + client + ", force=" + force);
4778
4779 if (client == null) {
4780 return null;
4781 }
4782
4783 synchronized (this) {
4784 if (DEBUG_INPUT) Log.v(
4785 TAG, "finishedKey: client=" + client.asBinder()
4786 + ", force=" + force + ", last=" + mLastBinder
4787 + " (token=" + (mLastWin != null ? mLastWin.mToken : null) + ")");
4788
4789 QueuedEvent qev = null;
4790 WindowState win = null;
4791 if (returnWhat == RETURN_PENDING_POINTER) {
4792 qev = session.mPendingPointerMove;
4793 win = session.mPendingPointerWindow;
4794 session.mPendingPointerMove = null;
4795 session.mPendingPointerWindow = null;
4796 } else if (returnWhat == RETURN_PENDING_TRACKBALL) {
4797 qev = session.mPendingTrackballMove;
4798 win = session.mPendingTrackballWindow;
4799 session.mPendingTrackballMove = null;
4800 session.mPendingTrackballWindow = null;
4801 }
4802
4803 if (mLastBinder == client.asBinder()) {
4804 if (DEBUG_INPUT) Log.v(
4805 TAG, "finishedKey: last paused="
4806 + ((mLastWin != null) ? mLastWin.mToken.paused : "null"));
4807 if (mLastWin != null && (!mLastWin.mToken.paused || force
4808 || !mEventDispatching)) {
4809 doFinishedKeyLocked(false);
4810 } else {
4811 // Make sure to wake up anyone currently waiting to
4812 // dispatch a key, so they can re-evaluate their
4813 // current situation.
4814 mFinished = true;
4815 notifyAll();
4816 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004817 }
4818
4819 if (qev != null) {
4820 MotionEvent res = (MotionEvent)qev.event;
4821 if (DEBUG_INPUT) Log.v(TAG,
4822 "Returning pending motion: " + res);
4823 mQueue.recycleEvent(qev);
4824 if (win != null && returnWhat == RETURN_PENDING_POINTER) {
4825 res.offsetLocation(-win.mFrame.left, -win.mFrame.top);
4826 }
4827 return res;
4828 }
4829 return null;
4830 }
4831 }
4832
4833 void tickle() {
4834 synchronized (this) {
4835 notifyAll();
4836 }
4837 }
4838
4839 void handleNewWindowLocked(WindowState newWindow) {
4840 if (!newWindow.canReceiveKeys()) {
4841 return;
4842 }
4843 synchronized (this) {
The Android Open Source Projectc474dec2009-03-04 09:49:09 -08004844 if (DEBUG_INPUT) Log.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004845 TAG, "New key dispatch window: win="
4846 + newWindow.mClient.asBinder()
4847 + ", last=" + mLastBinder
4848 + " (token=" + (mLastWin != null ? mLastWin.mToken : null)
4849 + "), finished=" + mFinished + ", paused="
4850 + newWindow.mToken.paused);
4851
4852 // Displaying a window implicitly causes dispatching to
4853 // be unpaused. (This is to protect against bugs if someone
4854 // pauses dispatching but forgets to resume.)
4855 newWindow.mToken.paused = false;
4856
4857 mGotFirstWindow = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004858
4859 if ((newWindow.mAttrs.flags & FLAG_SYSTEM_ERROR) != 0) {
4860 if (DEBUG_INPUT) Log.v(TAG,
4861 "New SYSTEM_ERROR window; resetting state");
4862 mLastWin = null;
4863 mLastBinder = null;
4864 mMotionTarget = null;
4865 mFinished = true;
4866 } else if (mLastWin != null) {
4867 // If the new window is above the window we are
4868 // waiting on, then stop waiting and let key dispatching
4869 // start on the new guy.
4870 if (DEBUG_INPUT) Log.v(
4871 TAG, "Last win layer=" + mLastWin.mLayer
4872 + ", new win layer=" + newWindow.mLayer);
4873 if (newWindow.mLayer >= mLastWin.mLayer) {
The Android Open Source Projectc474dec2009-03-04 09:49:09 -08004874 // The new window is above the old; finish pending input to the last
4875 // window and start directing it to the new one.
4876 mLastWin.mToken.paused = false;
4877 doFinishedKeyLocked(true); // does a notifyAll()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004878 }
The Android Open Source Projectc474dec2009-03-04 09:49:09 -08004879 // Either the new window is lower, so there is no need to wake key waiters,
4880 // or we just finished key input to the previous window, which implicitly
4881 // notified the key waiters. In both cases, we don't need to issue the
4882 // notification here.
4883 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004884 }
4885
The Android Open Source Projectc474dec2009-03-04 09:49:09 -08004886 // Now that we've put a new window state in place, make the event waiter
4887 // take notice and retarget its attentions.
4888 notifyAll();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004889 }
4890 }
4891
4892 void pauseDispatchingLocked(WindowToken token) {
4893 synchronized (this)
4894 {
4895 if (DEBUG_INPUT) Log.v(TAG, "Pausing WindowToken " + token);
4896 token.paused = true;
4897
4898 /*
4899 if (mLastWin != null && !mFinished && mLastWin.mBaseLayer <= layer) {
4900 mPaused = true;
4901 } else {
4902 if (mLastWin == null) {
Dave Bortcfe65242009-04-09 14:51:04 -07004903 Log.i(TAG, "Key dispatching not paused: no last window.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004904 } else if (mFinished) {
Dave Bortcfe65242009-04-09 14:51:04 -07004905 Log.i(TAG, "Key dispatching not paused: finished last key.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004906 } else {
Dave Bortcfe65242009-04-09 14:51:04 -07004907 Log.i(TAG, "Key dispatching not paused: window in higher layer.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004908 }
4909 }
4910 */
4911 }
4912 }
4913
4914 void resumeDispatchingLocked(WindowToken token) {
4915 synchronized (this) {
4916 if (token.paused) {
4917 if (DEBUG_INPUT) Log.v(
4918 TAG, "Resuming WindowToken " + token
4919 + ", last=" + mLastBinder
4920 + " (token=" + (mLastWin != null ? mLastWin.mToken : null)
4921 + "), finished=" + mFinished + ", paused="
4922 + token.paused);
4923 token.paused = false;
4924 if (mLastWin != null && mLastWin.mToken == token && mFinished) {
4925 doFinishedKeyLocked(true);
4926 } else {
4927 notifyAll();
4928 }
4929 }
4930 }
4931 }
4932
4933 void setEventDispatchingLocked(boolean enabled) {
4934 synchronized (this) {
4935 mEventDispatching = enabled;
4936 notifyAll();
4937 }
4938 }
4939
4940 void appSwitchComing() {
4941 synchronized (this) {
4942 // Don't wait for more than .5 seconds for app to finish
4943 // processing the pending events.
4944 long now = SystemClock.uptimeMillis() + 500;
4945 if (DEBUG_INPUT) Log.v(TAG, "appSwitchComing: " + now);
4946 if (mTimeToSwitch == 0 || now < mTimeToSwitch) {
4947 mTimeToSwitch = now;
4948 }
4949 notifyAll();
4950 }
4951 }
4952
4953 private final void doFinishedKeyLocked(boolean doRecycle) {
4954 if (mLastWin != null) {
4955 releasePendingPointerLocked(mLastWin.mSession);
4956 releasePendingTrackballLocked(mLastWin.mSession);
4957 }
4958
4959 if (mLastWin == null || !mLastWin.mToken.paused
4960 || !mLastWin.isVisibleLw()) {
4961 // If the current window has been paused, we aren't -really-
4962 // finished... so let the waiters still wait.
4963 mLastWin = null;
4964 mLastBinder = null;
4965 }
4966 mFinished = true;
4967 notifyAll();
4968 }
4969 }
4970
4971 private class KeyQ extends KeyInputQueue
4972 implements KeyInputQueue.FilterCallback {
4973 PowerManager.WakeLock mHoldingScreen;
4974
4975 KeyQ() {
4976 super(mContext);
4977 PowerManager pm = (PowerManager)mContext.getSystemService(Context.POWER_SERVICE);
4978 mHoldingScreen = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK,
4979 "KEEP_SCREEN_ON_FLAG");
4980 mHoldingScreen.setReferenceCounted(false);
4981 }
4982
4983 @Override
4984 boolean preprocessEvent(InputDevice device, RawInputEvent event) {
4985 if (mPolicy.preprocessInputEventTq(event)) {
4986 return true;
4987 }
4988
4989 switch (event.type) {
4990 case RawInputEvent.EV_KEY: {
4991 // XXX begin hack
4992 if (DEBUG) {
4993 if (event.keycode == KeyEvent.KEYCODE_G) {
4994 if (event.value != 0) {
4995 // G down
4996 mPolicy.screenTurnedOff(WindowManagerPolicy.OFF_BECAUSE_OF_USER);
4997 }
4998 return false;
4999 }
5000 if (event.keycode == KeyEvent.KEYCODE_D) {
5001 if (event.value != 0) {
5002 //dump();
5003 }
5004 return false;
5005 }
5006 }
5007 // XXX end hack
5008
5009 boolean screenIsOff = !mPowerManager.screenIsOn();
5010 boolean screenIsDim = !mPowerManager.screenIsBright();
5011 int actions = mPolicy.interceptKeyTq(event, !screenIsOff);
5012
5013 if ((actions & WindowManagerPolicy.ACTION_GO_TO_SLEEP) != 0) {
5014 mPowerManager.goToSleep(event.when);
5015 }
5016
5017 if (screenIsOff) {
5018 event.flags |= WindowManagerPolicy.FLAG_WOKE_HERE;
5019 }
5020 if (screenIsDim) {
5021 event.flags |= WindowManagerPolicy.FLAG_BRIGHT_HERE;
5022 }
5023 if ((actions & WindowManagerPolicy.ACTION_POKE_USER_ACTIVITY) != 0) {
5024 mPowerManager.userActivity(event.when, false,
Michael Chane96440f2009-05-06 10:27:36 -07005025 LocalPowerManager.BUTTON_EVENT, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005026 }
5027
5028 if ((actions & WindowManagerPolicy.ACTION_PASS_TO_USER) != 0) {
5029 if (event.value != 0 && mPolicy.isAppSwitchKeyTqTiLwLi(event.keycode)) {
5030 filterQueue(this);
5031 mKeyWaiter.appSwitchComing();
5032 }
5033 return true;
5034 } else {
5035 return false;
5036 }
5037 }
5038
5039 case RawInputEvent.EV_REL: {
5040 boolean screenIsOff = !mPowerManager.screenIsOn();
5041 boolean screenIsDim = !mPowerManager.screenIsBright();
5042 if (screenIsOff) {
5043 if (!mPolicy.isWakeRelMovementTq(event.deviceId,
5044 device.classes, event)) {
5045 //Log.i(TAG, "dropping because screenIsOff and !isWakeKey");
5046 return false;
5047 }
5048 event.flags |= WindowManagerPolicy.FLAG_WOKE_HERE;
5049 }
5050 if (screenIsDim) {
5051 event.flags |= WindowManagerPolicy.FLAG_BRIGHT_HERE;
5052 }
5053 return true;
5054 }
5055
5056 case RawInputEvent.EV_ABS: {
5057 boolean screenIsOff = !mPowerManager.screenIsOn();
5058 boolean screenIsDim = !mPowerManager.screenIsBright();
5059 if (screenIsOff) {
5060 if (!mPolicy.isWakeAbsMovementTq(event.deviceId,
5061 device.classes, event)) {
5062 //Log.i(TAG, "dropping because screenIsOff and !isWakeKey");
5063 return false;
5064 }
5065 event.flags |= WindowManagerPolicy.FLAG_WOKE_HERE;
5066 }
5067 if (screenIsDim) {
5068 event.flags |= WindowManagerPolicy.FLAG_BRIGHT_HERE;
5069 }
5070 return true;
5071 }
5072
5073 default:
5074 return true;
5075 }
5076 }
5077
5078 public int filterEvent(QueuedEvent ev) {
5079 switch (ev.classType) {
5080 case RawInputEvent.CLASS_KEYBOARD:
5081 KeyEvent ke = (KeyEvent)ev.event;
5082 if (mPolicy.isMovementKeyTi(ke.getKeyCode())) {
5083 Log.w(TAG, "Dropping movement key during app switch: "
5084 + ke.getKeyCode() + ", action=" + ke.getAction());
5085 return FILTER_REMOVE;
5086 }
5087 return FILTER_ABORT;
5088 default:
5089 return FILTER_KEEP;
5090 }
5091 }
5092
5093 /**
5094 * Must be called with the main window manager lock held.
5095 */
5096 void setHoldScreenLocked(boolean holding) {
5097 boolean state = mHoldingScreen.isHeld();
5098 if (holding != state) {
5099 if (holding) {
5100 mHoldingScreen.acquire();
5101 } else {
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07005102 mPolicy.screenOnStoppedLw();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005103 mHoldingScreen.release();
5104 }
5105 }
5106 }
Michael Chan53071d62009-05-13 17:29:48 -07005107 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005108
5109 public boolean detectSafeMode() {
5110 mSafeMode = mPolicy.detectSafeMode();
5111 return mSafeMode;
5112 }
5113
5114 public void systemReady() {
5115 mPolicy.systemReady();
5116 }
5117
5118 private final class InputDispatcherThread extends Thread {
5119 // Time to wait when there is nothing to do: 9999 seconds.
5120 static final int LONG_WAIT=9999*1000;
5121
5122 public InputDispatcherThread() {
5123 super("InputDispatcher");
5124 }
5125
5126 @Override
5127 public void run() {
5128 while (true) {
5129 try {
5130 process();
5131 } catch (Exception e) {
5132 Log.e(TAG, "Exception in input dispatcher", e);
5133 }
5134 }
5135 }
5136
5137 private void process() {
5138 android.os.Process.setThreadPriority(
5139 android.os.Process.THREAD_PRIORITY_URGENT_DISPLAY);
5140
5141 // The last key event we saw
5142 KeyEvent lastKey = null;
5143
5144 // Last keydown time for auto-repeating keys
5145 long lastKeyTime = SystemClock.uptimeMillis();
5146 long nextKeyTime = lastKeyTime+LONG_WAIT;
5147
5148 // How many successive repeats we generated
5149 int keyRepeatCount = 0;
5150
5151 // Need to report that configuration has changed?
5152 boolean configChanged = false;
5153
5154 while (true) {
5155 long curTime = SystemClock.uptimeMillis();
5156
5157 if (DEBUG_INPUT) Log.v(
5158 TAG, "Waiting for next key: now=" + curTime
5159 + ", repeat @ " + nextKeyTime);
5160
5161 // Retrieve next event, waiting only as long as the next
5162 // repeat timeout. If the configuration has changed, then
5163 // don't wait at all -- we'll report the change as soon as
5164 // we have processed all events.
5165 QueuedEvent ev = mQueue.getEvent(
5166 (int)((!configChanged && curTime < nextKeyTime)
5167 ? (nextKeyTime-curTime) : 0));
5168
5169 if (DEBUG_INPUT && ev != null) Log.v(
5170 TAG, "Event: type=" + ev.classType + " data=" + ev.event);
5171
Michael Chan53071d62009-05-13 17:29:48 -07005172 if (MEASURE_LATENCY) {
5173 lt.sample("2 got event ", System.nanoTime() - ev.whenNano);
5174 }
5175
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005176 try {
5177 if (ev != null) {
Michael Chan53071d62009-05-13 17:29:48 -07005178 curTime = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005179 int eventType;
5180 if (ev.classType == RawInputEvent.CLASS_TOUCHSCREEN) {
5181 eventType = eventType((MotionEvent)ev.event);
5182 } else if (ev.classType == RawInputEvent.CLASS_KEYBOARD ||
5183 ev.classType == RawInputEvent.CLASS_TRACKBALL) {
5184 eventType = LocalPowerManager.BUTTON_EVENT;
5185 } else {
5186 eventType = LocalPowerManager.OTHER_EVENT;
5187 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07005188 try {
Michael Chan53071d62009-05-13 17:29:48 -07005189 if ((curTime - mLastBatteryStatsCallTime)
Michael Chane96440f2009-05-06 10:27:36 -07005190 >= MIN_TIME_BETWEEN_USERACTIVITIES) {
Michael Chan53071d62009-05-13 17:29:48 -07005191 mLastBatteryStatsCallTime = curTime;
Michael Chane96440f2009-05-06 10:27:36 -07005192 mBatteryStats.noteInputEvent();
5193 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07005194 } catch (RemoteException e) {
5195 // Ignore
5196 }
Michael Chane10de972009-05-18 11:24:50 -07005197
5198 if (eventType != TOUCH_EVENT
5199 && eventType != LONG_TOUCH_EVENT
5200 && eventType != CHEEK_EVENT) {
5201 mPowerManager.userActivity(curTime, false,
5202 eventType, false);
5203 } else if (mLastTouchEventType != eventType
5204 || (curTime - mLastUserActivityCallTime)
5205 >= MIN_TIME_BETWEEN_USERACTIVITIES) {
5206 mLastUserActivityCallTime = curTime;
5207 mLastTouchEventType = eventType;
5208 mPowerManager.userActivity(curTime, false,
5209 eventType, false);
5210 }
5211
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005212 switch (ev.classType) {
5213 case RawInputEvent.CLASS_KEYBOARD:
5214 KeyEvent ke = (KeyEvent)ev.event;
5215 if (ke.isDown()) {
5216 lastKey = ke;
5217 keyRepeatCount = 0;
5218 lastKeyTime = curTime;
5219 nextKeyTime = lastKeyTime
5220 + KEY_REPEAT_FIRST_DELAY;
5221 if (DEBUG_INPUT) Log.v(
5222 TAG, "Received key down: first repeat @ "
5223 + nextKeyTime);
5224 } else {
5225 lastKey = null;
5226 // Arbitrary long timeout.
5227 lastKeyTime = curTime;
5228 nextKeyTime = curTime + LONG_WAIT;
5229 if (DEBUG_INPUT) Log.v(
5230 TAG, "Received key up: ignore repeat @ "
5231 + nextKeyTime);
5232 }
5233 dispatchKey((KeyEvent)ev.event, 0, 0);
5234 mQueue.recycleEvent(ev);
5235 break;
5236 case RawInputEvent.CLASS_TOUCHSCREEN:
5237 //Log.i(TAG, "Read next event " + ev);
5238 dispatchPointer(ev, (MotionEvent)ev.event, 0, 0);
5239 break;
5240 case RawInputEvent.CLASS_TRACKBALL:
5241 dispatchTrackball(ev, (MotionEvent)ev.event, 0, 0);
5242 break;
5243 case RawInputEvent.CLASS_CONFIGURATION_CHANGED:
5244 configChanged = true;
5245 break;
5246 default:
5247 mQueue.recycleEvent(ev);
5248 break;
5249 }
5250
5251 } else if (configChanged) {
5252 configChanged = false;
5253 sendNewConfiguration();
5254
5255 } else if (lastKey != null) {
5256 curTime = SystemClock.uptimeMillis();
5257
5258 // Timeout occurred while key was down. If it is at or
5259 // past the key repeat time, dispatch the repeat.
5260 if (DEBUG_INPUT) Log.v(
5261 TAG, "Key timeout: repeat=" + nextKeyTime
5262 + ", now=" + curTime);
5263 if (curTime < nextKeyTime) {
5264 continue;
5265 }
5266
5267 lastKeyTime = nextKeyTime;
5268 nextKeyTime = nextKeyTime + KEY_REPEAT_DELAY;
5269 keyRepeatCount++;
5270 if (DEBUG_INPUT) Log.v(
5271 TAG, "Key repeat: count=" + keyRepeatCount
5272 + ", next @ " + nextKeyTime);
The Android Open Source Project10592532009-03-18 17:39:46 -07005273 dispatchKey(KeyEvent.changeTimeRepeat(lastKey, curTime, keyRepeatCount), 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005274
5275 } else {
5276 curTime = SystemClock.uptimeMillis();
5277
5278 lastKeyTime = curTime;
5279 nextKeyTime = curTime + LONG_WAIT;
5280 }
5281
5282 } catch (Exception e) {
5283 Log.e(TAG,
5284 "Input thread received uncaught exception: " + e, e);
5285 }
5286 }
5287 }
5288 }
5289
5290 // -------------------------------------------------------------
5291 // Client Session State
5292 // -------------------------------------------------------------
5293
5294 private final class Session extends IWindowSession.Stub
5295 implements IBinder.DeathRecipient {
5296 final IInputMethodClient mClient;
5297 final IInputContext mInputContext;
5298 final int mUid;
5299 final int mPid;
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005300 final String mStringName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005301 SurfaceSession mSurfaceSession;
5302 int mNumWindow = 0;
5303 boolean mClientDead = false;
5304
5305 /**
5306 * Current pointer move event being dispatched to client window... must
5307 * hold key lock to access.
5308 */
5309 QueuedEvent mPendingPointerMove;
5310 WindowState mPendingPointerWindow;
5311
5312 /**
5313 * Current trackball move event being dispatched to client window... must
5314 * hold key lock to access.
5315 */
5316 QueuedEvent mPendingTrackballMove;
5317 WindowState mPendingTrackballWindow;
5318
5319 public Session(IInputMethodClient client, IInputContext inputContext) {
5320 mClient = client;
5321 mInputContext = inputContext;
5322 mUid = Binder.getCallingUid();
5323 mPid = Binder.getCallingPid();
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005324 StringBuilder sb = new StringBuilder();
5325 sb.append("Session{");
5326 sb.append(Integer.toHexString(System.identityHashCode(this)));
5327 sb.append(" uid ");
5328 sb.append(mUid);
5329 sb.append("}");
5330 mStringName = sb.toString();
5331
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005332 synchronized (mWindowMap) {
5333 if (mInputMethodManager == null && mHaveInputMethods) {
5334 IBinder b = ServiceManager.getService(
5335 Context.INPUT_METHOD_SERVICE);
5336 mInputMethodManager = IInputMethodManager.Stub.asInterface(b);
5337 }
5338 }
5339 long ident = Binder.clearCallingIdentity();
5340 try {
5341 // Note: it is safe to call in to the input method manager
5342 // here because we are not holding our lock.
5343 if (mInputMethodManager != null) {
5344 mInputMethodManager.addClient(client, inputContext,
5345 mUid, mPid);
5346 } else {
5347 client.setUsingInputMethod(false);
5348 }
5349 client.asBinder().linkToDeath(this, 0);
5350 } catch (RemoteException e) {
5351 // The caller has died, so we can just forget about this.
5352 try {
5353 if (mInputMethodManager != null) {
5354 mInputMethodManager.removeClient(client);
5355 }
5356 } catch (RemoteException ee) {
5357 }
5358 } finally {
5359 Binder.restoreCallingIdentity(ident);
5360 }
5361 }
5362
5363 @Override
5364 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
5365 throws RemoteException {
5366 try {
5367 return super.onTransact(code, data, reply, flags);
5368 } catch (RuntimeException e) {
5369 // Log all 'real' exceptions thrown to the caller
5370 if (!(e instanceof SecurityException)) {
5371 Log.e(TAG, "Window Session Crash", e);
5372 }
5373 throw e;
5374 }
5375 }
5376
5377 public void binderDied() {
5378 // Note: it is safe to call in to the input method manager
5379 // here because we are not holding our lock.
5380 try {
5381 if (mInputMethodManager != null) {
5382 mInputMethodManager.removeClient(mClient);
5383 }
5384 } catch (RemoteException e) {
5385 }
5386 synchronized(mWindowMap) {
5387 mClientDead = true;
5388 killSessionLocked();
5389 }
5390 }
5391
5392 public int add(IWindow window, WindowManager.LayoutParams attrs,
5393 int viewVisibility, Rect outContentInsets) {
5394 return addWindow(this, window, attrs, viewVisibility, outContentInsets);
5395 }
5396
5397 public void remove(IWindow window) {
5398 removeWindow(this, window);
5399 }
5400
5401 public int relayout(IWindow window, WindowManager.LayoutParams attrs,
5402 int requestedWidth, int requestedHeight, int viewFlags,
5403 boolean insetsPending, Rect outFrame, Rect outContentInsets,
5404 Rect outVisibleInsets, Surface outSurface) {
5405 return relayoutWindow(this, window, attrs,
5406 requestedWidth, requestedHeight, viewFlags, insetsPending,
5407 outFrame, outContentInsets, outVisibleInsets, outSurface);
5408 }
5409
5410 public void setTransparentRegion(IWindow window, Region region) {
5411 setTransparentRegionWindow(this, window, region);
5412 }
5413
5414 public void setInsets(IWindow window, int touchableInsets,
5415 Rect contentInsets, Rect visibleInsets) {
5416 setInsetsWindow(this, window, touchableInsets, contentInsets,
5417 visibleInsets);
5418 }
5419
5420 public void getDisplayFrame(IWindow window, Rect outDisplayFrame) {
5421 getWindowDisplayFrame(this, window, outDisplayFrame);
5422 }
5423
5424 public void finishDrawing(IWindow window) {
5425 if (localLOGV) Log.v(
5426 TAG, "IWindow finishDrawing called for " + window);
5427 finishDrawingWindow(this, window);
5428 }
5429
5430 public void finishKey(IWindow window) {
5431 if (localLOGV) Log.v(
5432 TAG, "IWindow finishKey called for " + window);
5433 mKeyWaiter.finishedKey(this, window, false,
5434 KeyWaiter.RETURN_NOTHING);
5435 }
5436
5437 public MotionEvent getPendingPointerMove(IWindow window) {
5438 if (localLOGV) Log.v(
5439 TAG, "IWindow getPendingMotionEvent called for " + window);
5440 return mKeyWaiter.finishedKey(this, window, false,
5441 KeyWaiter.RETURN_PENDING_POINTER);
5442 }
5443
5444 public MotionEvent getPendingTrackballMove(IWindow window) {
5445 if (localLOGV) Log.v(
5446 TAG, "IWindow getPendingMotionEvent called for " + window);
5447 return mKeyWaiter.finishedKey(this, window, false,
5448 KeyWaiter.RETURN_PENDING_TRACKBALL);
5449 }
5450
5451 public void setInTouchMode(boolean mode) {
5452 synchronized(mWindowMap) {
5453 mInTouchMode = mode;
5454 }
5455 }
5456
5457 public boolean getInTouchMode() {
5458 synchronized(mWindowMap) {
5459 return mInTouchMode;
5460 }
5461 }
5462
5463 public boolean performHapticFeedback(IWindow window, int effectId,
5464 boolean always) {
5465 synchronized(mWindowMap) {
5466 long ident = Binder.clearCallingIdentity();
5467 try {
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07005468 return mPolicy.performHapticFeedbackLw(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005469 windowForClientLocked(this, window), effectId, always);
5470 } finally {
5471 Binder.restoreCallingIdentity(ident);
5472 }
5473 }
5474 }
5475
5476 void windowAddedLocked() {
5477 if (mSurfaceSession == null) {
5478 if (localLOGV) Log.v(
5479 TAG, "First window added to " + this + ", creating SurfaceSession");
5480 mSurfaceSession = new SurfaceSession();
5481 mSessions.add(this);
5482 }
5483 mNumWindow++;
5484 }
5485
5486 void windowRemovedLocked() {
5487 mNumWindow--;
5488 killSessionLocked();
5489 }
5490
5491 void killSessionLocked() {
5492 if (mNumWindow <= 0 && mClientDead) {
5493 mSessions.remove(this);
5494 if (mSurfaceSession != null) {
5495 if (localLOGV) Log.v(
5496 TAG, "Last window removed from " + this
5497 + ", destroying " + mSurfaceSession);
5498 try {
5499 mSurfaceSession.kill();
5500 } catch (Exception e) {
5501 Log.w(TAG, "Exception thrown when killing surface session "
5502 + mSurfaceSession + " in session " + this
5503 + ": " + e.toString());
5504 }
5505 mSurfaceSession = null;
5506 }
5507 }
5508 }
5509
5510 void dump(PrintWriter pw, String prefix) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005511 pw.print(prefix); pw.print("mNumWindow="); pw.print(mNumWindow);
5512 pw.print(" mClientDead="); pw.print(mClientDead);
5513 pw.print(" mSurfaceSession="); pw.println(mSurfaceSession);
5514 if (mPendingPointerWindow != null || mPendingPointerMove != null) {
5515 pw.print(prefix);
5516 pw.print("mPendingPointerWindow="); pw.print(mPendingPointerWindow);
5517 pw.print(" mPendingPointerMove="); pw.println(mPendingPointerMove);
5518 }
5519 if (mPendingTrackballWindow != null || mPendingTrackballMove != null) {
5520 pw.print(prefix);
5521 pw.print("mPendingTrackballWindow="); pw.print(mPendingTrackballWindow);
5522 pw.print(" mPendingTrackballMove="); pw.println(mPendingTrackballMove);
5523 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005524 }
5525
5526 @Override
5527 public String toString() {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005528 return mStringName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005529 }
5530 }
5531
5532 // -------------------------------------------------------------
5533 // Client Window State
5534 // -------------------------------------------------------------
5535
5536 private final class WindowState implements WindowManagerPolicy.WindowState {
5537 final Session mSession;
5538 final IWindow mClient;
5539 WindowToken mToken;
The Android Open Source Project10592532009-03-18 17:39:46 -07005540 WindowToken mRootToken;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005541 AppWindowToken mAppToken;
5542 AppWindowToken mTargetAppToken;
5543 final WindowManager.LayoutParams mAttrs = new WindowManager.LayoutParams();
5544 final DeathRecipient mDeathRecipient;
5545 final WindowState mAttachedWindow;
5546 final ArrayList mChildWindows = new ArrayList();
5547 final int mBaseLayer;
5548 final int mSubLayer;
5549 final boolean mLayoutAttached;
5550 final boolean mIsImWindow;
5551 int mViewVisibility;
5552 boolean mPolicyVisibility = true;
5553 boolean mPolicyVisibilityAfterAnim = true;
5554 boolean mAppFreezing;
5555 Surface mSurface;
5556 boolean mAttachedHidden; // is our parent window hidden?
5557 boolean mLastHidden; // was this window last hidden?
5558 int mRequestedWidth;
5559 int mRequestedHeight;
5560 int mLastRequestedWidth;
5561 int mLastRequestedHeight;
5562 int mReqXPos;
5563 int mReqYPos;
5564 int mLayer;
5565 int mAnimLayer;
5566 int mLastLayer;
5567 boolean mHaveFrame;
5568
5569 WindowState mNextOutsideTouch;
5570
5571 // Actual frame shown on-screen (may be modified by animation)
5572 final Rect mShownFrame = new Rect();
5573 final Rect mLastShownFrame = new Rect();
5574
5575 /**
5576 * Insets that determine the actually visible area
5577 */
5578 final Rect mVisibleInsets = new Rect();
5579 final Rect mLastVisibleInsets = new Rect();
5580 boolean mVisibleInsetsChanged;
5581
5582 /**
5583 * Insets that are covered by system windows
5584 */
5585 final Rect mContentInsets = new Rect();
5586 final Rect mLastContentInsets = new Rect();
5587 boolean mContentInsetsChanged;
5588
5589 /**
5590 * Set to true if we are waiting for this window to receive its
5591 * given internal insets before laying out other windows based on it.
5592 */
5593 boolean mGivenInsetsPending;
5594
5595 /**
5596 * These are the content insets that were given during layout for
5597 * this window, to be applied to windows behind it.
5598 */
5599 final Rect mGivenContentInsets = new Rect();
5600
5601 /**
5602 * These are the visible insets that were given during layout for
5603 * this window, to be applied to windows behind it.
5604 */
5605 final Rect mGivenVisibleInsets = new Rect();
5606
5607 /**
5608 * Flag indicating whether the touchable region should be adjusted by
5609 * the visible insets; if false the area outside the visible insets is
5610 * NOT touchable, so we must use those to adjust the frame during hit
5611 * tests.
5612 */
5613 int mTouchableInsets = ViewTreeObserver.InternalInsetsInfo.TOUCHABLE_INSETS_FRAME;
5614
5615 // Current transformation being applied.
5616 float mDsDx=1, mDtDx=0, mDsDy=0, mDtDy=1;
5617 float mLastDsDx=1, mLastDtDx=0, mLastDsDy=0, mLastDtDy=1;
5618 float mHScale=1, mVScale=1;
5619 float mLastHScale=1, mLastVScale=1;
5620 final Matrix mTmpMatrix = new Matrix();
5621
5622 // "Real" frame that the application sees.
5623 final Rect mFrame = new Rect();
5624 final Rect mLastFrame = new Rect();
5625
5626 final Rect mContainingFrame = new Rect();
5627 final Rect mDisplayFrame = new Rect();
5628 final Rect mContentFrame = new Rect();
5629 final Rect mVisibleFrame = new Rect();
5630
5631 float mShownAlpha = 1;
5632 float mAlpha = 1;
5633 float mLastAlpha = 1;
5634
5635 // Set to true if, when the window gets displayed, it should perform
5636 // an enter animation.
5637 boolean mEnterAnimationPending;
5638
5639 // Currently running animation.
5640 boolean mAnimating;
5641 boolean mLocalAnimating;
5642 Animation mAnimation;
5643 boolean mAnimationIsEntrance;
5644 boolean mHasTransformation;
5645 boolean mHasLocalTransformation;
5646 final Transformation mTransformation = new Transformation();
5647
5648 // This is set after IWindowSession.relayout() has been called at
5649 // least once for the window. It allows us to detect the situation
5650 // where we don't yet have a surface, but should have one soon, so
5651 // we can give the window focus before waiting for the relayout.
5652 boolean mRelayoutCalled;
5653
5654 // This is set after the Surface has been created but before the
5655 // window has been drawn. During this time the surface is hidden.
5656 boolean mDrawPending;
5657
5658 // This is set after the window has finished drawing for the first
5659 // time but before its surface is shown. The surface will be
5660 // displayed when the next layout is run.
5661 boolean mCommitDrawPending;
5662
5663 // This is set during the time after the window's drawing has been
5664 // committed, and before its surface is actually shown. It is used
5665 // to delay showing the surface until all windows in a token are ready
5666 // to be shown.
5667 boolean mReadyToShow;
5668
5669 // Set when the window has been shown in the screen the first time.
5670 boolean mHasDrawn;
5671
5672 // Currently running an exit animation?
5673 boolean mExiting;
5674
5675 // Currently on the mDestroySurface list?
5676 boolean mDestroying;
5677
5678 // Completely remove from window manager after exit animation?
5679 boolean mRemoveOnExit;
5680
5681 // Set when the orientation is changing and this window has not yet
5682 // been updated for the new orientation.
5683 boolean mOrientationChanging;
5684
5685 // Is this window now (or just being) removed?
5686 boolean mRemoved;
5687
5688 WindowState(Session s, IWindow c, WindowToken token,
5689 WindowState attachedWindow, WindowManager.LayoutParams a,
5690 int viewVisibility) {
5691 mSession = s;
5692 mClient = c;
5693 mToken = token;
5694 mAttrs.copyFrom(a);
5695 mViewVisibility = viewVisibility;
5696 DeathRecipient deathRecipient = new DeathRecipient();
5697 mAlpha = a.alpha;
5698 if (localLOGV) Log.v(
5699 TAG, "Window " + this + " client=" + c.asBinder()
5700 + " token=" + token + " (" + mAttrs.token + ")");
5701 try {
5702 c.asBinder().linkToDeath(deathRecipient, 0);
5703 } catch (RemoteException e) {
5704 mDeathRecipient = null;
5705 mAttachedWindow = null;
5706 mLayoutAttached = false;
5707 mIsImWindow = false;
5708 mBaseLayer = 0;
5709 mSubLayer = 0;
5710 return;
5711 }
5712 mDeathRecipient = deathRecipient;
5713
5714 if ((mAttrs.type >= FIRST_SUB_WINDOW &&
5715 mAttrs.type <= LAST_SUB_WINDOW)) {
5716 // The multiplier here is to reserve space for multiple
5717 // windows in the same type layer.
5718 mBaseLayer = mPolicy.windowTypeToLayerLw(
5719 attachedWindow.mAttrs.type) * TYPE_LAYER_MULTIPLIER
5720 + TYPE_LAYER_OFFSET;
5721 mSubLayer = mPolicy.subWindowTypeToLayerLw(a.type);
5722 mAttachedWindow = attachedWindow;
5723 mAttachedWindow.mChildWindows.add(this);
5724 mLayoutAttached = mAttrs.type !=
5725 WindowManager.LayoutParams.TYPE_APPLICATION_ATTACHED_DIALOG;
5726 mIsImWindow = attachedWindow.mAttrs.type == TYPE_INPUT_METHOD
5727 || attachedWindow.mAttrs.type == TYPE_INPUT_METHOD_DIALOG;
5728 } else {
5729 // The multiplier here is to reserve space for multiple
5730 // windows in the same type layer.
5731 mBaseLayer = mPolicy.windowTypeToLayerLw(a.type)
5732 * TYPE_LAYER_MULTIPLIER
5733 + TYPE_LAYER_OFFSET;
5734 mSubLayer = 0;
5735 mAttachedWindow = null;
5736 mLayoutAttached = false;
5737 mIsImWindow = mAttrs.type == TYPE_INPUT_METHOD
5738 || mAttrs.type == TYPE_INPUT_METHOD_DIALOG;
5739 }
5740
5741 WindowState appWin = this;
5742 while (appWin.mAttachedWindow != null) {
5743 appWin = mAttachedWindow;
5744 }
5745 WindowToken appToken = appWin.mToken;
5746 while (appToken.appWindowToken == null) {
5747 WindowToken parent = mTokenMap.get(appToken.token);
5748 if (parent == null || appToken == parent) {
5749 break;
5750 }
5751 appToken = parent;
5752 }
The Android Open Source Project10592532009-03-18 17:39:46 -07005753 mRootToken = appToken;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005754 mAppToken = appToken.appWindowToken;
5755
5756 mSurface = null;
5757 mRequestedWidth = 0;
5758 mRequestedHeight = 0;
5759 mLastRequestedWidth = 0;
5760 mLastRequestedHeight = 0;
5761 mReqXPos = 0;
5762 mReqYPos = 0;
5763 mLayer = 0;
5764 mAnimLayer = 0;
5765 mLastLayer = 0;
5766 }
5767
5768 void attach() {
5769 if (localLOGV) Log.v(
5770 TAG, "Attaching " + this + " token=" + mToken
5771 + ", list=" + mToken.windows);
5772 mSession.windowAddedLocked();
5773 }
5774
5775 public void computeFrameLw(Rect pf, Rect df, Rect cf, Rect vf) {
5776 mHaveFrame = true;
5777
5778 final int pw = pf.right-pf.left;
5779 final int ph = pf.bottom-pf.top;
5780
5781 int w,h;
5782 if ((mAttrs.flags & mAttrs.FLAG_SCALED) != 0) {
5783 w = mAttrs.width < 0 ? pw : mAttrs.width;
5784 h = mAttrs.height< 0 ? ph : mAttrs.height;
5785 } else {
5786 w = mAttrs.width == mAttrs.FILL_PARENT ? pw : mRequestedWidth;
5787 h = mAttrs.height== mAttrs.FILL_PARENT ? ph : mRequestedHeight;
5788 }
5789
5790 final Rect container = mContainingFrame;
5791 container.set(pf);
5792
5793 final Rect display = mDisplayFrame;
5794 display.set(df);
5795
5796 final Rect content = mContentFrame;
5797 content.set(cf);
5798
5799 final Rect visible = mVisibleFrame;
5800 visible.set(vf);
5801
5802 final Rect frame = mFrame;
5803
5804 //System.out.println("In: w=" + w + " h=" + h + " container=" +
5805 // container + " x=" + mAttrs.x + " y=" + mAttrs.y);
5806
5807 Gravity.apply(mAttrs.gravity, w, h, container,
5808 (int) (mAttrs.x + mAttrs.horizontalMargin * pw),
5809 (int) (mAttrs.y + mAttrs.verticalMargin * ph), frame);
5810
5811 //System.out.println("Out: " + mFrame);
5812
5813 // Now make sure the window fits in the overall display.
5814 Gravity.applyDisplay(mAttrs.gravity, df, frame);
5815
5816 // Make sure the content and visible frames are inside of the
5817 // final window frame.
5818 if (content.left < frame.left) content.left = frame.left;
5819 if (content.top < frame.top) content.top = frame.top;
5820 if (content.right > frame.right) content.right = frame.right;
5821 if (content.bottom > frame.bottom) content.bottom = frame.bottom;
5822 if (visible.left < frame.left) visible.left = frame.left;
5823 if (visible.top < frame.top) visible.top = frame.top;
5824 if (visible.right > frame.right) visible.right = frame.right;
5825 if (visible.bottom > frame.bottom) visible.bottom = frame.bottom;
5826
5827 final Rect contentInsets = mContentInsets;
5828 contentInsets.left = content.left-frame.left;
5829 contentInsets.top = content.top-frame.top;
5830 contentInsets.right = frame.right-content.right;
5831 contentInsets.bottom = frame.bottom-content.bottom;
5832
5833 final Rect visibleInsets = mVisibleInsets;
5834 visibleInsets.left = visible.left-frame.left;
5835 visibleInsets.top = visible.top-frame.top;
5836 visibleInsets.right = frame.right-visible.right;
5837 visibleInsets.bottom = frame.bottom-visible.bottom;
5838
5839 if (localLOGV) {
5840 //if ("com.google.android.youtube".equals(mAttrs.packageName)
5841 // && mAttrs.type == WindowManager.LayoutParams.TYPE_APPLICATION_PANEL) {
5842 Log.v(TAG, "Resolving (mRequestedWidth="
5843 + mRequestedWidth + ", mRequestedheight="
5844 + mRequestedHeight + ") to" + " (pw=" + pw + ", ph=" + ph
5845 + "): frame=" + mFrame.toShortString()
5846 + " ci=" + contentInsets.toShortString()
5847 + " vi=" + visibleInsets.toShortString());
5848 //}
5849 }
5850 }
5851
5852 public Rect getFrameLw() {
5853 return mFrame;
5854 }
5855
5856 public Rect getShownFrameLw() {
5857 return mShownFrame;
5858 }
5859
5860 public Rect getDisplayFrameLw() {
5861 return mDisplayFrame;
5862 }
5863
5864 public Rect getContentFrameLw() {
5865 return mContentFrame;
5866 }
5867
5868 public Rect getVisibleFrameLw() {
5869 return mVisibleFrame;
5870 }
5871
5872 public boolean getGivenInsetsPendingLw() {
5873 return mGivenInsetsPending;
5874 }
5875
5876 public Rect getGivenContentInsetsLw() {
5877 return mGivenContentInsets;
5878 }
5879
5880 public Rect getGivenVisibleInsetsLw() {
5881 return mGivenVisibleInsets;
5882 }
5883
5884 public WindowManager.LayoutParams getAttrs() {
5885 return mAttrs;
5886 }
5887
5888 public int getSurfaceLayer() {
5889 return mLayer;
5890 }
5891
5892 public IApplicationToken getAppToken() {
5893 return mAppToken != null ? mAppToken.appToken : null;
5894 }
5895
5896 public boolean hasAppShownWindows() {
5897 return mAppToken != null ? mAppToken.firstWindowDrawn : false;
5898 }
5899
5900 public boolean hasAppStartingIcon() {
5901 return mAppToken != null ? (mAppToken.startingData != null) : false;
5902 }
5903
5904 public WindowManagerPolicy.WindowState getAppStartingWindow() {
5905 return mAppToken != null ? mAppToken.startingWindow : null;
5906 }
5907
5908 public void setAnimation(Animation anim) {
5909 if (localLOGV) Log.v(
5910 TAG, "Setting animation in " + this + ": " + anim);
5911 mAnimating = false;
5912 mLocalAnimating = false;
5913 mAnimation = anim;
5914 mAnimation.restrictDuration(MAX_ANIMATION_DURATION);
5915 mAnimation.scaleCurrentDuration(mWindowAnimationScale);
5916 }
5917
5918 public void clearAnimation() {
5919 if (mAnimation != null) {
5920 mAnimating = true;
5921 mLocalAnimating = false;
5922 mAnimation = null;
5923 }
5924 }
5925
5926 Surface createSurfaceLocked() {
5927 if (mSurface == null) {
5928 mDrawPending = true;
5929 mCommitDrawPending = false;
5930 mReadyToShow = false;
5931 if (mAppToken != null) {
5932 mAppToken.allDrawn = false;
5933 }
5934
5935 int flags = 0;
5936 if (mAttrs.memoryType == MEMORY_TYPE_HARDWARE) {
5937 flags |= Surface.HARDWARE;
5938 } else if (mAttrs.memoryType == MEMORY_TYPE_GPU) {
5939 flags |= Surface.GPU;
5940 } else if (mAttrs.memoryType == MEMORY_TYPE_PUSH_BUFFERS) {
5941 flags |= Surface.PUSH_BUFFERS;
5942 }
5943
5944 if ((mAttrs.flags&WindowManager.LayoutParams.FLAG_SECURE) != 0) {
5945 flags |= Surface.SECURE;
5946 }
5947 if (DEBUG_VISIBILITY) Log.v(
5948 TAG, "Creating surface in session "
5949 + mSession.mSurfaceSession + " window " + this
5950 + " w=" + mFrame.width()
5951 + " h=" + mFrame.height() + " format="
5952 + mAttrs.format + " flags=" + flags);
5953
5954 int w = mFrame.width();
5955 int h = mFrame.height();
5956 if ((mAttrs.flags & LayoutParams.FLAG_SCALED) != 0) {
5957 // for a scaled surface, we always want the requested
5958 // size.
5959 w = mRequestedWidth;
5960 h = mRequestedHeight;
5961 }
5962
5963 try {
5964 mSurface = new Surface(
5965 mSession.mSurfaceSession, mSession.mPid,
5966 0, w, h, mAttrs.format, flags);
5967 } catch (Surface.OutOfResourcesException e) {
5968 Log.w(TAG, "OutOfResourcesException creating surface");
5969 reclaimSomeSurfaceMemoryLocked(this, "create");
5970 return null;
5971 } catch (Exception e) {
5972 Log.e(TAG, "Exception creating surface", e);
5973 return null;
5974 }
5975
5976 if (localLOGV) Log.v(
5977 TAG, "Got surface: " + mSurface
5978 + ", set left=" + mFrame.left + " top=" + mFrame.top
5979 + ", animLayer=" + mAnimLayer);
5980 if (SHOW_TRANSACTIONS) {
5981 Log.i(TAG, ">>> OPEN TRANSACTION");
5982 Log.i(TAG, " SURFACE " + mSurface + ": CREATE ("
5983 + mAttrs.getTitle() + ") pos=(" +
5984 mFrame.left + "," + mFrame.top + ") (" +
5985 mFrame.width() + "x" + mFrame.height() + "), layer=" +
5986 mAnimLayer + " HIDE");
5987 }
5988 Surface.openTransaction();
5989 try {
5990 try {
5991 mSurface.setPosition(mFrame.left, mFrame.top);
5992 mSurface.setLayer(mAnimLayer);
5993 mSurface.hide();
5994 if ((mAttrs.flags&WindowManager.LayoutParams.FLAG_DITHER) != 0) {
5995 mSurface.setFlags(Surface.SURFACE_DITHER,
5996 Surface.SURFACE_DITHER);
5997 }
5998 } catch (RuntimeException e) {
5999 Log.w(TAG, "Error creating surface in " + w, e);
6000 reclaimSomeSurfaceMemoryLocked(this, "create-init");
6001 }
6002 mLastHidden = true;
6003 } finally {
6004 if (SHOW_TRANSACTIONS) Log.i(TAG, "<<< CLOSE TRANSACTION");
6005 Surface.closeTransaction();
6006 }
6007 if (localLOGV) Log.v(
6008 TAG, "Created surface " + this);
6009 }
6010 return mSurface;
6011 }
6012
6013 void destroySurfaceLocked() {
6014 // Window is no longer on-screen, so can no longer receive
6015 // key events... if we were waiting for it to finish
6016 // handling a key event, the wait is over!
6017 mKeyWaiter.finishedKey(mSession, mClient, true,
6018 KeyWaiter.RETURN_NOTHING);
6019 mKeyWaiter.releasePendingPointerLocked(mSession);
6020 mKeyWaiter.releasePendingTrackballLocked(mSession);
6021
6022 if (mAppToken != null && this == mAppToken.startingWindow) {
6023 mAppToken.startingDisplayed = false;
6024 }
6025
6026 if (localLOGV) Log.v(
6027 TAG, "Window " + this
6028 + " destroying surface " + mSurface + ", session " + mSession);
6029 if (mSurface != null) {
6030 try {
6031 if (SHOW_TRANSACTIONS) {
6032 RuntimeException ex = new RuntimeException();
6033 ex.fillInStackTrace();
6034 Log.i(TAG, " SURFACE " + mSurface + ": DESTROY ("
6035 + mAttrs.getTitle() + ")", ex);
6036 }
6037 mSurface.clear();
6038 } catch (RuntimeException e) {
6039 Log.w(TAG, "Exception thrown when destroying Window " + this
6040 + " surface " + mSurface + " session " + mSession
6041 + ": " + e.toString());
6042 }
6043 mSurface = null;
6044 mDrawPending = false;
6045 mCommitDrawPending = false;
6046 mReadyToShow = false;
6047
6048 int i = mChildWindows.size();
6049 while (i > 0) {
6050 i--;
6051 WindowState c = (WindowState)mChildWindows.get(i);
6052 c.mAttachedHidden = true;
6053 }
6054 }
6055 }
6056
6057 boolean finishDrawingLocked() {
6058 if (mDrawPending) {
6059 if (SHOW_TRANSACTIONS || DEBUG_ORIENTATION) Log.v(
6060 TAG, "finishDrawingLocked: " + mSurface);
6061 mCommitDrawPending = true;
6062 mDrawPending = false;
6063 return true;
6064 }
6065 return false;
6066 }
6067
6068 // This must be called while inside a transaction.
6069 void commitFinishDrawingLocked(long currentTime) {
6070 //Log.i(TAG, "commitFinishDrawingLocked: " + mSurface);
6071 if (!mCommitDrawPending) {
6072 return;
6073 }
6074 mCommitDrawPending = false;
6075 mReadyToShow = true;
6076 final boolean starting = mAttrs.type == TYPE_APPLICATION_STARTING;
6077 final AppWindowToken atoken = mAppToken;
6078 if (atoken == null || atoken.allDrawn || starting) {
6079 performShowLocked();
6080 }
6081 }
6082
6083 // This must be called while inside a transaction.
6084 boolean performShowLocked() {
6085 if (DEBUG_VISIBILITY) {
6086 RuntimeException e = new RuntimeException();
6087 e.fillInStackTrace();
6088 Log.v(TAG, "performShow on " + this
6089 + ": readyToShow=" + mReadyToShow + " readyForDisplay=" + isReadyForDisplay()
6090 + " starting=" + (mAttrs.type == TYPE_APPLICATION_STARTING), e);
6091 }
6092 if (mReadyToShow && isReadyForDisplay()) {
6093 if (SHOW_TRANSACTIONS || DEBUG_ORIENTATION) Log.i(
6094 TAG, " SURFACE " + mSurface + ": SHOW (performShowLocked)");
6095 if (DEBUG_VISIBILITY) Log.v(TAG, "Showing " + this
6096 + " during animation: policyVis=" + mPolicyVisibility
6097 + " attHidden=" + mAttachedHidden
6098 + " tok.hiddenRequested="
6099 + (mAppToken != null ? mAppToken.hiddenRequested : false)
6100 + " tok.idden="
6101 + (mAppToken != null ? mAppToken.hidden : false)
6102 + " animating=" + mAnimating
6103 + " tok animating="
6104 + (mAppToken != null ? mAppToken.animating : false));
6105 if (!showSurfaceRobustlyLocked(this)) {
6106 return false;
6107 }
6108 mLastAlpha = -1;
6109 mHasDrawn = true;
6110 mLastHidden = false;
6111 mReadyToShow = false;
6112 enableScreenIfNeededLocked();
6113
6114 applyEnterAnimationLocked(this);
6115
6116 int i = mChildWindows.size();
6117 while (i > 0) {
6118 i--;
6119 WindowState c = (WindowState)mChildWindows.get(i);
6120 if (c.mSurface != null && c.mAttachedHidden) {
6121 c.mAttachedHidden = false;
6122 c.performShowLocked();
6123 }
6124 }
6125
6126 if (mAttrs.type != TYPE_APPLICATION_STARTING
6127 && mAppToken != null) {
6128 mAppToken.firstWindowDrawn = true;
6129 if (mAnimation == null && mAppToken.startingData != null) {
6130 if (DEBUG_STARTING_WINDOW) Log.v(TAG, "Finish starting "
6131 + mToken
6132 + ": first real window is shown, no animation");
6133 mFinishedStarting.add(mAppToken);
6134 mH.sendEmptyMessage(H.FINISHED_STARTING);
6135 }
6136 mAppToken.updateReportedVisibilityLocked();
6137 }
6138 }
6139 return true;
6140 }
6141
6142 // This must be called while inside a transaction. Returns true if
6143 // there is more animation to run.
6144 boolean stepAnimationLocked(long currentTime, int dw, int dh) {
6145 if (!mDisplayFrozen) {
6146 // We will run animations as long as the display isn't frozen.
6147
6148 if (!mDrawPending && !mCommitDrawPending && mAnimation != null) {
6149 mHasTransformation = true;
6150 mHasLocalTransformation = true;
6151 if (!mLocalAnimating) {
6152 if (DEBUG_ANIM) Log.v(
6153 TAG, "Starting animation in " + this +
6154 " @ " + currentTime + ": ww=" + mFrame.width() + " wh=" + mFrame.height() +
6155 " dw=" + dw + " dh=" + dh + " scale=" + mWindowAnimationScale);
6156 mAnimation.initialize(mFrame.width(), mFrame.height(), dw, dh);
6157 mAnimation.setStartTime(currentTime);
6158 mLocalAnimating = true;
6159 mAnimating = true;
6160 }
6161 mTransformation.clear();
6162 final boolean more = mAnimation.getTransformation(
6163 currentTime, mTransformation);
6164 if (DEBUG_ANIM) Log.v(
6165 TAG, "Stepped animation in " + this +
6166 ": more=" + more + ", xform=" + mTransformation);
6167 if (more) {
6168 // we're not done!
6169 return true;
6170 }
6171 if (DEBUG_ANIM) Log.v(
6172 TAG, "Finished animation in " + this +
6173 " @ " + currentTime);
6174 mAnimation = null;
6175 //WindowManagerService.this.dump();
6176 }
6177 mHasLocalTransformation = false;
6178 if ((!mLocalAnimating || mAnimationIsEntrance) && mAppToken != null
6179 && mAppToken.hasTransformation) {
6180 // When our app token is animating, we kind-of pretend like
6181 // we are as well. Note the mLocalAnimating mAnimationIsEntrance
6182 // part of this check means that we will only do this if
6183 // our window is not currently exiting, or it is not
6184 // locally animating itself. The idea being that one that
6185 // is exiting and doing a local animation should be removed
6186 // once that animation is done.
6187 mAnimating = true;
6188 mHasTransformation = true;
6189 mTransformation.clear();
6190 return false;
6191 } else if (mHasTransformation) {
6192 // Little trick to get through the path below to act like
6193 // we have finished an animation.
6194 mAnimating = true;
6195 } else if (isAnimating()) {
6196 mAnimating = true;
6197 }
6198 } else if (mAnimation != null) {
6199 // If the display is frozen, and there is a pending animation,
6200 // clear it and make sure we run the cleanup code.
6201 mAnimating = true;
6202 mLocalAnimating = true;
6203 mAnimation = null;
6204 }
6205
6206 if (!mAnimating && !mLocalAnimating) {
6207 return false;
6208 }
6209
6210 if (DEBUG_ANIM) Log.v(
6211 TAG, "Animation done in " + this + ": exiting=" + mExiting
6212 + ", reportedVisible="
6213 + (mAppToken != null ? mAppToken.reportedVisible : false));
6214
6215 mAnimating = false;
6216 mLocalAnimating = false;
6217 mAnimation = null;
6218 mAnimLayer = mLayer;
6219 if (mIsImWindow) {
6220 mAnimLayer += mInputMethodAnimLayerAdjustment;
6221 }
6222 if (DEBUG_LAYERS) Log.v(TAG, "Stepping win " + this
6223 + " anim layer: " + mAnimLayer);
6224 mHasTransformation = false;
6225 mHasLocalTransformation = false;
6226 mPolicyVisibility = mPolicyVisibilityAfterAnim;
6227 mTransformation.clear();
6228 if (mHasDrawn
6229 && mAttrs.type == WindowManager.LayoutParams.TYPE_APPLICATION_STARTING
6230 && mAppToken != null
6231 && mAppToken.firstWindowDrawn
6232 && mAppToken.startingData != null) {
6233 if (DEBUG_STARTING_WINDOW) Log.v(TAG, "Finish starting "
6234 + mToken + ": first real window done animating");
6235 mFinishedStarting.add(mAppToken);
6236 mH.sendEmptyMessage(H.FINISHED_STARTING);
6237 }
6238
6239 finishExit();
6240
6241 if (mAppToken != null) {
6242 mAppToken.updateReportedVisibilityLocked();
6243 }
6244
6245 return false;
6246 }
6247
6248 void finishExit() {
6249 if (DEBUG_ANIM) Log.v(
6250 TAG, "finishExit in " + this
6251 + ": exiting=" + mExiting
6252 + " remove=" + mRemoveOnExit
6253 + " windowAnimating=" + isWindowAnimating());
6254
6255 final int N = mChildWindows.size();
6256 for (int i=0; i<N; i++) {
6257 ((WindowState)mChildWindows.get(i)).finishExit();
6258 }
6259
6260 if (!mExiting) {
6261 return;
6262 }
6263
6264 if (isWindowAnimating()) {
6265 return;
6266 }
6267
6268 if (localLOGV) Log.v(
6269 TAG, "Exit animation finished in " + this
6270 + ": remove=" + mRemoveOnExit);
6271 if (mSurface != null) {
6272 mDestroySurface.add(this);
6273 mDestroying = true;
6274 if (SHOW_TRANSACTIONS) Log.i(
6275 TAG, " SURFACE " + mSurface + ": HIDE (finishExit)");
6276 try {
6277 mSurface.hide();
6278 } catch (RuntimeException e) {
6279 Log.w(TAG, "Error hiding surface in " + this, e);
6280 }
6281 mLastHidden = true;
6282 mKeyWaiter.releasePendingPointerLocked(mSession);
6283 }
6284 mExiting = false;
6285 if (mRemoveOnExit) {
6286 mPendingRemove.add(this);
6287 mRemoveOnExit = false;
6288 }
6289 }
6290
6291 boolean isIdentityMatrix(float dsdx, float dtdx, float dsdy, float dtdy) {
6292 if (dsdx < .99999f || dsdx > 1.00001f) return false;
6293 if (dtdy < .99999f || dtdy > 1.00001f) return false;
6294 if (dtdx < -.000001f || dtdx > .000001f) return false;
6295 if (dsdy < -.000001f || dsdy > .000001f) return false;
6296 return true;
6297 }
6298
6299 void computeShownFrameLocked() {
6300 final boolean selfTransformation = mHasLocalTransformation;
6301 Transformation attachedTransformation =
6302 (mAttachedWindow != null && mAttachedWindow.mHasLocalTransformation)
6303 ? mAttachedWindow.mTransformation : null;
6304 Transformation appTransformation =
6305 (mAppToken != null && mAppToken.hasTransformation)
6306 ? mAppToken.transformation : null;
6307 if (selfTransformation || attachedTransformation != null
6308 || appTransformation != null) {
6309 // cache often used attributes locally
6310 final Rect frame = mFrame;
6311 final float tmpFloats[] = mTmpFloats;
6312 final Matrix tmpMatrix = mTmpMatrix;
6313
6314 // Compute the desired transformation.
6315 tmpMatrix.setTranslate(frame.left, frame.top);
6316 if (selfTransformation) {
6317 tmpMatrix.preConcat(mTransformation.getMatrix());
6318 }
6319 if (attachedTransformation != null) {
6320 tmpMatrix.preConcat(attachedTransformation.getMatrix());
6321 }
6322 if (appTransformation != null) {
6323 tmpMatrix.preConcat(appTransformation.getMatrix());
6324 }
6325
6326 // "convert" it into SurfaceFlinger's format
6327 // (a 2x2 matrix + an offset)
6328 // Here we must not transform the position of the surface
6329 // since it is already included in the transformation.
6330 //Log.i(TAG, "Transform: " + matrix);
6331
6332 tmpMatrix.getValues(tmpFloats);
6333 mDsDx = tmpFloats[Matrix.MSCALE_X];
6334 mDtDx = tmpFloats[Matrix.MSKEW_X];
6335 mDsDy = tmpFloats[Matrix.MSKEW_Y];
6336 mDtDy = tmpFloats[Matrix.MSCALE_Y];
6337 int x = (int)tmpFloats[Matrix.MTRANS_X];
6338 int y = (int)tmpFloats[Matrix.MTRANS_Y];
6339 int w = frame.width();
6340 int h = frame.height();
6341 mShownFrame.set(x, y, x+w, y+h);
6342
6343 // Now set the alpha... but because our current hardware
6344 // can't do alpha transformation on a non-opaque surface,
6345 // turn it off if we are running an animation that is also
6346 // transforming since it is more important to have that
6347 // animation be smooth.
6348 mShownAlpha = mAlpha;
6349 if (!mLimitedAlphaCompositing
6350 || (!PixelFormat.formatHasAlpha(mAttrs.format)
6351 || (isIdentityMatrix(mDsDx, mDtDx, mDsDy, mDtDy)
6352 && x == frame.left && y == frame.top))) {
6353 //Log.i(TAG, "Applying alpha transform");
6354 if (selfTransformation) {
6355 mShownAlpha *= mTransformation.getAlpha();
6356 }
6357 if (attachedTransformation != null) {
6358 mShownAlpha *= attachedTransformation.getAlpha();
6359 }
6360 if (appTransformation != null) {
6361 mShownAlpha *= appTransformation.getAlpha();
6362 }
6363 } else {
6364 //Log.i(TAG, "Not applying alpha transform");
6365 }
6366
6367 if (localLOGV) Log.v(
6368 TAG, "Continuing animation in " + this +
6369 ": " + mShownFrame +
6370 ", alpha=" + mTransformation.getAlpha());
6371 return;
6372 }
6373
6374 mShownFrame.set(mFrame);
6375 mShownAlpha = mAlpha;
6376 mDsDx = 1;
6377 mDtDx = 0;
6378 mDsDy = 0;
6379 mDtDy = 1;
6380 }
6381
6382 /**
6383 * Is this window visible? It is not visible if there is no
6384 * surface, or we are in the process of running an exit animation
6385 * that will remove the surface, or its app token has been hidden.
6386 */
6387 public boolean isVisibleLw() {
6388 final AppWindowToken atoken = mAppToken;
6389 return mSurface != null && mPolicyVisibility && !mAttachedHidden
6390 && (atoken == null || !atoken.hiddenRequested)
6391 && !mExiting && !mDestroying;
6392 }
6393
6394 /**
6395 * Is this window visible, ignoring its app token? It is not visible
6396 * if there is no surface, or we are in the process of running an exit animation
6397 * that will remove the surface.
6398 */
6399 public boolean isWinVisibleLw() {
6400 final AppWindowToken atoken = mAppToken;
6401 return mSurface != null && mPolicyVisibility && !mAttachedHidden
6402 && (atoken == null || !atoken.hiddenRequested || atoken.animating)
6403 && !mExiting && !mDestroying;
6404 }
6405
6406 /**
6407 * The same as isVisible(), but follows the current hidden state of
6408 * the associated app token, not the pending requested hidden state.
6409 */
6410 boolean isVisibleNow() {
6411 return mSurface != null && mPolicyVisibility && !mAttachedHidden
The Android Open Source Project10592532009-03-18 17:39:46 -07006412 && !mRootToken.hidden && !mExiting && !mDestroying;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006413 }
6414
6415 /**
6416 * Same as isVisible(), but we also count it as visible between the
6417 * call to IWindowSession.add() and the first relayout().
6418 */
6419 boolean isVisibleOrAdding() {
6420 final AppWindowToken atoken = mAppToken;
6421 return (mSurface != null
6422 || (!mRelayoutCalled && mViewVisibility == View.VISIBLE))
6423 && mPolicyVisibility && !mAttachedHidden
6424 && (atoken == null || !atoken.hiddenRequested)
6425 && !mExiting && !mDestroying;
6426 }
6427
6428 /**
6429 * Is this window currently on-screen? It is on-screen either if it
6430 * is visible or it is currently running an animation before no longer
6431 * being visible.
6432 */
6433 boolean isOnScreen() {
6434 final AppWindowToken atoken = mAppToken;
6435 if (atoken != null) {
6436 return mSurface != null && mPolicyVisibility && !mDestroying
6437 && ((!mAttachedHidden && !atoken.hiddenRequested)
6438 || mAnimating || atoken.animating);
6439 } else {
6440 return mSurface != null && mPolicyVisibility && !mDestroying
6441 && (!mAttachedHidden || mAnimating);
6442 }
6443 }
6444
6445 /**
6446 * Like isOnScreen(), but we don't return true if the window is part
6447 * of a transition that has not yet been started.
6448 */
6449 boolean isReadyForDisplay() {
6450 final AppWindowToken atoken = mAppToken;
6451 final boolean animating = atoken != null ? atoken.animating : false;
6452 return mSurface != null && mPolicyVisibility && !mDestroying
The Android Open Source Project10592532009-03-18 17:39:46 -07006453 && ((!mAttachedHidden && !mRootToken.hidden)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006454 || mAnimating || animating);
6455 }
6456
6457 /** Is the window or its container currently animating? */
6458 boolean isAnimating() {
6459 final WindowState attached = mAttachedWindow;
6460 final AppWindowToken atoken = mAppToken;
6461 return mAnimation != null
6462 || (attached != null && attached.mAnimation != null)
6463 || (atoken != null &&
6464 (atoken.animation != null
6465 || atoken.inPendingTransaction));
6466 }
6467
6468 /** Is this window currently animating? */
6469 boolean isWindowAnimating() {
6470 return mAnimation != null;
6471 }
6472
6473 /**
6474 * Like isOnScreen, but returns false if the surface hasn't yet
6475 * been drawn.
6476 */
6477 public boolean isDisplayedLw() {
6478 final AppWindowToken atoken = mAppToken;
6479 return mSurface != null && mPolicyVisibility && !mDestroying
6480 && !mDrawPending && !mCommitDrawPending
6481 && ((!mAttachedHidden &&
6482 (atoken == null || !atoken.hiddenRequested))
6483 || mAnimating);
6484 }
6485
6486 public boolean fillsScreenLw(int screenWidth, int screenHeight,
6487 boolean shownFrame, boolean onlyOpaque) {
6488 if (mSurface == null) {
6489 return false;
6490 }
6491 if (mAppToken != null && !mAppToken.appFullscreen) {
6492 return false;
6493 }
6494 if (onlyOpaque && mAttrs.format != PixelFormat.OPAQUE) {
6495 return false;
6496 }
6497 final Rect frame = shownFrame ? mShownFrame : mFrame;
6498 if (frame.left <= 0 && frame.top <= 0
6499 && frame.right >= screenWidth
6500 && frame.bottom >= screenHeight) {
6501 return true;
6502 }
6503 return false;
6504 }
6505
6506 boolean isFullscreenOpaque(int screenWidth, int screenHeight) {
6507 if (mAttrs.format != PixelFormat.OPAQUE || mSurface == null
6508 || mAnimation != null || mDrawPending || mCommitDrawPending) {
6509 return false;
6510 }
6511 if (mFrame.left <= 0 && mFrame.top <= 0 &&
6512 mFrame.right >= screenWidth && mFrame.bottom >= screenHeight) {
6513 return true;
6514 }
6515 return false;
6516 }
6517
6518 void removeLocked() {
6519 if (mAttachedWindow != null) {
6520 mAttachedWindow.mChildWindows.remove(this);
6521 }
6522 destroySurfaceLocked();
6523 mSession.windowRemovedLocked();
6524 try {
6525 mClient.asBinder().unlinkToDeath(mDeathRecipient, 0);
6526 } catch (RuntimeException e) {
6527 // Ignore if it has already been removed (usually because
6528 // we are doing this as part of processing a death note.)
6529 }
6530 }
6531
6532 private class DeathRecipient implements IBinder.DeathRecipient {
6533 public void binderDied() {
6534 try {
6535 synchronized(mWindowMap) {
6536 WindowState win = windowForClientLocked(mSession, mClient);
6537 Log.i(TAG, "WIN DEATH: " + win);
6538 if (win != null) {
6539 removeWindowLocked(mSession, win);
6540 }
6541 }
6542 } catch (IllegalArgumentException ex) {
6543 // This will happen if the window has already been
6544 // removed.
6545 }
6546 }
6547 }
6548
6549 /** Returns true if this window desires key events. */
6550 public final boolean canReceiveKeys() {
6551 return isVisibleOrAdding()
6552 && (mViewVisibility == View.VISIBLE)
6553 && ((mAttrs.flags & WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE) == 0);
6554 }
6555
6556 public boolean hasDrawnLw() {
6557 return mHasDrawn;
6558 }
6559
6560 public boolean showLw(boolean doAnimation) {
6561 if (!mPolicyVisibility || !mPolicyVisibilityAfterAnim) {
6562 mPolicyVisibility = true;
6563 mPolicyVisibilityAfterAnim = true;
6564 if (doAnimation) {
6565 applyAnimationLocked(this, WindowManagerPolicy.TRANSIT_ENTER, true);
6566 }
6567 requestAnimationLocked(0);
6568 return true;
6569 }
6570 return false;
6571 }
6572
6573 public boolean hideLw(boolean doAnimation) {
6574 boolean current = doAnimation ? mPolicyVisibilityAfterAnim
6575 : mPolicyVisibility;
6576 if (current) {
6577 if (doAnimation) {
6578 applyAnimationLocked(this, WindowManagerPolicy.TRANSIT_EXIT, false);
6579 if (mAnimation == null) {
6580 doAnimation = false;
6581 }
6582 }
6583 if (doAnimation) {
6584 mPolicyVisibilityAfterAnim = false;
6585 } else {
6586 mPolicyVisibilityAfterAnim = false;
6587 mPolicyVisibility = false;
6588 }
6589 requestAnimationLocked(0);
6590 return true;
6591 }
6592 return false;
6593 }
6594
6595 void dump(PrintWriter pw, String prefix) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006596 StringBuilder sb = new StringBuilder(64);
6597
6598 pw.print(prefix); pw.print("mSession="); pw.print(mSession);
6599 pw.print(" mClient="); pw.println(mClient.asBinder());
6600 pw.print(prefix); pw.print("mAttrs="); pw.println(mAttrs);
6601 if (mAttachedWindow != null || mLayoutAttached) {
6602 pw.print(prefix); pw.print("mAttachedWindow="); pw.print(mAttachedWindow);
6603 pw.print(" mLayoutAttached="); pw.println(mLayoutAttached);
6604 }
6605 if (mIsImWindow) {
6606 pw.print(prefix); pw.print("mIsImWindow="); pw.println(mIsImWindow);
6607 }
6608 pw.print(prefix); pw.print("mBaseLayer="); pw.print(mBaseLayer);
6609 pw.print(" mSubLayer="); pw.print(mSubLayer);
6610 pw.print(" mAnimLayer="); pw.print(mLayer); pw.print("+");
6611 pw.print((mTargetAppToken != null ? mTargetAppToken.animLayerAdjustment
6612 : (mAppToken != null ? mAppToken.animLayerAdjustment : 0)));
6613 pw.print("="); pw.print(mAnimLayer);
6614 pw.print(" mLastLayer="); pw.println(mLastLayer);
6615 if (mSurface != null) {
6616 pw.print(prefix); pw.print("mSurface="); pw.println(mSurface);
6617 }
6618 pw.print(prefix); pw.print("mToken="); pw.println(mToken);
6619 pw.print(prefix); pw.print("mRootToken="); pw.println(mRootToken);
6620 if (mAppToken != null) {
6621 pw.print(prefix); pw.print("mAppToken="); pw.println(mAppToken);
6622 }
6623 if (mTargetAppToken != null) {
6624 pw.print(prefix); pw.print("mTargetAppToken="); pw.println(mTargetAppToken);
6625 }
6626 pw.print(prefix); pw.print("mViewVisibility=0x");
6627 pw.print(Integer.toHexString(mViewVisibility));
6628 pw.print(" mLastHidden="); pw.print(mLastHidden);
6629 pw.print(" mHaveFrame="); pw.println(mHaveFrame);
6630 if (!mPolicyVisibility || !mPolicyVisibilityAfterAnim || mAttachedHidden) {
6631 pw.print(prefix); pw.print("mPolicyVisibility=");
6632 pw.print(mPolicyVisibility);
6633 pw.print(" mPolicyVisibilityAfterAnim=");
6634 pw.print(mPolicyVisibilityAfterAnim);
6635 pw.print(" mAttachedHidden="); pw.println(mAttachedHidden);
6636 }
6637 pw.print(prefix); pw.print("Requested w="); pw.print(mRequestedWidth);
6638 pw.print(" h="); pw.print(mRequestedHeight);
6639 pw.print(" x="); pw.print(mReqXPos);
6640 pw.print(" y="); pw.println(mReqYPos);
6641 pw.print(prefix); pw.print("mGivenContentInsets=");
6642 mGivenContentInsets.printShortString(pw);
6643 pw.print(" mGivenVisibleInsets=");
6644 mGivenVisibleInsets.printShortString(pw);
6645 pw.println();
6646 if (mTouchableInsets != 0 || mGivenInsetsPending) {
6647 pw.print(prefix); pw.print("mTouchableInsets="); pw.print(mTouchableInsets);
6648 pw.print(" mGivenInsetsPending="); pw.println(mGivenInsetsPending);
6649 }
6650 pw.print(prefix); pw.print("mShownFrame=");
6651 mShownFrame.printShortString(pw);
6652 pw.print(" last="); mLastShownFrame.printShortString(pw);
6653 pw.println();
6654 pw.print(prefix); pw.print("mFrame="); mFrame.printShortString(pw);
6655 pw.print(" last="); mLastFrame.printShortString(pw);
6656 pw.println();
6657 pw.print(prefix); pw.print("mContainingFrame=");
6658 mContainingFrame.printShortString(pw);
6659 pw.print(" mDisplayFrame=");
6660 mDisplayFrame.printShortString(pw);
6661 pw.println();
6662 pw.print(prefix); pw.print("mContentFrame="); mContentFrame.printShortString(pw);
6663 pw.print(" mVisibleFrame="); mVisibleFrame.printShortString(pw);
6664 pw.println();
6665 pw.print(prefix); pw.print("mContentInsets="); mContentInsets.printShortString(pw);
6666 pw.print(" last="); mLastContentInsets.printShortString(pw);
6667 pw.print(" mVisibleInsets="); mVisibleInsets.printShortString(pw);
6668 pw.print(" last="); mLastVisibleInsets.printShortString(pw);
6669 pw.println();
6670 if (mShownAlpha != 1 || mAlpha != 1 || mLastAlpha != 1) {
6671 pw.print(prefix); pw.print("mShownAlpha="); pw.print(mShownAlpha);
6672 pw.print(" mAlpha="); pw.print(mAlpha);
6673 pw.print(" mLastAlpha="); pw.println(mLastAlpha);
6674 }
6675 if (mAnimating || mLocalAnimating || mAnimationIsEntrance
6676 || mAnimation != null) {
6677 pw.print(prefix); pw.print("mAnimating="); pw.print(mAnimating);
6678 pw.print(" mLocalAnimating="); pw.print(mLocalAnimating);
6679 pw.print(" mAnimationIsEntrance="); pw.print(mAnimationIsEntrance);
6680 pw.print(" mAnimation="); pw.println(mAnimation);
6681 }
6682 if (mHasTransformation || mHasLocalTransformation) {
6683 pw.print(prefix); pw.print("XForm: has=");
6684 pw.print(mHasTransformation);
6685 pw.print(" hasLocal="); pw.print(mHasLocalTransformation);
6686 pw.print(" "); mTransformation.printShortString(pw);
6687 pw.println();
6688 }
6689 pw.print(prefix); pw.print("mDrawPending="); pw.print(mDrawPending);
6690 pw.print(" mCommitDrawPending="); pw.print(mCommitDrawPending);
6691 pw.print(" mReadyToShow="); pw.print(mReadyToShow);
6692 pw.print(" mHasDrawn="); pw.println(mHasDrawn);
6693 if (mExiting || mRemoveOnExit || mDestroying || mRemoved) {
6694 pw.print(prefix); pw.print("mExiting="); pw.print(mExiting);
6695 pw.print(" mRemoveOnExit="); pw.print(mRemoveOnExit);
6696 pw.print(" mDestroying="); pw.print(mDestroying);
6697 pw.print(" mRemoved="); pw.println(mRemoved);
6698 }
6699 if (mOrientationChanging || mAppFreezing) {
6700 pw.print(prefix); pw.print("mOrientationChanging=");
6701 pw.print(mOrientationChanging);
6702 pw.print(" mAppFreezing="); pw.println(mAppFreezing);
6703 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006704 }
6705
6706 @Override
6707 public String toString() {
6708 return "Window{"
6709 + Integer.toHexString(System.identityHashCode(this))
6710 + " " + mAttrs.getTitle() + " paused=" + mToken.paused + "}";
6711 }
6712 }
6713
6714 // -------------------------------------------------------------
6715 // Window Token State
6716 // -------------------------------------------------------------
6717
6718 class WindowToken {
6719 // The actual token.
6720 final IBinder token;
6721
6722 // The type of window this token is for, as per WindowManager.LayoutParams.
6723 final int windowType;
6724
6725 // Set if this token was explicitly added by a client, so should
6726 // not be removed when all windows are removed.
6727 final boolean explicit;
6728
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006729 // For printing.
6730 String stringName;
6731
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006732 // If this is an AppWindowToken, this is non-null.
6733 AppWindowToken appWindowToken;
6734
6735 // All of the windows associated with this token.
6736 final ArrayList<WindowState> windows = new ArrayList<WindowState>();
6737
6738 // Is key dispatching paused for this token?
6739 boolean paused = false;
6740
6741 // Should this token's windows be hidden?
6742 boolean hidden;
6743
6744 // Temporary for finding which tokens no longer have visible windows.
6745 boolean hasVisible;
6746
6747 WindowToken(IBinder _token, int type, boolean _explicit) {
6748 token = _token;
6749 windowType = type;
6750 explicit = _explicit;
6751 }
6752
6753 void dump(PrintWriter pw, String prefix) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006754 pw.print(prefix); pw.print("token="); pw.println(token);
6755 pw.print(prefix); pw.print("windows="); pw.println(windows);
6756 pw.print(prefix); pw.print("windowType="); pw.print(windowType);
6757 pw.print(" hidden="); pw.print(hidden);
6758 pw.print(" hasVisible="); pw.println(hasVisible);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006759 }
6760
6761 @Override
6762 public String toString() {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006763 if (stringName == null) {
6764 StringBuilder sb = new StringBuilder();
6765 sb.append("WindowToken{");
6766 sb.append(Integer.toHexString(System.identityHashCode(this)));
6767 sb.append(" token="); sb.append(token); sb.append('}');
6768 stringName = sb.toString();
6769 }
6770 return stringName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006771 }
6772 };
6773
6774 class AppWindowToken extends WindowToken {
6775 // Non-null only for application tokens.
6776 final IApplicationToken appToken;
6777
6778 // All of the windows and child windows that are included in this
6779 // application token. Note this list is NOT sorted!
6780 final ArrayList<WindowState> allAppWindows = new ArrayList<WindowState>();
6781
6782 int groupId = -1;
6783 boolean appFullscreen;
6784 int requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
6785
6786 // These are used for determining when all windows associated with
6787 // an activity have been drawn, so they can be made visible together
6788 // at the same time.
6789 int lastTransactionSequence = mTransactionSequence-1;
6790 int numInterestingWindows;
6791 int numDrawnWindows;
6792 boolean inPendingTransaction;
6793 boolean allDrawn;
6794
6795 // Is this token going to be hidden in a little while? If so, it
6796 // won't be taken into account for setting the screen orientation.
6797 boolean willBeHidden;
6798
6799 // Is this window's surface needed? This is almost like hidden, except
6800 // it will sometimes be true a little earlier: when the token has
6801 // been shown, but is still waiting for its app transition to execute
6802 // before making its windows shown.
6803 boolean hiddenRequested;
6804
6805 // Have we told the window clients to hide themselves?
6806 boolean clientHidden;
6807
6808 // Last visibility state we reported to the app token.
6809 boolean reportedVisible;
6810
6811 // Set to true when the token has been removed from the window mgr.
6812 boolean removed;
6813
6814 // Have we been asked to have this token keep the screen frozen?
6815 boolean freezingScreen;
6816
6817 boolean animating;
6818 Animation animation;
6819 boolean hasTransformation;
6820 final Transformation transformation = new Transformation();
6821
6822 // Offset to the window of all layers in the token, for use by
6823 // AppWindowToken animations.
6824 int animLayerAdjustment;
6825
6826 // Information about an application starting window if displayed.
6827 StartingData startingData;
6828 WindowState startingWindow;
6829 View startingView;
6830 boolean startingDisplayed;
6831 boolean startingMoved;
6832 boolean firstWindowDrawn;
6833
6834 AppWindowToken(IApplicationToken _token) {
6835 super(_token.asBinder(),
6836 WindowManager.LayoutParams.TYPE_APPLICATION, true);
6837 appWindowToken = this;
6838 appToken = _token;
6839 }
6840
6841 public void setAnimation(Animation anim) {
6842 if (localLOGV) Log.v(
6843 TAG, "Setting animation in " + this + ": " + anim);
6844 animation = anim;
6845 animating = false;
6846 anim.restrictDuration(MAX_ANIMATION_DURATION);
6847 anim.scaleCurrentDuration(mTransitionAnimationScale);
6848 int zorder = anim.getZAdjustment();
6849 int adj = 0;
6850 if (zorder == Animation.ZORDER_TOP) {
6851 adj = TYPE_LAYER_OFFSET;
6852 } else if (zorder == Animation.ZORDER_BOTTOM) {
6853 adj = -TYPE_LAYER_OFFSET;
6854 }
6855
6856 if (animLayerAdjustment != adj) {
6857 animLayerAdjustment = adj;
6858 updateLayers();
6859 }
6860 }
6861
6862 public void setDummyAnimation() {
6863 if (animation == null) {
6864 if (localLOGV) Log.v(
6865 TAG, "Setting dummy animation in " + this);
6866 animation = sDummyAnimation;
6867 }
6868 }
6869
6870 public void clearAnimation() {
6871 if (animation != null) {
6872 animation = null;
6873 animating = true;
6874 }
6875 }
6876
6877 void updateLayers() {
6878 final int N = allAppWindows.size();
6879 final int adj = animLayerAdjustment;
6880 for (int i=0; i<N; i++) {
6881 WindowState w = allAppWindows.get(i);
6882 w.mAnimLayer = w.mLayer + adj;
6883 if (DEBUG_LAYERS) Log.v(TAG, "Updating layer " + w + ": "
6884 + w.mAnimLayer);
6885 if (w == mInputMethodTarget) {
6886 setInputMethodAnimLayerAdjustment(adj);
6887 }
6888 }
6889 }
6890
6891 void sendAppVisibilityToClients() {
6892 final int N = allAppWindows.size();
6893 for (int i=0; i<N; i++) {
6894 WindowState win = allAppWindows.get(i);
6895 if (win == startingWindow && clientHidden) {
6896 // Don't hide the starting window.
6897 continue;
6898 }
6899 try {
6900 if (DEBUG_VISIBILITY) Log.v(TAG,
6901 "Setting visibility of " + win + ": " + (!clientHidden));
6902 win.mClient.dispatchAppVisibility(!clientHidden);
6903 } catch (RemoteException e) {
6904 }
6905 }
6906 }
6907
6908 void showAllWindowsLocked() {
6909 final int NW = allAppWindows.size();
6910 for (int i=0; i<NW; i++) {
6911 WindowState w = allAppWindows.get(i);
6912 if (DEBUG_VISIBILITY) Log.v(TAG,
6913 "performing show on: " + w);
6914 w.performShowLocked();
6915 }
6916 }
6917
6918 // This must be called while inside a transaction.
6919 boolean stepAnimationLocked(long currentTime, int dw, int dh) {
6920 if (!mDisplayFrozen) {
6921 // We will run animations as long as the display isn't frozen.
6922
6923 if (animation == sDummyAnimation) {
6924 // This guy is going to animate, but not yet. For now count
6925 // it is not animating for purposes of scheduling transactions;
6926 // when it is really time to animate, this will be set to
6927 // a real animation and the next call will execute normally.
6928 return false;
6929 }
6930
6931 if ((allDrawn || animating || startingDisplayed) && animation != null) {
6932 if (!animating) {
6933 if (DEBUG_ANIM) Log.v(
6934 TAG, "Starting animation in " + this +
6935 " @ " + currentTime + ": dw=" + dw + " dh=" + dh
6936 + " scale=" + mTransitionAnimationScale
6937 + " allDrawn=" + allDrawn + " animating=" + animating);
6938 animation.initialize(dw, dh, dw, dh);
6939 animation.setStartTime(currentTime);
6940 animating = true;
6941 }
6942 transformation.clear();
6943 final boolean more = animation.getTransformation(
6944 currentTime, transformation);
6945 if (DEBUG_ANIM) Log.v(
6946 TAG, "Stepped animation in " + this +
6947 ": more=" + more + ", xform=" + transformation);
6948 if (more) {
6949 // we're done!
6950 hasTransformation = true;
6951 return true;
6952 }
6953 if (DEBUG_ANIM) Log.v(
6954 TAG, "Finished animation in " + this +
6955 " @ " + currentTime);
6956 animation = null;
6957 }
6958 } else if (animation != null) {
6959 // If the display is frozen, and there is a pending animation,
6960 // clear it and make sure we run the cleanup code.
6961 animating = true;
6962 animation = null;
6963 }
6964
6965 hasTransformation = false;
6966
6967 if (!animating) {
6968 return false;
6969 }
6970
6971 clearAnimation();
6972 animating = false;
6973 if (mInputMethodTarget != null && mInputMethodTarget.mAppToken == this) {
6974 moveInputMethodWindowsIfNeededLocked(true);
6975 }
6976
6977 if (DEBUG_ANIM) Log.v(
6978 TAG, "Animation done in " + this
6979 + ": reportedVisible=" + reportedVisible);
6980
6981 transformation.clear();
6982 if (animLayerAdjustment != 0) {
6983 animLayerAdjustment = 0;
6984 updateLayers();
6985 }
6986
6987 final int N = windows.size();
6988 for (int i=0; i<N; i++) {
6989 ((WindowState)windows.get(i)).finishExit();
6990 }
6991 updateReportedVisibilityLocked();
6992
6993 return false;
6994 }
6995
6996 void updateReportedVisibilityLocked() {
6997 if (appToken == null) {
6998 return;
6999 }
7000
7001 int numInteresting = 0;
7002 int numVisible = 0;
7003 boolean nowGone = true;
7004
7005 if (DEBUG_VISIBILITY) Log.v(TAG, "Update reported visibility: " + this);
7006 final int N = allAppWindows.size();
7007 for (int i=0; i<N; i++) {
7008 WindowState win = allAppWindows.get(i);
7009 if (win == startingWindow || win.mAppFreezing) {
7010 continue;
7011 }
7012 if (DEBUG_VISIBILITY) {
7013 Log.v(TAG, "Win " + win + ": isDisplayed="
7014 + win.isDisplayedLw()
7015 + ", isAnimating=" + win.isAnimating());
7016 if (!win.isDisplayedLw()) {
7017 Log.v(TAG, "Not displayed: s=" + win.mSurface
7018 + " pv=" + win.mPolicyVisibility
7019 + " dp=" + win.mDrawPending
7020 + " cdp=" + win.mCommitDrawPending
7021 + " ah=" + win.mAttachedHidden
7022 + " th="
7023 + (win.mAppToken != null
7024 ? win.mAppToken.hiddenRequested : false)
7025 + " a=" + win.mAnimating);
7026 }
7027 }
7028 numInteresting++;
7029 if (win.isDisplayedLw()) {
7030 if (!win.isAnimating()) {
7031 numVisible++;
7032 }
7033 nowGone = false;
7034 } else if (win.isAnimating()) {
7035 nowGone = false;
7036 }
7037 }
7038
7039 boolean nowVisible = numInteresting > 0 && numVisible >= numInteresting;
7040 if (DEBUG_VISIBILITY) Log.v(TAG, "VIS " + this + ": interesting="
7041 + numInteresting + " visible=" + numVisible);
7042 if (nowVisible != reportedVisible) {
7043 if (DEBUG_VISIBILITY) Log.v(
7044 TAG, "Visibility changed in " + this
7045 + ": vis=" + nowVisible);
7046 reportedVisible = nowVisible;
7047 Message m = mH.obtainMessage(
7048 H.REPORT_APPLICATION_TOKEN_WINDOWS,
7049 nowVisible ? 1 : 0,
7050 nowGone ? 1 : 0,
7051 this);
7052 mH.sendMessage(m);
7053 }
7054 }
7055
7056 void dump(PrintWriter pw, String prefix) {
7057 super.dump(pw, prefix);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007058 if (appToken != null) {
7059 pw.print(prefix); pw.println("app=true");
7060 }
7061 if (allAppWindows.size() > 0) {
7062 pw.print(prefix); pw.print("allAppWindows="); pw.println(allAppWindows);
7063 }
7064 pw.print(prefix); pw.print("groupId="); pw.print(groupId);
7065 pw.print(" requestedOrientation="); pw.println(requestedOrientation);
7066 pw.print(prefix); pw.print("hiddenRequested="); pw.print(hiddenRequested);
7067 pw.print(" clientHidden="); pw.print(clientHidden);
7068 pw.print(" willBeHidden="); pw.print(willBeHidden);
7069 pw.print(" reportedVisible="); pw.println(reportedVisible);
7070 if (paused || freezingScreen) {
7071 pw.print(prefix); pw.print("paused="); pw.print(paused);
7072 pw.print(" freezingScreen="); pw.println(freezingScreen);
7073 }
7074 if (numInterestingWindows != 0 || numDrawnWindows != 0
7075 || inPendingTransaction || allDrawn) {
7076 pw.print(prefix); pw.print("numInterestingWindows=");
7077 pw.print(numInterestingWindows);
7078 pw.print(" numDrawnWindows="); pw.print(numDrawnWindows);
7079 pw.print(" inPendingTransaction="); pw.print(inPendingTransaction);
7080 pw.print(" allDrawn="); pw.println(allDrawn);
7081 }
7082 if (animating || animation != null) {
7083 pw.print(prefix); pw.print("animating="); pw.print(animating);
7084 pw.print(" animation="); pw.println(animation);
7085 }
7086 if (animLayerAdjustment != 0) {
7087 pw.print(prefix); pw.print("animLayerAdjustment="); pw.println(animLayerAdjustment);
7088 }
7089 if (hasTransformation) {
7090 pw.print(prefix); pw.print("hasTransformation="); pw.print(hasTransformation);
7091 pw.print(" transformation="); transformation.printShortString(pw);
7092 pw.println();
7093 }
7094 if (startingData != null || removed || firstWindowDrawn) {
7095 pw.print(prefix); pw.print("startingData="); pw.print(startingData);
7096 pw.print(" removed="); pw.print(removed);
7097 pw.print(" firstWindowDrawn="); pw.println(firstWindowDrawn);
7098 }
7099 if (startingWindow != null || startingView != null
7100 || startingDisplayed || startingMoved) {
7101 pw.print(prefix); pw.print("startingWindow="); pw.print(startingWindow);
7102 pw.print(" startingView="); pw.print(startingView);
7103 pw.print(" startingDisplayed="); pw.print(startingDisplayed);
7104 pw.print(" startingMoved"); pw.println(startingMoved);
7105 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007106 }
7107
7108 @Override
7109 public String toString() {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007110 if (stringName == null) {
7111 StringBuilder sb = new StringBuilder();
7112 sb.append("AppWindowToken{");
7113 sb.append(Integer.toHexString(System.identityHashCode(this)));
7114 sb.append(" token="); sb.append(token); sb.append('}');
7115 stringName = sb.toString();
7116 }
7117 return stringName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007118 }
7119 }
7120
7121 public static WindowManager.LayoutParams findAnimations(
7122 ArrayList<AppWindowToken> order,
7123 ArrayList<AppWindowToken> tokenList1,
7124 ArrayList<AppWindowToken> tokenList2) {
7125 // We need to figure out which animation to use...
7126 WindowManager.LayoutParams animParams = null;
7127 int animSrc = 0;
7128
7129 //Log.i(TAG, "Looking for animations...");
7130 for (int i=order.size()-1; i>=0; i--) {
7131 AppWindowToken wtoken = order.get(i);
7132 //Log.i(TAG, "Token " + wtoken + " with " + wtoken.windows.size() + " windows");
7133 if (tokenList1.contains(wtoken) || tokenList2.contains(wtoken)) {
7134 int j = wtoken.windows.size();
7135 while (j > 0) {
7136 j--;
7137 WindowState win = wtoken.windows.get(j);
7138 //Log.i(TAG, "Window " + win + ": type=" + win.mAttrs.type);
7139 if (win.mAttrs.type == WindowManager.LayoutParams.TYPE_BASE_APPLICATION
7140 || win.mAttrs.type == WindowManager.LayoutParams.TYPE_APPLICATION_STARTING) {
7141 //Log.i(TAG, "Found base or application window, done!");
7142 if (wtoken.appFullscreen) {
7143 return win.mAttrs;
7144 }
7145 if (animSrc < 2) {
7146 animParams = win.mAttrs;
7147 animSrc = 2;
7148 }
7149 } else if (animSrc < 1 && win.mAttrs.type == WindowManager.LayoutParams.TYPE_APPLICATION) {
7150 //Log.i(TAG, "Found normal window, we may use this...");
7151 animParams = win.mAttrs;
7152 animSrc = 1;
7153 }
7154 }
7155 }
7156 }
7157
7158 return animParams;
7159 }
7160
7161 // -------------------------------------------------------------
7162 // DummyAnimation
7163 // -------------------------------------------------------------
7164
7165 // This is an animation that does nothing: it just immediately finishes
7166 // itself every time it is called. It is used as a stub animation in cases
7167 // where we want to synchronize multiple things that may be animating.
7168 static final class DummyAnimation extends Animation {
7169 public boolean getTransformation(long currentTime, Transformation outTransformation) {
7170 return false;
7171 }
7172 }
7173 static final Animation sDummyAnimation = new DummyAnimation();
7174
7175 // -------------------------------------------------------------
7176 // Async Handler
7177 // -------------------------------------------------------------
7178
7179 static final class StartingData {
7180 final String pkg;
7181 final int theme;
7182 final CharSequence nonLocalizedLabel;
7183 final int labelRes;
7184 final int icon;
7185
7186 StartingData(String _pkg, int _theme, CharSequence _nonLocalizedLabel,
7187 int _labelRes, int _icon) {
7188 pkg = _pkg;
7189 theme = _theme;
7190 nonLocalizedLabel = _nonLocalizedLabel;
7191 labelRes = _labelRes;
7192 icon = _icon;
7193 }
7194 }
7195
7196 private final class H extends Handler {
7197 public static final int REPORT_FOCUS_CHANGE = 2;
7198 public static final int REPORT_LOSING_FOCUS = 3;
7199 public static final int ANIMATE = 4;
7200 public static final int ADD_STARTING = 5;
7201 public static final int REMOVE_STARTING = 6;
7202 public static final int FINISHED_STARTING = 7;
7203 public static final int REPORT_APPLICATION_TOKEN_WINDOWS = 8;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007204 public static final int WINDOW_FREEZE_TIMEOUT = 11;
7205 public static final int HOLD_SCREEN_CHANGED = 12;
7206 public static final int APP_TRANSITION_TIMEOUT = 13;
7207 public static final int PERSIST_ANIMATION_SCALE = 14;
7208 public static final int FORCE_GC = 15;
7209 public static final int ENABLE_SCREEN = 16;
7210 public static final int APP_FREEZE_TIMEOUT = 17;
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07007211 public static final int COMPUTE_AND_SEND_NEW_CONFIGURATION = 18;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007212
7213 private Session mLastReportedHold;
7214
7215 public H() {
7216 }
7217
7218 @Override
7219 public void handleMessage(Message msg) {
7220 switch (msg.what) {
7221 case REPORT_FOCUS_CHANGE: {
7222 WindowState lastFocus;
7223 WindowState newFocus;
7224
7225 synchronized(mWindowMap) {
7226 lastFocus = mLastFocus;
7227 newFocus = mCurrentFocus;
7228 if (lastFocus == newFocus) {
7229 // Focus is not changing, so nothing to do.
7230 return;
7231 }
7232 mLastFocus = newFocus;
7233 //Log.i(TAG, "Focus moving from " + lastFocus
7234 // + " to " + newFocus);
7235 if (newFocus != null && lastFocus != null
7236 && !newFocus.isDisplayedLw()) {
7237 //Log.i(TAG, "Delaying loss of focus...");
7238 mLosingFocus.add(lastFocus);
7239 lastFocus = null;
7240 }
7241 }
7242
7243 if (lastFocus != newFocus) {
7244 //System.out.println("Changing focus from " + lastFocus
7245 // + " to " + newFocus);
7246 if (newFocus != null) {
7247 try {
7248 //Log.i(TAG, "Gaining focus: " + newFocus);
7249 newFocus.mClient.windowFocusChanged(true, mInTouchMode);
7250 } catch (RemoteException e) {
7251 // Ignore if process has died.
7252 }
7253 }
7254
7255 if (lastFocus != null) {
7256 try {
7257 //Log.i(TAG, "Losing focus: " + lastFocus);
7258 lastFocus.mClient.windowFocusChanged(false, mInTouchMode);
7259 } catch (RemoteException e) {
7260 // Ignore if process has died.
7261 }
7262 }
7263 }
7264 } break;
7265
7266 case REPORT_LOSING_FOCUS: {
7267 ArrayList<WindowState> losers;
7268
7269 synchronized(mWindowMap) {
7270 losers = mLosingFocus;
7271 mLosingFocus = new ArrayList<WindowState>();
7272 }
7273
7274 final int N = losers.size();
7275 for (int i=0; i<N; i++) {
7276 try {
7277 //Log.i(TAG, "Losing delayed focus: " + losers.get(i));
7278 losers.get(i).mClient.windowFocusChanged(false, mInTouchMode);
7279 } catch (RemoteException e) {
7280 // Ignore if process has died.
7281 }
7282 }
7283 } break;
7284
7285 case ANIMATE: {
7286 synchronized(mWindowMap) {
7287 mAnimationPending = false;
7288 performLayoutAndPlaceSurfacesLocked();
7289 }
7290 } break;
7291
7292 case ADD_STARTING: {
7293 final AppWindowToken wtoken = (AppWindowToken)msg.obj;
7294 final StartingData sd = wtoken.startingData;
7295
7296 if (sd == null) {
7297 // Animation has been canceled... do nothing.
7298 return;
7299 }
7300
7301 if (DEBUG_STARTING_WINDOW) Log.v(TAG, "Add starting "
7302 + wtoken + ": pkg=" + sd.pkg);
7303
7304 View view = null;
7305 try {
7306 view = mPolicy.addStartingWindow(
7307 wtoken.token, sd.pkg,
7308 sd.theme, sd.nonLocalizedLabel, sd.labelRes,
7309 sd.icon);
7310 } catch (Exception e) {
7311 Log.w(TAG, "Exception when adding starting window", e);
7312 }
7313
7314 if (view != null) {
7315 boolean abort = false;
7316
7317 synchronized(mWindowMap) {
7318 if (wtoken.removed || wtoken.startingData == null) {
7319 // If the window was successfully added, then
7320 // we need to remove it.
7321 if (wtoken.startingWindow != null) {
7322 if (DEBUG_STARTING_WINDOW) Log.v(TAG,
7323 "Aborted starting " + wtoken
7324 + ": removed=" + wtoken.removed
7325 + " startingData=" + wtoken.startingData);
7326 wtoken.startingWindow = null;
7327 wtoken.startingData = null;
7328 abort = true;
7329 }
7330 } else {
7331 wtoken.startingView = view;
7332 }
7333 if (DEBUG_STARTING_WINDOW && !abort) Log.v(TAG,
7334 "Added starting " + wtoken
7335 + ": startingWindow="
7336 + wtoken.startingWindow + " startingView="
7337 + wtoken.startingView);
7338 }
7339
7340 if (abort) {
7341 try {
7342 mPolicy.removeStartingWindow(wtoken.token, view);
7343 } catch (Exception e) {
7344 Log.w(TAG, "Exception when removing starting window", e);
7345 }
7346 }
7347 }
7348 } break;
7349
7350 case REMOVE_STARTING: {
7351 final AppWindowToken wtoken = (AppWindowToken)msg.obj;
7352 IBinder token = null;
7353 View view = null;
7354 synchronized (mWindowMap) {
7355 if (DEBUG_STARTING_WINDOW) Log.v(TAG, "Remove starting "
7356 + wtoken + ": startingWindow="
7357 + wtoken.startingWindow + " startingView="
7358 + wtoken.startingView);
7359 if (wtoken.startingWindow != null) {
7360 view = wtoken.startingView;
7361 token = wtoken.token;
7362 wtoken.startingData = null;
7363 wtoken.startingView = null;
7364 wtoken.startingWindow = null;
7365 }
7366 }
7367 if (view != null) {
7368 try {
7369 mPolicy.removeStartingWindow(token, view);
7370 } catch (Exception e) {
7371 Log.w(TAG, "Exception when removing starting window", e);
7372 }
7373 }
7374 } break;
7375
7376 case FINISHED_STARTING: {
7377 IBinder token = null;
7378 View view = null;
7379 while (true) {
7380 synchronized (mWindowMap) {
7381 final int N = mFinishedStarting.size();
7382 if (N <= 0) {
7383 break;
7384 }
7385 AppWindowToken wtoken = mFinishedStarting.remove(N-1);
7386
7387 if (DEBUG_STARTING_WINDOW) Log.v(TAG,
7388 "Finished starting " + wtoken
7389 + ": startingWindow=" + wtoken.startingWindow
7390 + " startingView=" + wtoken.startingView);
7391
7392 if (wtoken.startingWindow == null) {
7393 continue;
7394 }
7395
7396 view = wtoken.startingView;
7397 token = wtoken.token;
7398 wtoken.startingData = null;
7399 wtoken.startingView = null;
7400 wtoken.startingWindow = null;
7401 }
7402
7403 try {
7404 mPolicy.removeStartingWindow(token, view);
7405 } catch (Exception e) {
7406 Log.w(TAG, "Exception when removing starting window", e);
7407 }
7408 }
7409 } break;
7410
7411 case REPORT_APPLICATION_TOKEN_WINDOWS: {
7412 final AppWindowToken wtoken = (AppWindowToken)msg.obj;
7413
7414 boolean nowVisible = msg.arg1 != 0;
7415 boolean nowGone = msg.arg2 != 0;
7416
7417 try {
7418 if (DEBUG_VISIBILITY) Log.v(
7419 TAG, "Reporting visible in " + wtoken
7420 + " visible=" + nowVisible
7421 + " gone=" + nowGone);
7422 if (nowVisible) {
7423 wtoken.appToken.windowsVisible();
7424 } else {
7425 wtoken.appToken.windowsGone();
7426 }
7427 } catch (RemoteException ex) {
7428 }
7429 } break;
7430
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007431 case WINDOW_FREEZE_TIMEOUT: {
7432 synchronized (mWindowMap) {
7433 Log.w(TAG, "Window freeze timeout expired.");
7434 int i = mWindows.size();
7435 while (i > 0) {
7436 i--;
7437 WindowState w = (WindowState)mWindows.get(i);
7438 if (w.mOrientationChanging) {
7439 w.mOrientationChanging = false;
7440 Log.w(TAG, "Force clearing orientation change: " + w);
7441 }
7442 }
7443 performLayoutAndPlaceSurfacesLocked();
7444 }
7445 break;
7446 }
7447
7448 case HOLD_SCREEN_CHANGED: {
7449 Session oldHold;
7450 Session newHold;
7451 synchronized (mWindowMap) {
7452 oldHold = mLastReportedHold;
7453 newHold = (Session)msg.obj;
7454 mLastReportedHold = newHold;
7455 }
7456
7457 if (oldHold != newHold) {
7458 try {
7459 if (oldHold != null) {
7460 mBatteryStats.noteStopWakelock(oldHold.mUid,
7461 "window",
7462 BatteryStats.WAKE_TYPE_WINDOW);
7463 }
7464 if (newHold != null) {
7465 mBatteryStats.noteStartWakelock(newHold.mUid,
7466 "window",
7467 BatteryStats.WAKE_TYPE_WINDOW);
7468 }
7469 } catch (RemoteException e) {
7470 }
7471 }
7472 break;
7473 }
7474
7475 case APP_TRANSITION_TIMEOUT: {
7476 synchronized (mWindowMap) {
7477 if (mNextAppTransition != WindowManagerPolicy.TRANSIT_NONE) {
7478 if (DEBUG_APP_TRANSITIONS) Log.v(TAG,
7479 "*** APP TRANSITION TIMEOUT");
7480 mAppTransitionReady = true;
7481 mAppTransitionTimeout = true;
7482 performLayoutAndPlaceSurfacesLocked();
7483 }
7484 }
7485 break;
7486 }
7487
7488 case PERSIST_ANIMATION_SCALE: {
7489 Settings.System.putFloat(mContext.getContentResolver(),
7490 Settings.System.WINDOW_ANIMATION_SCALE, mWindowAnimationScale);
7491 Settings.System.putFloat(mContext.getContentResolver(),
7492 Settings.System.TRANSITION_ANIMATION_SCALE, mTransitionAnimationScale);
7493 break;
7494 }
7495
7496 case FORCE_GC: {
7497 synchronized(mWindowMap) {
7498 if (mAnimationPending) {
7499 // If we are animating, don't do the gc now but
7500 // delay a bit so we don't interrupt the animation.
7501 mH.sendMessageDelayed(mH.obtainMessage(H.FORCE_GC),
7502 2000);
7503 return;
7504 }
7505 // If we are currently rotating the display, it will
7506 // schedule a new message when done.
7507 if (mDisplayFrozen) {
7508 return;
7509 }
7510 mFreezeGcPending = 0;
7511 }
7512 Runtime.getRuntime().gc();
7513 break;
7514 }
7515
7516 case ENABLE_SCREEN: {
7517 performEnableScreen();
7518 break;
7519 }
7520
7521 case APP_FREEZE_TIMEOUT: {
7522 synchronized (mWindowMap) {
7523 Log.w(TAG, "App freeze timeout expired.");
7524 int i = mAppTokens.size();
7525 while (i > 0) {
7526 i--;
7527 AppWindowToken tok = mAppTokens.get(i);
7528 if (tok.freezingScreen) {
7529 Log.w(TAG, "Force clearing freeze: " + tok);
7530 unsetAppFreezingScreenLocked(tok, true, true);
7531 }
7532 }
7533 }
7534 break;
7535 }
7536
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07007537 case COMPUTE_AND_SEND_NEW_CONFIGURATION: {
The Android Open Source Project10592532009-03-18 17:39:46 -07007538 if (updateOrientationFromAppTokens(null, null) != null) {
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07007539 sendNewConfiguration();
7540 }
7541 break;
7542 }
7543
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007544 }
7545 }
7546 }
7547
7548 // -------------------------------------------------------------
7549 // IWindowManager API
7550 // -------------------------------------------------------------
7551
7552 public IWindowSession openSession(IInputMethodClient client,
7553 IInputContext inputContext) {
7554 if (client == null) throw new IllegalArgumentException("null client");
7555 if (inputContext == null) throw new IllegalArgumentException("null inputContext");
7556 return new Session(client, inputContext);
7557 }
7558
7559 public boolean inputMethodClientHasFocus(IInputMethodClient client) {
7560 synchronized (mWindowMap) {
7561 // The focus for the client is the window immediately below
7562 // where we would place the input method window.
7563 int idx = findDesiredInputMethodWindowIndexLocked(false);
7564 WindowState imFocus;
7565 if (idx > 0) {
7566 imFocus = (WindowState)mWindows.get(idx-1);
7567 if (imFocus != null) {
7568 if (imFocus.mSession.mClient != null &&
7569 imFocus.mSession.mClient.asBinder() == client.asBinder()) {
7570 return true;
7571 }
7572 }
7573 }
7574 }
7575 return false;
7576 }
7577
7578 // -------------------------------------------------------------
7579 // Internals
7580 // -------------------------------------------------------------
7581
7582 final WindowState windowForClientLocked(Session session, IWindow client) {
7583 return windowForClientLocked(session, client.asBinder());
7584 }
7585
7586 final WindowState windowForClientLocked(Session session, IBinder client) {
7587 WindowState win = mWindowMap.get(client);
7588 if (localLOGV) Log.v(
7589 TAG, "Looking up client " + client + ": " + win);
7590 if (win == null) {
7591 RuntimeException ex = new RuntimeException();
7592 Log.w(TAG, "Requested window " + client + " does not exist", ex);
7593 return null;
7594 }
7595 if (session != null && win.mSession != session) {
7596 RuntimeException ex = new RuntimeException();
7597 Log.w(TAG, "Requested window " + client + " is in session " +
7598 win.mSession + ", not " + session, ex);
7599 return null;
7600 }
7601
7602 return win;
7603 }
7604
7605 private final void assignLayersLocked() {
7606 int N = mWindows.size();
7607 int curBaseLayer = 0;
7608 int curLayer = 0;
7609 int i;
7610
7611 for (i=0; i<N; i++) {
7612 WindowState w = (WindowState)mWindows.get(i);
7613 if (w.mBaseLayer == curBaseLayer || w.mIsImWindow) {
7614 curLayer += WINDOW_LAYER_MULTIPLIER;
7615 w.mLayer = curLayer;
7616 } else {
7617 curBaseLayer = curLayer = w.mBaseLayer;
7618 w.mLayer = curLayer;
7619 }
7620 if (w.mTargetAppToken != null) {
7621 w.mAnimLayer = w.mLayer + w.mTargetAppToken.animLayerAdjustment;
7622 } else if (w.mAppToken != null) {
7623 w.mAnimLayer = w.mLayer + w.mAppToken.animLayerAdjustment;
7624 } else {
7625 w.mAnimLayer = w.mLayer;
7626 }
7627 if (w.mIsImWindow) {
7628 w.mAnimLayer += mInputMethodAnimLayerAdjustment;
7629 }
7630 if (DEBUG_LAYERS) Log.v(TAG, "Assign layer " + w + ": "
7631 + w.mAnimLayer);
7632 //System.out.println(
7633 // "Assigned layer " + curLayer + " to " + w.mClient.asBinder());
7634 }
7635 }
7636
7637 private boolean mInLayout = false;
7638 private final void performLayoutAndPlaceSurfacesLocked() {
7639 if (mInLayout) {
Dave Bortcfe65242009-04-09 14:51:04 -07007640 if (DEBUG) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007641 throw new RuntimeException("Recursive call!");
7642 }
7643 Log.w(TAG, "performLayoutAndPlaceSurfacesLocked called while in layout");
7644 return;
7645 }
7646
7647 boolean recoveringMemory = false;
7648 if (mForceRemoves != null) {
7649 recoveringMemory = true;
7650 // Wait a little it for things to settle down, and off we go.
7651 for (int i=0; i<mForceRemoves.size(); i++) {
7652 WindowState ws = mForceRemoves.get(i);
7653 Log.i(TAG, "Force removing: " + ws);
7654 removeWindowInnerLocked(ws.mSession, ws);
7655 }
7656 mForceRemoves = null;
7657 Log.w(TAG, "Due to memory failure, waiting a bit for next layout");
7658 Object tmp = new Object();
7659 synchronized (tmp) {
7660 try {
7661 tmp.wait(250);
7662 } catch (InterruptedException e) {
7663 }
7664 }
7665 }
7666
7667 mInLayout = true;
7668 try {
7669 performLayoutAndPlaceSurfacesLockedInner(recoveringMemory);
7670
7671 int i = mPendingRemove.size()-1;
7672 if (i >= 0) {
7673 while (i >= 0) {
7674 WindowState w = mPendingRemove.get(i);
7675 removeWindowInnerLocked(w.mSession, w);
7676 i--;
7677 }
7678 mPendingRemove.clear();
7679
7680 mInLayout = false;
7681 assignLayersLocked();
7682 mLayoutNeeded = true;
7683 performLayoutAndPlaceSurfacesLocked();
7684
7685 } else {
7686 mInLayout = false;
7687 if (mLayoutNeeded) {
7688 requestAnimationLocked(0);
7689 }
7690 }
7691 } catch (RuntimeException e) {
7692 mInLayout = false;
7693 Log.e(TAG, "Unhandled exception while layout out windows", e);
7694 }
7695 }
7696
7697 private final void performLayoutLockedInner() {
7698 final int dw = mDisplay.getWidth();
7699 final int dh = mDisplay.getHeight();
7700
7701 final int N = mWindows.size();
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07007702 int repeats = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007703 int i;
7704
7705 // FIRST LOOP: Perform a layout, if needed.
7706
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07007707 while (mLayoutNeeded) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007708 mPolicy.beginLayoutLw(dw, dh);
7709
7710 // First perform layout of any root windows (not attached
7711 // to another window).
7712 int topAttached = -1;
7713 for (i = N-1; i >= 0; i--) {
7714 WindowState win = (WindowState) mWindows.get(i);
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07007715
7716 // Don't do layout of a window if it is not visible, or
7717 // soon won't be visible, to avoid wasting time and funky
7718 // changes while a window is animating away.
7719 final AppWindowToken atoken = win.mAppToken;
7720 final boolean gone = win.mViewVisibility == View.GONE
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007721 || !win.mRelayoutCalled
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07007722 || win.mRootToken.hidden
7723 || (atoken != null && atoken.hiddenRequested)
7724 || !win.mPolicyVisibility
7725 || win.mAttachedHidden
7726 || win.mExiting || win.mDestroying;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007727
7728 // If this view is GONE, then skip it -- keep the current
7729 // frame, and let the caller know so they can ignore it
7730 // if they want. (We do the normal layout for INVISIBLE
7731 // windows, since that means "perform layout as normal,
7732 // just don't display").
7733 if (!gone || !win.mHaveFrame) {
7734 if (!win.mLayoutAttached) {
7735 mPolicy.layoutWindowLw(win, win.mAttrs, null);
7736 } else {
7737 if (topAttached < 0) topAttached = i;
7738 }
7739 }
7740 }
7741
7742 // Now perform layout of attached windows, which usually
7743 // depend on the position of the window they are attached to.
7744 // XXX does not deal with windows that are attached to windows
7745 // that are themselves attached.
7746 for (i = topAttached; i >= 0; i--) {
7747 WindowState win = (WindowState) mWindows.get(i);
7748
7749 // If this view is GONE, then skip it -- keep the current
7750 // frame, and let the caller know so they can ignore it
7751 // if they want. (We do the normal layout for INVISIBLE
7752 // windows, since that means "perform layout as normal,
7753 // just don't display").
7754 if (win.mLayoutAttached) {
7755 if ((win.mViewVisibility != View.GONE && win.mRelayoutCalled)
7756 || !win.mHaveFrame) {
7757 mPolicy.layoutWindowLw(win, win.mAttrs, win.mAttachedWindow);
7758 }
7759 }
7760 }
7761
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07007762 if (!mPolicy.finishLayoutLw()) {
7763 mLayoutNeeded = false;
7764 } else if (repeats > 2) {
7765 Log.w(TAG, "Layout repeat aborted after too many iterations");
7766 mLayoutNeeded = false;
7767 } else {
7768 repeats++;
7769 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007770 }
7771 }
7772
7773 private final void performLayoutAndPlaceSurfacesLockedInner(
7774 boolean recoveringMemory) {
7775 final long currentTime = SystemClock.uptimeMillis();
7776 final int dw = mDisplay.getWidth();
7777 final int dh = mDisplay.getHeight();
7778
7779 final int N = mWindows.size();
7780 int i;
7781
7782 // FIRST LOOP: Perform a layout, if needed.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007783 performLayoutLockedInner();
7784
7785 if (mFxSession == null) {
7786 mFxSession = new SurfaceSession();
7787 }
7788
7789 if (SHOW_TRANSACTIONS) Log.i(TAG, ">>> OPEN TRANSACTION");
7790
7791 // Initialize state of exiting tokens.
7792 for (i=mExitingTokens.size()-1; i>=0; i--) {
7793 mExitingTokens.get(i).hasVisible = false;
7794 }
7795
7796 // Initialize state of exiting applications.
7797 for (i=mExitingAppTokens.size()-1; i>=0; i--) {
7798 mExitingAppTokens.get(i).hasVisible = false;
7799 }
7800
7801 // SECOND LOOP: Execute animations and update visibility of windows.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007802 boolean orientationChangeComplete = true;
7803 Session holdScreen = null;
7804 float screenBrightness = -1;
7805 boolean focusDisplayed = false;
7806 boolean animating = false;
7807
7808 Surface.openTransaction();
7809 try {
7810 boolean restart;
7811
7812 do {
7813 final int transactionSequence = ++mTransactionSequence;
7814
7815 // Update animations of all applications, including those
7816 // associated with exiting/removed apps
7817 boolean tokensAnimating = false;
7818 final int NAT = mAppTokens.size();
7819 for (i=0; i<NAT; i++) {
7820 if (mAppTokens.get(i).stepAnimationLocked(currentTime, dw, dh)) {
7821 tokensAnimating = true;
7822 }
7823 }
7824 final int NEAT = mExitingAppTokens.size();
7825 for (i=0; i<NEAT; i++) {
7826 if (mExitingAppTokens.get(i).stepAnimationLocked(currentTime, dw, dh)) {
7827 tokensAnimating = true;
7828 }
7829 }
7830
7831 animating = tokensAnimating;
7832 restart = false;
7833
7834 boolean tokenMayBeDrawn = false;
7835
7836 mPolicy.beginAnimationLw(dw, dh);
7837
7838 for (i=N-1; i>=0; i--) {
7839 WindowState w = (WindowState)mWindows.get(i);
7840
7841 final WindowManager.LayoutParams attrs = w.mAttrs;
7842
7843 if (w.mSurface != null) {
7844 // Execute animation.
7845 w.commitFinishDrawingLocked(currentTime);
7846 if (w.stepAnimationLocked(currentTime, dw, dh)) {
7847 animating = true;
7848 //w.dump(" ");
7849 }
7850
7851 mPolicy.animatingWindowLw(w, attrs);
7852 }
7853
7854 final AppWindowToken atoken = w.mAppToken;
7855 if (atoken != null && (!atoken.allDrawn || atoken.freezingScreen)) {
7856 if (atoken.lastTransactionSequence != transactionSequence) {
7857 atoken.lastTransactionSequence = transactionSequence;
7858 atoken.numInterestingWindows = atoken.numDrawnWindows = 0;
7859 atoken.startingDisplayed = false;
7860 }
7861 if ((w.isOnScreen() || w.mAttrs.type
7862 == WindowManager.LayoutParams.TYPE_BASE_APPLICATION)
7863 && !w.mExiting && !w.mDestroying) {
7864 if (DEBUG_VISIBILITY || DEBUG_ORIENTATION) {
7865 Log.v(TAG, "Eval win " + w + ": isDisplayed="
7866 + w.isDisplayedLw()
7867 + ", isAnimating=" + w.isAnimating());
7868 if (!w.isDisplayedLw()) {
7869 Log.v(TAG, "Not displayed: s=" + w.mSurface
7870 + " pv=" + w.mPolicyVisibility
7871 + " dp=" + w.mDrawPending
7872 + " cdp=" + w.mCommitDrawPending
7873 + " ah=" + w.mAttachedHidden
7874 + " th=" + atoken.hiddenRequested
7875 + " a=" + w.mAnimating);
7876 }
7877 }
7878 if (w != atoken.startingWindow) {
7879 if (!atoken.freezingScreen || !w.mAppFreezing) {
7880 atoken.numInterestingWindows++;
7881 if (w.isDisplayedLw()) {
7882 atoken.numDrawnWindows++;
7883 if (DEBUG_VISIBILITY || DEBUG_ORIENTATION) Log.v(TAG,
7884 "tokenMayBeDrawn: " + atoken
7885 + " freezingScreen=" + atoken.freezingScreen
7886 + " mAppFreezing=" + w.mAppFreezing);
7887 tokenMayBeDrawn = true;
7888 }
7889 }
7890 } else if (w.isDisplayedLw()) {
7891 atoken.startingDisplayed = true;
7892 }
7893 }
7894 } else if (w.mReadyToShow) {
7895 w.performShowLocked();
7896 }
7897 }
7898
7899 if (mPolicy.finishAnimationLw()) {
7900 restart = true;
7901 }
7902
7903 if (tokenMayBeDrawn) {
7904 // See if any windows have been drawn, so they (and others
7905 // associated with them) can now be shown.
7906 final int NT = mTokenList.size();
7907 for (i=0; i<NT; i++) {
7908 AppWindowToken wtoken = mTokenList.get(i).appWindowToken;
7909 if (wtoken == null) {
7910 continue;
7911 }
7912 if (wtoken.freezingScreen) {
7913 int numInteresting = wtoken.numInterestingWindows;
7914 if (numInteresting > 0 && wtoken.numDrawnWindows >= numInteresting) {
7915 if (DEBUG_VISIBILITY) Log.v(TAG,
7916 "allDrawn: " + wtoken
7917 + " interesting=" + numInteresting
7918 + " drawn=" + wtoken.numDrawnWindows);
7919 wtoken.showAllWindowsLocked();
7920 unsetAppFreezingScreenLocked(wtoken, false, true);
7921 orientationChangeComplete = true;
7922 }
7923 } else if (!wtoken.allDrawn) {
7924 int numInteresting = wtoken.numInterestingWindows;
7925 if (numInteresting > 0 && wtoken.numDrawnWindows >= numInteresting) {
7926 if (DEBUG_VISIBILITY) Log.v(TAG,
7927 "allDrawn: " + wtoken
7928 + " interesting=" + numInteresting
7929 + " drawn=" + wtoken.numDrawnWindows);
7930 wtoken.allDrawn = true;
7931 restart = true;
7932
7933 // We can now show all of the drawn windows!
7934 if (!mOpeningApps.contains(wtoken)) {
7935 wtoken.showAllWindowsLocked();
7936 }
7937 }
7938 }
7939 }
7940 }
7941
7942 // If we are ready to perform an app transition, check through
7943 // all of the app tokens to be shown and see if they are ready
7944 // to go.
7945 if (mAppTransitionReady) {
7946 int NN = mOpeningApps.size();
7947 boolean goodToGo = true;
7948 if (DEBUG_APP_TRANSITIONS) Log.v(TAG,
7949 "Checking " + NN + " opening apps (frozen="
7950 + mDisplayFrozen + " timeout="
7951 + mAppTransitionTimeout + ")...");
7952 if (!mDisplayFrozen && !mAppTransitionTimeout) {
7953 // If the display isn't frozen, wait to do anything until
7954 // all of the apps are ready. Otherwise just go because
7955 // we'll unfreeze the display when everyone is ready.
7956 for (i=0; i<NN && goodToGo; i++) {
7957 AppWindowToken wtoken = mOpeningApps.get(i);
7958 if (DEBUG_APP_TRANSITIONS) Log.v(TAG,
7959 "Check opening app" + wtoken + ": allDrawn="
7960 + wtoken.allDrawn + " startingDisplayed="
7961 + wtoken.startingDisplayed);
7962 if (!wtoken.allDrawn && !wtoken.startingDisplayed
7963 && !wtoken.startingMoved) {
7964 goodToGo = false;
7965 }
7966 }
7967 }
7968 if (goodToGo) {
7969 if (DEBUG_APP_TRANSITIONS) Log.v(TAG, "**** GOOD TO GO");
7970 int transit = mNextAppTransition;
7971 if (mSkipAppTransitionAnimation) {
7972 transit = WindowManagerPolicy.TRANSIT_NONE;
7973 }
7974 mNextAppTransition = WindowManagerPolicy.TRANSIT_NONE;
7975 mAppTransitionReady = false;
7976 mAppTransitionTimeout = false;
7977 mStartingIconInTransition = false;
7978 mSkipAppTransitionAnimation = false;
7979
7980 mH.removeMessages(H.APP_TRANSITION_TIMEOUT);
7981
7982 // We need to figure out which animation to use...
7983 WindowManager.LayoutParams lp = findAnimations(mAppTokens,
7984 mOpeningApps, mClosingApps);
7985
7986 NN = mOpeningApps.size();
7987 for (i=0; i<NN; i++) {
7988 AppWindowToken wtoken = mOpeningApps.get(i);
7989 if (DEBUG_APP_TRANSITIONS) Log.v(TAG,
7990 "Now opening app" + wtoken);
7991 wtoken.reportedVisible = false;
7992 wtoken.inPendingTransaction = false;
7993 setTokenVisibilityLocked(wtoken, lp, true, transit, false);
7994 wtoken.updateReportedVisibilityLocked();
7995 wtoken.showAllWindowsLocked();
7996 }
7997 NN = mClosingApps.size();
7998 for (i=0; i<NN; i++) {
7999 AppWindowToken wtoken = mClosingApps.get(i);
8000 if (DEBUG_APP_TRANSITIONS) Log.v(TAG,
8001 "Now closing app" + wtoken);
8002 wtoken.inPendingTransaction = false;
8003 setTokenVisibilityLocked(wtoken, lp, false, transit, false);
8004 wtoken.updateReportedVisibilityLocked();
8005 // Force the allDrawn flag, because we want to start
8006 // this guy's animations regardless of whether it's
8007 // gotten drawn.
8008 wtoken.allDrawn = true;
8009 }
8010
8011 mOpeningApps.clear();
8012 mClosingApps.clear();
8013
8014 // This has changed the visibility of windows, so perform
8015 // a new layout to get them all up-to-date.
8016 mLayoutNeeded = true;
8017 moveInputMethodWindowsIfNeededLocked(true);
8018 performLayoutLockedInner();
8019 updateFocusedWindowLocked(UPDATE_FOCUS_PLACING_SURFACES);
8020
8021 restart = true;
8022 }
8023 }
8024 } while (restart);
8025
8026 // THIRD LOOP: Update the surfaces of all windows.
8027
8028 final boolean someoneLosingFocus = mLosingFocus.size() != 0;
8029
8030 boolean obscured = false;
8031 boolean blurring = false;
8032 boolean dimming = false;
8033 boolean covered = false;
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07008034 boolean syswin = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008035
8036 for (i=N-1; i>=0; i--) {
8037 WindowState w = (WindowState)mWindows.get(i);
8038
8039 boolean displayed = false;
8040 final WindowManager.LayoutParams attrs = w.mAttrs;
8041 final int attrFlags = attrs.flags;
8042
8043 if (w.mSurface != null) {
8044 w.computeShownFrameLocked();
8045 if (localLOGV) Log.v(
8046 TAG, "Placing surface #" + i + " " + w.mSurface
8047 + ": new=" + w.mShownFrame + ", old="
8048 + w.mLastShownFrame);
8049
8050 boolean resize;
8051 int width, height;
8052 if ((w.mAttrs.flags & w.mAttrs.FLAG_SCALED) != 0) {
8053 resize = w.mLastRequestedWidth != w.mRequestedWidth ||
8054 w.mLastRequestedHeight != w.mRequestedHeight;
8055 // for a scaled surface, we just want to use
8056 // the requested size.
8057 width = w.mRequestedWidth;
8058 height = w.mRequestedHeight;
8059 w.mLastRequestedWidth = width;
8060 w.mLastRequestedHeight = height;
8061 w.mLastShownFrame.set(w.mShownFrame);
8062 try {
8063 w.mSurface.setPosition(w.mShownFrame.left, w.mShownFrame.top);
8064 } catch (RuntimeException e) {
8065 Log.w(TAG, "Error positioning surface in " + w, e);
8066 if (!recoveringMemory) {
8067 reclaimSomeSurfaceMemoryLocked(w, "position");
8068 }
8069 }
8070 } else {
8071 resize = !w.mLastShownFrame.equals(w.mShownFrame);
8072 width = w.mShownFrame.width();
8073 height = w.mShownFrame.height();
8074 w.mLastShownFrame.set(w.mShownFrame);
8075 if (resize) {
8076 if (SHOW_TRANSACTIONS) Log.i(
8077 TAG, " SURFACE " + w.mSurface + ": ("
8078 + w.mShownFrame.left + ","
8079 + w.mShownFrame.top + ") ("
8080 + w.mShownFrame.width() + "x"
8081 + w.mShownFrame.height() + ")");
8082 }
8083 }
8084
8085 if (resize) {
8086 if (width < 1) width = 1;
8087 if (height < 1) height = 1;
8088 if (w.mSurface != null) {
8089 try {
8090 w.mSurface.setSize(width, height);
8091 w.mSurface.setPosition(w.mShownFrame.left,
8092 w.mShownFrame.top);
8093 } catch (RuntimeException e) {
8094 // If something goes wrong with the surface (such
8095 // as running out of memory), don't take down the
8096 // entire system.
8097 Log.e(TAG, "Failure updating surface of " + w
8098 + "size=(" + width + "x" + height
8099 + "), pos=(" + w.mShownFrame.left
8100 + "," + w.mShownFrame.top + ")", e);
8101 if (!recoveringMemory) {
8102 reclaimSomeSurfaceMemoryLocked(w, "size");
8103 }
8104 }
8105 }
8106 }
8107 if (!w.mAppFreezing) {
8108 w.mContentInsetsChanged =
8109 !w.mLastContentInsets.equals(w.mContentInsets);
8110 w.mVisibleInsetsChanged =
8111 !w.mLastVisibleInsets.equals(w.mVisibleInsets);
8112 if (!w.mLastFrame.equals(w.mFrame)
8113 || w.mContentInsetsChanged
8114 || w.mVisibleInsetsChanged) {
8115 w.mLastFrame.set(w.mFrame);
8116 w.mLastContentInsets.set(w.mContentInsets);
8117 w.mLastVisibleInsets.set(w.mVisibleInsets);
8118 // If the orientation is changing, then we need to
8119 // hold off on unfreezing the display until this
8120 // window has been redrawn; to do that, we need
8121 // to go through the process of getting informed
8122 // by the application when it has finished drawing.
8123 if (w.mOrientationChanging) {
8124 if (DEBUG_ORIENTATION) Log.v(TAG,
8125 "Orientation start waiting for draw in "
8126 + w + ", surface " + w.mSurface);
8127 w.mDrawPending = true;
8128 w.mCommitDrawPending = false;
8129 w.mReadyToShow = false;
8130 if (w.mAppToken != null) {
8131 w.mAppToken.allDrawn = false;
8132 }
8133 }
8134 if (DEBUG_ORIENTATION) Log.v(TAG,
8135 "Resizing window " + w + " to " + w.mFrame);
8136 mResizingWindows.add(w);
8137 } else if (w.mOrientationChanging) {
8138 if (!w.mDrawPending && !w.mCommitDrawPending) {
8139 if (DEBUG_ORIENTATION) Log.v(TAG,
8140 "Orientation not waiting for draw in "
8141 + w + ", surface " + w.mSurface);
8142 w.mOrientationChanging = false;
8143 }
8144 }
8145 }
8146
8147 if (w.mAttachedHidden) {
8148 if (!w.mLastHidden) {
8149 //dump();
8150 w.mLastHidden = true;
8151 if (SHOW_TRANSACTIONS) Log.i(
8152 TAG, " SURFACE " + w.mSurface + ": HIDE (performLayout-attached)");
8153 if (w.mSurface != null) {
8154 try {
8155 w.mSurface.hide();
8156 } catch (RuntimeException e) {
8157 Log.w(TAG, "Exception hiding surface in " + w);
8158 }
8159 }
8160 mKeyWaiter.releasePendingPointerLocked(w.mSession);
8161 }
8162 // If we are waiting for this window to handle an
8163 // orientation change, well, it is hidden, so
8164 // doesn't really matter. Note that this does
8165 // introduce a potential glitch if the window
8166 // becomes unhidden before it has drawn for the
8167 // new orientation.
8168 if (w.mOrientationChanging) {
8169 w.mOrientationChanging = false;
8170 if (DEBUG_ORIENTATION) Log.v(TAG,
8171 "Orientation change skips hidden " + w);
8172 }
8173 } else if (!w.isReadyForDisplay()) {
8174 if (!w.mLastHidden) {
8175 //dump();
8176 w.mLastHidden = true;
8177 if (SHOW_TRANSACTIONS) Log.i(
8178 TAG, " SURFACE " + w.mSurface + ": HIDE (performLayout-ready)");
8179 if (w.mSurface != null) {
8180 try {
8181 w.mSurface.hide();
8182 } catch (RuntimeException e) {
8183 Log.w(TAG, "Exception exception hiding surface in " + w);
8184 }
8185 }
8186 mKeyWaiter.releasePendingPointerLocked(w.mSession);
8187 }
8188 // If we are waiting for this window to handle an
8189 // orientation change, well, it is hidden, so
8190 // doesn't really matter. Note that this does
8191 // introduce a potential glitch if the window
8192 // becomes unhidden before it has drawn for the
8193 // new orientation.
8194 if (w.mOrientationChanging) {
8195 w.mOrientationChanging = false;
8196 if (DEBUG_ORIENTATION) Log.v(TAG,
8197 "Orientation change skips hidden " + w);
8198 }
8199 } else if (w.mLastLayer != w.mAnimLayer
8200 || w.mLastAlpha != w.mShownAlpha
8201 || w.mLastDsDx != w.mDsDx
8202 || w.mLastDtDx != w.mDtDx
8203 || w.mLastDsDy != w.mDsDy
8204 || w.mLastDtDy != w.mDtDy
8205 || w.mLastHScale != w.mHScale
8206 || w.mLastVScale != w.mVScale
8207 || w.mLastHidden) {
8208 displayed = true;
8209 w.mLastAlpha = w.mShownAlpha;
8210 w.mLastLayer = w.mAnimLayer;
8211 w.mLastDsDx = w.mDsDx;
8212 w.mLastDtDx = w.mDtDx;
8213 w.mLastDsDy = w.mDsDy;
8214 w.mLastDtDy = w.mDtDy;
8215 w.mLastHScale = w.mHScale;
8216 w.mLastVScale = w.mVScale;
8217 if (SHOW_TRANSACTIONS) Log.i(
8218 TAG, " SURFACE " + w.mSurface + ": alpha="
8219 + w.mShownAlpha + " layer=" + w.mAnimLayer);
8220 if (w.mSurface != null) {
8221 try {
8222 w.mSurface.setAlpha(w.mShownAlpha);
8223 w.mSurface.setLayer(w.mAnimLayer);
8224 w.mSurface.setMatrix(
8225 w.mDsDx*w.mHScale, w.mDtDx*w.mVScale,
8226 w.mDsDy*w.mHScale, w.mDtDy*w.mVScale);
8227 } catch (RuntimeException e) {
8228 Log.w(TAG, "Error updating surface in " + w, e);
8229 if (!recoveringMemory) {
8230 reclaimSomeSurfaceMemoryLocked(w, "update");
8231 }
8232 }
8233 }
8234
8235 if (w.mLastHidden && !w.mDrawPending
8236 && !w.mCommitDrawPending
8237 && !w.mReadyToShow) {
8238 if (SHOW_TRANSACTIONS) Log.i(
8239 TAG, " SURFACE " + w.mSurface + ": SHOW (performLayout)");
8240 if (DEBUG_VISIBILITY) Log.v(TAG, "Showing " + w
8241 + " during relayout");
8242 if (showSurfaceRobustlyLocked(w)) {
8243 w.mHasDrawn = true;
8244 w.mLastHidden = false;
8245 } else {
8246 w.mOrientationChanging = false;
8247 }
8248 }
8249 if (w.mSurface != null) {
8250 w.mToken.hasVisible = true;
8251 }
8252 } else {
8253 displayed = true;
8254 }
8255
8256 if (displayed) {
8257 if (!covered) {
8258 if (attrs.width == LayoutParams.FILL_PARENT
8259 && attrs.height == LayoutParams.FILL_PARENT) {
8260 covered = true;
8261 }
8262 }
8263 if (w.mOrientationChanging) {
8264 if (w.mDrawPending || w.mCommitDrawPending) {
8265 orientationChangeComplete = false;
8266 if (DEBUG_ORIENTATION) Log.v(TAG,
8267 "Orientation continue waiting for draw in " + w);
8268 } else {
8269 w.mOrientationChanging = false;
8270 if (DEBUG_ORIENTATION) Log.v(TAG,
8271 "Orientation change complete in " + w);
8272 }
8273 }
8274 w.mToken.hasVisible = true;
8275 }
8276 } else if (w.mOrientationChanging) {
8277 if (DEBUG_ORIENTATION) Log.v(TAG,
8278 "Orientation change skips hidden " + w);
8279 w.mOrientationChanging = false;
8280 }
8281
8282 final boolean canBeSeen = w.isDisplayedLw();
8283
8284 if (someoneLosingFocus && w == mCurrentFocus && canBeSeen) {
8285 focusDisplayed = true;
8286 }
8287
8288 // Update effect.
8289 if (!obscured) {
8290 if (w.mSurface != null) {
8291 if ((attrFlags&FLAG_KEEP_SCREEN_ON) != 0) {
8292 holdScreen = w.mSession;
8293 }
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07008294 if (!syswin && w.mAttrs.screenBrightness >= 0
8295 && screenBrightness < 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008296 screenBrightness = w.mAttrs.screenBrightness;
8297 }
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07008298 if (attrs.type == WindowManager.LayoutParams.TYPE_SYSTEM_DIALOG
8299 || attrs.type == WindowManager.LayoutParams.TYPE_KEYGUARD
8300 || attrs.type == WindowManager.LayoutParams.TYPE_SYSTEM_ERROR) {
8301 syswin = true;
8302 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008303 }
8304 if (w.isFullscreenOpaque(dw, dh)) {
8305 // This window completely covers everything behind it,
8306 // so we want to leave all of them as unblurred (for
8307 // performance reasons).
8308 obscured = true;
8309 } else if (canBeSeen && !obscured &&
8310 (attrFlags&FLAG_BLUR_BEHIND|FLAG_DIM_BEHIND) != 0) {
8311 if (localLOGV) Log.v(TAG, "Win " + w
8312 + ": blurring=" + blurring
8313 + " obscured=" + obscured
8314 + " displayed=" + displayed);
8315 if ((attrFlags&FLAG_DIM_BEHIND) != 0) {
8316 if (!dimming) {
8317 //Log.i(TAG, "DIM BEHIND: " + w);
8318 dimming = true;
8319 mDimShown = true;
8320 if (mDimSurface == null) {
8321 if (SHOW_TRANSACTIONS) Log.i(TAG, " DIM "
8322 + mDimSurface + ": CREATE");
8323 try {
8324 mDimSurface = new Surface(mFxSession, 0,
8325 -1, 16, 16,
8326 PixelFormat.OPAQUE,
8327 Surface.FX_SURFACE_DIM);
8328 } catch (Exception e) {
8329 Log.e(TAG, "Exception creating Dim surface", e);
8330 }
8331 }
8332 if (SHOW_TRANSACTIONS) Log.i(TAG, " DIM "
8333 + mDimSurface + ": SHOW pos=(0,0) (" +
8334 dw + "x" + dh + "), layer=" + (w.mAnimLayer-1));
8335 if (mDimSurface != null) {
8336 try {
8337 mDimSurface.setPosition(0, 0);
8338 mDimSurface.setSize(dw, dh);
8339 mDimSurface.show();
8340 } catch (RuntimeException e) {
8341 Log.w(TAG, "Failure showing dim surface", e);
8342 }
8343 }
8344 }
8345 mDimSurface.setLayer(w.mAnimLayer-1);
8346 final float target = w.mExiting ? 0 : attrs.dimAmount;
8347 if (mDimTargetAlpha != target) {
8348 // If the desired dim level has changed, then
8349 // start an animation to it.
8350 mLastDimAnimTime = currentTime;
8351 long duration = (w.mAnimating && w.mAnimation != null)
8352 ? w.mAnimation.computeDurationHint()
8353 : DEFAULT_DIM_DURATION;
8354 if (target > mDimTargetAlpha) {
8355 // This is happening behind the activity UI,
8356 // so we can make it run a little longer to
8357 // give a stronger impression without disrupting
8358 // the user.
8359 duration *= DIM_DURATION_MULTIPLIER;
8360 }
8361 if (duration < 1) {
8362 // Don't divide by zero
8363 duration = 1;
8364 }
8365 mDimTargetAlpha = target;
8366 mDimDeltaPerMs = (mDimTargetAlpha-mDimCurrentAlpha)
8367 / duration;
8368 }
8369 }
8370 if ((attrFlags&FLAG_BLUR_BEHIND) != 0) {
8371 if (!blurring) {
8372 //Log.i(TAG, "BLUR BEHIND: " + w);
8373 blurring = true;
8374 mBlurShown = true;
8375 if (mBlurSurface == null) {
8376 if (SHOW_TRANSACTIONS) Log.i(TAG, " BLUR "
8377 + mBlurSurface + ": CREATE");
8378 try {
8379 mBlurSurface = new Surface(mFxSession, 0,
8380 -1, 16, 16,
8381 PixelFormat.OPAQUE,
8382 Surface.FX_SURFACE_BLUR);
8383 } catch (Exception e) {
8384 Log.e(TAG, "Exception creating Blur surface", e);
8385 }
8386 }
8387 if (SHOW_TRANSACTIONS) Log.i(TAG, " BLUR "
8388 + mBlurSurface + ": SHOW pos=(0,0) (" +
8389 dw + "x" + dh + "), layer=" + (w.mAnimLayer-1));
8390 if (mBlurSurface != null) {
8391 mBlurSurface.setPosition(0, 0);
8392 mBlurSurface.setSize(dw, dh);
8393 try {
8394 mBlurSurface.show();
8395 } catch (RuntimeException e) {
8396 Log.w(TAG, "Failure showing blur surface", e);
8397 }
8398 }
8399 }
8400 mBlurSurface.setLayer(w.mAnimLayer-2);
8401 }
8402 }
8403 }
8404 }
8405
8406 if (!dimming && mDimShown) {
8407 // Time to hide the dim surface... start fading.
8408 if (mDimTargetAlpha != 0) {
8409 mLastDimAnimTime = currentTime;
8410 mDimTargetAlpha = 0;
8411 mDimDeltaPerMs = (-mDimCurrentAlpha) / DEFAULT_DIM_DURATION;
8412 }
8413 }
8414
8415 if (mDimShown && mLastDimAnimTime != 0) {
8416 mDimCurrentAlpha += mDimDeltaPerMs
8417 * (currentTime-mLastDimAnimTime);
8418 boolean more = true;
8419 if (mDisplayFrozen) {
8420 // If the display is frozen, there is no reason to animate.
8421 more = false;
8422 } else if (mDimDeltaPerMs > 0) {
8423 if (mDimCurrentAlpha > mDimTargetAlpha) {
8424 more = false;
8425 }
8426 } else if (mDimDeltaPerMs < 0) {
8427 if (mDimCurrentAlpha < mDimTargetAlpha) {
8428 more = false;
8429 }
8430 } else {
8431 more = false;
8432 }
8433
8434 // Do we need to continue animating?
8435 if (more) {
8436 if (SHOW_TRANSACTIONS) Log.i(TAG, " DIM "
8437 + mDimSurface + ": alpha=" + mDimCurrentAlpha);
8438 mLastDimAnimTime = currentTime;
8439 mDimSurface.setAlpha(mDimCurrentAlpha);
8440 animating = true;
8441 } else {
8442 mDimCurrentAlpha = mDimTargetAlpha;
8443 mLastDimAnimTime = 0;
8444 if (SHOW_TRANSACTIONS) Log.i(TAG, " DIM "
8445 + mDimSurface + ": final alpha=" + mDimCurrentAlpha);
8446 mDimSurface.setAlpha(mDimCurrentAlpha);
8447 if (!dimming) {
8448 if (SHOW_TRANSACTIONS) Log.i(TAG, " DIM " + mDimSurface
8449 + ": HIDE");
8450 try {
8451 mDimSurface.hide();
8452 } catch (RuntimeException e) {
8453 Log.w(TAG, "Illegal argument exception hiding dim surface");
8454 }
8455 mDimShown = false;
8456 }
8457 }
8458 }
8459
8460 if (!blurring && mBlurShown) {
8461 if (SHOW_TRANSACTIONS) Log.i(TAG, " BLUR " + mBlurSurface
8462 + ": HIDE");
8463 try {
8464 mBlurSurface.hide();
8465 } catch (IllegalArgumentException e) {
8466 Log.w(TAG, "Illegal argument exception hiding blur surface");
8467 }
8468 mBlurShown = false;
8469 }
8470
8471 if (SHOW_TRANSACTIONS) Log.i(TAG, "<<< CLOSE TRANSACTION");
8472 } catch (RuntimeException e) {
8473 Log.e(TAG, "Unhandled exception in Window Manager", e);
8474 }
8475
8476 Surface.closeTransaction();
8477
8478 if (DEBUG_ORIENTATION && mDisplayFrozen) Log.v(TAG,
8479 "With display frozen, orientationChangeComplete="
8480 + orientationChangeComplete);
8481 if (orientationChangeComplete) {
8482 if (mWindowsFreezingScreen) {
8483 mWindowsFreezingScreen = false;
8484 mH.removeMessages(H.WINDOW_FREEZE_TIMEOUT);
8485 }
8486 if (mAppsFreezingScreen == 0) {
8487 stopFreezingDisplayLocked();
8488 }
8489 }
8490
8491 i = mResizingWindows.size();
8492 if (i > 0) {
8493 do {
8494 i--;
8495 WindowState win = mResizingWindows.get(i);
8496 try {
8497 win.mClient.resized(win.mFrame.width(),
8498 win.mFrame.height(), win.mLastContentInsets,
8499 win.mLastVisibleInsets, win.mDrawPending);
8500 win.mContentInsetsChanged = false;
8501 win.mVisibleInsetsChanged = false;
8502 } catch (RemoteException e) {
8503 win.mOrientationChanging = false;
8504 }
8505 } while (i > 0);
8506 mResizingWindows.clear();
8507 }
8508
8509 // Destroy the surface of any windows that are no longer visible.
8510 i = mDestroySurface.size();
8511 if (i > 0) {
8512 do {
8513 i--;
8514 WindowState win = mDestroySurface.get(i);
8515 win.mDestroying = false;
8516 if (mInputMethodWindow == win) {
8517 mInputMethodWindow = null;
8518 }
8519 win.destroySurfaceLocked();
8520 } while (i > 0);
8521 mDestroySurface.clear();
8522 }
8523
8524 // Time to remove any exiting tokens?
8525 for (i=mExitingTokens.size()-1; i>=0; i--) {
8526 WindowToken token = mExitingTokens.get(i);
8527 if (!token.hasVisible) {
8528 mExitingTokens.remove(i);
8529 }
8530 }
8531
8532 // Time to remove any exiting applications?
8533 for (i=mExitingAppTokens.size()-1; i>=0; i--) {
8534 AppWindowToken token = mExitingAppTokens.get(i);
8535 if (!token.hasVisible && !mClosingApps.contains(token)) {
8536 mAppTokens.remove(token);
8537 mExitingAppTokens.remove(i);
8538 }
8539 }
8540
8541 if (focusDisplayed) {
8542 mH.sendEmptyMessage(H.REPORT_LOSING_FOCUS);
8543 }
8544 if (animating) {
8545 requestAnimationLocked(currentTime+(1000/60)-SystemClock.uptimeMillis());
8546 }
8547 mQueue.setHoldScreenLocked(holdScreen != null);
8548 if (screenBrightness < 0 || screenBrightness > 1.0f) {
8549 mPowerManager.setScreenBrightnessOverride(-1);
8550 } else {
8551 mPowerManager.setScreenBrightnessOverride((int)
8552 (screenBrightness * Power.BRIGHTNESS_ON));
8553 }
8554 if (holdScreen != mHoldingScreenOn) {
8555 mHoldingScreenOn = holdScreen;
8556 Message m = mH.obtainMessage(H.HOLD_SCREEN_CHANGED, holdScreen);
8557 mH.sendMessage(m);
8558 }
8559 }
8560
8561 void requestAnimationLocked(long delay) {
8562 if (!mAnimationPending) {
8563 mAnimationPending = true;
8564 mH.sendMessageDelayed(mH.obtainMessage(H.ANIMATE), delay);
8565 }
8566 }
8567
8568 /**
8569 * Have the surface flinger show a surface, robustly dealing with
8570 * error conditions. In particular, if there is not enough memory
8571 * to show the surface, then we will try to get rid of other surfaces
8572 * in order to succeed.
8573 *
8574 * @return Returns true if the surface was successfully shown.
8575 */
8576 boolean showSurfaceRobustlyLocked(WindowState win) {
8577 try {
8578 if (win.mSurface != null) {
8579 win.mSurface.show();
8580 }
8581 return true;
8582 } catch (RuntimeException e) {
8583 Log.w(TAG, "Failure showing surface " + win.mSurface + " in " + win);
8584 }
8585
8586 reclaimSomeSurfaceMemoryLocked(win, "show");
8587
8588 return false;
8589 }
8590
8591 void reclaimSomeSurfaceMemoryLocked(WindowState win, String operation) {
8592 final Surface surface = win.mSurface;
8593
8594 EventLog.writeEvent(LOG_WM_NO_SURFACE_MEMORY, win.toString(),
8595 win.mSession.mPid, operation);
8596
8597 if (mForceRemoves == null) {
8598 mForceRemoves = new ArrayList<WindowState>();
8599 }
8600
8601 long callingIdentity = Binder.clearCallingIdentity();
8602 try {
8603 // There was some problem... first, do a sanity check of the
8604 // window list to make sure we haven't left any dangling surfaces
8605 // around.
8606 int N = mWindows.size();
8607 boolean leakedSurface = false;
8608 Log.i(TAG, "Out of memory for surface! Looking for leaks...");
8609 for (int i=0; i<N; i++) {
8610 WindowState ws = (WindowState)mWindows.get(i);
8611 if (ws.mSurface != null) {
8612 if (!mSessions.contains(ws.mSession)) {
8613 Log.w(TAG, "LEAKED SURFACE (session doesn't exist): "
8614 + ws + " surface=" + ws.mSurface
8615 + " token=" + win.mToken
8616 + " pid=" + ws.mSession.mPid
8617 + " uid=" + ws.mSession.mUid);
8618 ws.mSurface.clear();
8619 ws.mSurface = null;
8620 mForceRemoves.add(ws);
8621 i--;
8622 N--;
8623 leakedSurface = true;
8624 } else if (win.mAppToken != null && win.mAppToken.clientHidden) {
8625 Log.w(TAG, "LEAKED SURFACE (app token hidden): "
8626 + ws + " surface=" + ws.mSurface
8627 + " token=" + win.mAppToken);
8628 ws.mSurface.clear();
8629 ws.mSurface = null;
8630 leakedSurface = true;
8631 }
8632 }
8633 }
8634
8635 boolean killedApps = false;
8636 if (!leakedSurface) {
8637 Log.w(TAG, "No leaked surfaces; killing applicatons!");
8638 SparseIntArray pidCandidates = new SparseIntArray();
8639 for (int i=0; i<N; i++) {
8640 WindowState ws = (WindowState)mWindows.get(i);
8641 if (ws.mSurface != null) {
8642 pidCandidates.append(ws.mSession.mPid, ws.mSession.mPid);
8643 }
8644 }
8645 if (pidCandidates.size() > 0) {
8646 int[] pids = new int[pidCandidates.size()];
8647 for (int i=0; i<pids.length; i++) {
8648 pids[i] = pidCandidates.keyAt(i);
8649 }
8650 try {
8651 if (mActivityManager.killPidsForMemory(pids)) {
8652 killedApps = true;
8653 }
8654 } catch (RemoteException e) {
8655 }
8656 }
8657 }
8658
8659 if (leakedSurface || killedApps) {
8660 // We managed to reclaim some memory, so get rid of the trouble
8661 // surface and ask the app to request another one.
8662 Log.w(TAG, "Looks like we have reclaimed some memory, clearing surface for retry.");
8663 if (surface != null) {
8664 surface.clear();
8665 win.mSurface = null;
8666 }
8667
8668 try {
8669 win.mClient.dispatchGetNewSurface();
8670 } catch (RemoteException e) {
8671 }
8672 }
8673 } finally {
8674 Binder.restoreCallingIdentity(callingIdentity);
8675 }
8676 }
8677
8678 private boolean updateFocusedWindowLocked(int mode) {
8679 WindowState newFocus = computeFocusedWindowLocked();
8680 if (mCurrentFocus != newFocus) {
8681 // This check makes sure that we don't already have the focus
8682 // change message pending.
8683 mH.removeMessages(H.REPORT_FOCUS_CHANGE);
8684 mH.sendEmptyMessage(H.REPORT_FOCUS_CHANGE);
8685 if (localLOGV) Log.v(
8686 TAG, "Changing focus from " + mCurrentFocus + " to " + newFocus);
8687 final WindowState oldFocus = mCurrentFocus;
8688 mCurrentFocus = newFocus;
8689 mLosingFocus.remove(newFocus);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008690
8691 final WindowState imWindow = mInputMethodWindow;
8692 if (newFocus != imWindow && oldFocus != imWindow) {
The Android Open Source Projectc474dec2009-03-04 09:49:09 -08008693 if (moveInputMethodWindowsIfNeededLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008694 mode != UPDATE_FOCUS_WILL_ASSIGN_LAYERS &&
The Android Open Source Projectc474dec2009-03-04 09:49:09 -08008695 mode != UPDATE_FOCUS_WILL_PLACE_SURFACES)) {
8696 mLayoutNeeded = true;
8697 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008698 if (mode == UPDATE_FOCUS_PLACING_SURFACES) {
8699 performLayoutLockedInner();
The Android Open Source Projectc474dec2009-03-04 09:49:09 -08008700 } else if (mode == UPDATE_FOCUS_WILL_PLACE_SURFACES) {
8701 // Client will do the layout, but we need to assign layers
8702 // for handleNewWindowLocked() below.
8703 assignLayersLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008704 }
8705 }
The Android Open Source Projectc474dec2009-03-04 09:49:09 -08008706
8707 if (newFocus != null && mode != UPDATE_FOCUS_WILL_ASSIGN_LAYERS) {
8708 mKeyWaiter.handleNewWindowLocked(newFocus);
8709 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008710 return true;
8711 }
8712 return false;
8713 }
8714
8715 private WindowState computeFocusedWindowLocked() {
8716 WindowState result = null;
8717 WindowState win;
8718
8719 int i = mWindows.size() - 1;
8720 int nextAppIndex = mAppTokens.size()-1;
8721 WindowToken nextApp = nextAppIndex >= 0
8722 ? mAppTokens.get(nextAppIndex) : null;
8723
8724 while (i >= 0) {
8725 win = (WindowState)mWindows.get(i);
8726
8727 if (localLOGV || DEBUG_FOCUS) Log.v(
8728 TAG, "Looking for focus: " + i
8729 + " = " + win
8730 + ", flags=" + win.mAttrs.flags
8731 + ", canReceive=" + win.canReceiveKeys());
8732
8733 AppWindowToken thisApp = win.mAppToken;
8734
8735 // If this window's application has been removed, just skip it.
8736 if (thisApp != null && thisApp.removed) {
8737 i--;
8738 continue;
8739 }
8740
8741 // If there is a focused app, don't allow focus to go to any
8742 // windows below it. If this is an application window, step
8743 // through the app tokens until we find its app.
8744 if (thisApp != null && nextApp != null && thisApp != nextApp
8745 && win.mAttrs.type != TYPE_APPLICATION_STARTING) {
8746 int origAppIndex = nextAppIndex;
8747 while (nextAppIndex > 0) {
8748 if (nextApp == mFocusedApp) {
8749 // Whoops, we are below the focused app... no focus
8750 // for you!
8751 if (localLOGV || DEBUG_FOCUS) Log.v(
8752 TAG, "Reached focused app: " + mFocusedApp);
8753 return null;
8754 }
8755 nextAppIndex--;
8756 nextApp = mAppTokens.get(nextAppIndex);
8757 if (nextApp == thisApp) {
8758 break;
8759 }
8760 }
8761 if (thisApp != nextApp) {
8762 // Uh oh, the app token doesn't exist! This shouldn't
8763 // happen, but if it does we can get totally hosed...
8764 // so restart at the original app.
8765 nextAppIndex = origAppIndex;
8766 nextApp = mAppTokens.get(nextAppIndex);
8767 }
8768 }
8769
8770 // Dispatch to this window if it is wants key events.
8771 if (win.canReceiveKeys()) {
8772 if (DEBUG_FOCUS) Log.v(
8773 TAG, "Found focus @ " + i + " = " + win);
8774 result = win;
8775 break;
8776 }
8777
8778 i--;
8779 }
8780
8781 return result;
8782 }
8783
8784 private void startFreezingDisplayLocked() {
8785 if (mDisplayFrozen) {
Chris Tate2ad63a92009-03-25 17:36:48 -07008786 // Freezing the display also suspends key event delivery, to
8787 // keep events from going astray while the display is reconfigured.
8788 // If someone has changed orientation again while the screen is
8789 // still frozen, the events will continue to be blocked while the
8790 // successive orientation change is processed. To prevent spurious
8791 // ANRs, we reset the event dispatch timeout in this case.
8792 synchronized (mKeyWaiter) {
8793 mKeyWaiter.mWasFrozen = true;
8794 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008795 return;
8796 }
8797
8798 mScreenFrozenLock.acquire();
8799
8800 long now = SystemClock.uptimeMillis();
8801 //Log.i(TAG, "Freezing, gc pending: " + mFreezeGcPending + ", now " + now);
8802 if (mFreezeGcPending != 0) {
8803 if (now > (mFreezeGcPending+1000)) {
8804 //Log.i(TAG, "Gc! " + now + " > " + (mFreezeGcPending+1000));
8805 mH.removeMessages(H.FORCE_GC);
8806 Runtime.getRuntime().gc();
8807 mFreezeGcPending = now;
8808 }
8809 } else {
8810 mFreezeGcPending = now;
8811 }
8812
8813 mDisplayFrozen = true;
8814 if (mNextAppTransition != WindowManagerPolicy.TRANSIT_NONE) {
8815 mNextAppTransition = WindowManagerPolicy.TRANSIT_NONE;
8816 mAppTransitionReady = true;
8817 }
8818
8819 if (PROFILE_ORIENTATION) {
8820 File file = new File("/data/system/frozen");
8821 Debug.startMethodTracing(file.toString(), 8 * 1024 * 1024);
8822 }
8823 Surface.freezeDisplay(0);
8824 }
8825
8826 private void stopFreezingDisplayLocked() {
8827 if (!mDisplayFrozen) {
8828 return;
8829 }
8830
8831 mDisplayFrozen = false;
8832 mH.removeMessages(H.APP_FREEZE_TIMEOUT);
8833 if (PROFILE_ORIENTATION) {
8834 Debug.stopMethodTracing();
8835 }
8836 Surface.unfreezeDisplay(0);
8837
Chris Tate2ad63a92009-03-25 17:36:48 -07008838 // Reset the key delivery timeout on unfreeze, too. We force a wakeup here
8839 // too because regular key delivery processing should resume immediately.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008840 synchronized (mKeyWaiter) {
8841 mKeyWaiter.mWasFrozen = true;
8842 mKeyWaiter.notifyAll();
8843 }
8844
8845 // A little kludge: a lot could have happened while the
8846 // display was frozen, so now that we are coming back we
8847 // do a gc so that any remote references the system
8848 // processes holds on others can be released if they are
8849 // no longer needed.
8850 mH.removeMessages(H.FORCE_GC);
8851 mH.sendMessageDelayed(mH.obtainMessage(H.FORCE_GC),
8852 2000);
8853
8854 mScreenFrozenLock.release();
8855 }
8856
8857 @Override
8858 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
8859 if (mContext.checkCallingOrSelfPermission("android.permission.DUMP")
8860 != PackageManager.PERMISSION_GRANTED) {
8861 pw.println("Permission Denial: can't dump WindowManager from from pid="
8862 + Binder.getCallingPid()
8863 + ", uid=" + Binder.getCallingUid());
8864 return;
8865 }
8866
8867 synchronized(mWindowMap) {
8868 pw.println("Current Window Manager state:");
8869 for (int i=mWindows.size()-1; i>=0; i--) {
8870 WindowState w = (WindowState)mWindows.get(i);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008871 pw.print(" Window #"); pw.print(i); pw.print(' ');
8872 pw.print(w); pw.println(":");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008873 w.dump(pw, " ");
8874 }
8875 if (mInputMethodDialogs.size() > 0) {
8876 pw.println(" ");
8877 pw.println(" Input method dialogs:");
8878 for (int i=mInputMethodDialogs.size()-1; i>=0; i--) {
8879 WindowState w = mInputMethodDialogs.get(i);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008880 pw.print(" IM Dialog #"); pw.print(i); pw.print(": "); pw.println(w);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008881 }
8882 }
8883 if (mPendingRemove.size() > 0) {
8884 pw.println(" ");
8885 pw.println(" Remove pending for:");
8886 for (int i=mPendingRemove.size()-1; i>=0; i--) {
8887 WindowState w = mPendingRemove.get(i);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008888 pw.print(" Remove #"); pw.print(i); pw.print(' ');
8889 pw.print(w); pw.println(":");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008890 w.dump(pw, " ");
8891 }
8892 }
8893 if (mForceRemoves != null && mForceRemoves.size() > 0) {
8894 pw.println(" ");
8895 pw.println(" Windows force removing:");
8896 for (int i=mForceRemoves.size()-1; i>=0; i--) {
8897 WindowState w = mForceRemoves.get(i);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008898 pw.print(" Removing #"); pw.print(i); pw.print(' ');
8899 pw.print(w); pw.println(":");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008900 w.dump(pw, " ");
8901 }
8902 }
8903 if (mDestroySurface.size() > 0) {
8904 pw.println(" ");
8905 pw.println(" Windows waiting to destroy their surface:");
8906 for (int i=mDestroySurface.size()-1; i>=0; i--) {
8907 WindowState w = mDestroySurface.get(i);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008908 pw.print(" Destroy #"); pw.print(i); pw.print(' ');
8909 pw.print(w); pw.println(":");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008910 w.dump(pw, " ");
8911 }
8912 }
8913 if (mLosingFocus.size() > 0) {
8914 pw.println(" ");
8915 pw.println(" Windows losing focus:");
8916 for (int i=mLosingFocus.size()-1; i>=0; i--) {
8917 WindowState w = mLosingFocus.get(i);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008918 pw.print(" Losing #"); pw.print(i); pw.print(' ');
8919 pw.print(w); pw.println(":");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008920 w.dump(pw, " ");
8921 }
8922 }
8923 if (mSessions.size() > 0) {
8924 pw.println(" ");
8925 pw.println(" All active sessions:");
8926 Iterator<Session> it = mSessions.iterator();
8927 while (it.hasNext()) {
8928 Session s = it.next();
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008929 pw.print(" Session "); pw.print(s); pw.println(':');
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008930 s.dump(pw, " ");
8931 }
8932 }
8933 if (mTokenMap.size() > 0) {
8934 pw.println(" ");
8935 pw.println(" All tokens:");
8936 Iterator<WindowToken> it = mTokenMap.values().iterator();
8937 while (it.hasNext()) {
8938 WindowToken token = it.next();
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008939 pw.print(" Token "); pw.print(token.token); pw.println(':');
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008940 token.dump(pw, " ");
8941 }
8942 }
8943 if (mTokenList.size() > 0) {
8944 pw.println(" ");
8945 pw.println(" Window token list:");
8946 for (int i=0; i<mTokenList.size(); i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008947 pw.print(" #"); pw.print(i); pw.print(": ");
8948 pw.println(mTokenList.get(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008949 }
8950 }
8951 if (mAppTokens.size() > 0) {
8952 pw.println(" ");
8953 pw.println(" Application tokens in Z order:");
8954 for (int i=mAppTokens.size()-1; i>=0; i--) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008955 pw.print(" App #"); pw.print(i); pw.print(": ");
8956 pw.println(mAppTokens.get(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008957 }
8958 }
8959 if (mFinishedStarting.size() > 0) {
8960 pw.println(" ");
8961 pw.println(" Finishing start of application tokens:");
8962 for (int i=mFinishedStarting.size()-1; i>=0; i--) {
8963 WindowToken token = mFinishedStarting.get(i);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008964 pw.print(" Finished Starting #"); pw.print(i);
8965 pw.print(' '); pw.print(token); pw.println(':');
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008966 token.dump(pw, " ");
8967 }
8968 }
8969 if (mExitingTokens.size() > 0) {
8970 pw.println(" ");
8971 pw.println(" Exiting tokens:");
8972 for (int i=mExitingTokens.size()-1; i>=0; i--) {
8973 WindowToken token = mExitingTokens.get(i);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008974 pw.print(" Exiting #"); pw.print(i);
8975 pw.print(' '); pw.print(token); pw.println(':');
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008976 token.dump(pw, " ");
8977 }
8978 }
8979 if (mExitingAppTokens.size() > 0) {
8980 pw.println(" ");
8981 pw.println(" Exiting application tokens:");
8982 for (int i=mExitingAppTokens.size()-1; i>=0; i--) {
8983 WindowToken token = mExitingAppTokens.get(i);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008984 pw.print(" Exiting App #"); pw.print(i);
8985 pw.print(' '); pw.print(token); pw.println(':');
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008986 token.dump(pw, " ");
8987 }
8988 }
8989 pw.println(" ");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008990 pw.print(" mCurrentFocus="); pw.println(mCurrentFocus);
8991 pw.print(" mLastFocus="); pw.println(mLastFocus);
8992 pw.print(" mFocusedApp="); pw.println(mFocusedApp);
8993 pw.print(" mInputMethodTarget="); pw.println(mInputMethodTarget);
8994 pw.print(" mInputMethodWindow="); pw.println(mInputMethodWindow);
8995 pw.print(" mInTouchMode="); pw.println(mInTouchMode);
8996 pw.print(" mSystemBooted="); pw.print(mSystemBooted);
8997 pw.print(" mDisplayEnabled="); pw.println(mDisplayEnabled);
8998 pw.print(" mLayoutNeeded="); pw.print(mLayoutNeeded);
8999 pw.print(" mBlurShown="); pw.println(mBlurShown);
9000 pw.print(" mDimShown="); pw.print(mDimShown);
9001 pw.print(" current="); pw.print(mDimCurrentAlpha);
9002 pw.print(" target="); pw.print(mDimTargetAlpha);
9003 pw.print(" delta="); pw.print(mDimDeltaPerMs);
9004 pw.print(" lastAnimTime="); pw.println(mLastDimAnimTime);
9005 pw.print(" mInputMethodAnimLayerAdjustment=");
9006 pw.println(mInputMethodAnimLayerAdjustment);
9007 pw.print(" mDisplayFrozen="); pw.print(mDisplayFrozen);
9008 pw.print(" mWindowsFreezingScreen="); pw.print(mWindowsFreezingScreen);
9009 pw.print(" mAppsFreezingScreen="); pw.println(mAppsFreezingScreen);
9010 pw.print(" mRotation="); pw.print(mRotation);
9011 pw.print(", mForcedAppOrientation="); pw.print(mForcedAppOrientation);
9012 pw.print(", mRequestedRotation="); pw.println(mRequestedRotation);
9013 pw.print(" mAnimationPending="); pw.print(mAnimationPending);
9014 pw.print(" mWindowAnimationScale="); pw.print(mWindowAnimationScale);
9015 pw.print(" mTransitionWindowAnimationScale="); pw.println(mTransitionAnimationScale);
9016 pw.print(" mNextAppTransition=0x");
9017 pw.print(Integer.toHexString(mNextAppTransition));
9018 pw.print(", mAppTransitionReady="); pw.print(mAppTransitionReady);
9019 pw.print(", mAppTransitionTimeout="); pw.println( mAppTransitionTimeout);
9020 pw.print(" mStartingIconInTransition="); pw.print(mStartingIconInTransition);
9021 pw.print(", mSkipAppTransitionAnimation="); pw.println(mSkipAppTransitionAnimation);
9022 if (mOpeningApps.size() > 0) {
9023 pw.print(" mOpeningApps="); pw.println(mOpeningApps);
9024 }
9025 if (mClosingApps.size() > 0) {
9026 pw.print(" mClosingApps="); pw.println(mClosingApps);
9027 }
9028 pw.print(" DisplayWidth="); pw.print(mDisplay.getWidth());
9029 pw.print(" DisplayHeight="); pw.println(mDisplay.getHeight());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009030 pw.println(" KeyWaiter state:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009031 pw.print(" mLastWin="); pw.print(mKeyWaiter.mLastWin);
9032 pw.print(" mLastBinder="); pw.println(mKeyWaiter.mLastBinder);
9033 pw.print(" mFinished="); pw.print(mKeyWaiter.mFinished);
9034 pw.print(" mGotFirstWindow="); pw.print(mKeyWaiter.mGotFirstWindow);
9035 pw.print(" mEventDispatching="); pw.print(mKeyWaiter.mEventDispatching);
9036 pw.print(" mTimeToSwitch="); pw.println(mKeyWaiter.mTimeToSwitch);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009037 }
9038 }
9039
9040 public void monitor() {
9041 synchronized (mWindowMap) { }
9042 synchronized (mKeyguardDisabled) { }
9043 synchronized (mKeyWaiter) { }
9044 }
9045}