blob: 1a0d00bb5341d73598e5f9dd7ccbe93754d9ea1d [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
3724 if (eventType == LONG_TOUCH_EVENT || eventType == CHEEK_EVENT) {
3725 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 Chane96440f2009-05-06 10:27:36 -07005197 mPowerManager.userActivity(curTime, false, eventType, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005198 switch (ev.classType) {
5199 case RawInputEvent.CLASS_KEYBOARD:
5200 KeyEvent ke = (KeyEvent)ev.event;
5201 if (ke.isDown()) {
5202 lastKey = ke;
5203 keyRepeatCount = 0;
5204 lastKeyTime = curTime;
5205 nextKeyTime = lastKeyTime
5206 + KEY_REPEAT_FIRST_DELAY;
5207 if (DEBUG_INPUT) Log.v(
5208 TAG, "Received key down: first repeat @ "
5209 + nextKeyTime);
5210 } else {
5211 lastKey = null;
5212 // Arbitrary long timeout.
5213 lastKeyTime = curTime;
5214 nextKeyTime = curTime + LONG_WAIT;
5215 if (DEBUG_INPUT) Log.v(
5216 TAG, "Received key up: ignore repeat @ "
5217 + nextKeyTime);
5218 }
5219 dispatchKey((KeyEvent)ev.event, 0, 0);
5220 mQueue.recycleEvent(ev);
5221 break;
5222 case RawInputEvent.CLASS_TOUCHSCREEN:
5223 //Log.i(TAG, "Read next event " + ev);
5224 dispatchPointer(ev, (MotionEvent)ev.event, 0, 0);
5225 break;
5226 case RawInputEvent.CLASS_TRACKBALL:
5227 dispatchTrackball(ev, (MotionEvent)ev.event, 0, 0);
5228 break;
5229 case RawInputEvent.CLASS_CONFIGURATION_CHANGED:
5230 configChanged = true;
5231 break;
5232 default:
5233 mQueue.recycleEvent(ev);
5234 break;
5235 }
5236
5237 } else if (configChanged) {
5238 configChanged = false;
5239 sendNewConfiguration();
5240
5241 } else if (lastKey != null) {
5242 curTime = SystemClock.uptimeMillis();
5243
5244 // Timeout occurred while key was down. If it is at or
5245 // past the key repeat time, dispatch the repeat.
5246 if (DEBUG_INPUT) Log.v(
5247 TAG, "Key timeout: repeat=" + nextKeyTime
5248 + ", now=" + curTime);
5249 if (curTime < nextKeyTime) {
5250 continue;
5251 }
5252
5253 lastKeyTime = nextKeyTime;
5254 nextKeyTime = nextKeyTime + KEY_REPEAT_DELAY;
5255 keyRepeatCount++;
5256 if (DEBUG_INPUT) Log.v(
5257 TAG, "Key repeat: count=" + keyRepeatCount
5258 + ", next @ " + nextKeyTime);
The Android Open Source Project10592532009-03-18 17:39:46 -07005259 dispatchKey(KeyEvent.changeTimeRepeat(lastKey, curTime, keyRepeatCount), 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005260
5261 } else {
5262 curTime = SystemClock.uptimeMillis();
5263
5264 lastKeyTime = curTime;
5265 nextKeyTime = curTime + LONG_WAIT;
5266 }
5267
5268 } catch (Exception e) {
5269 Log.e(TAG,
5270 "Input thread received uncaught exception: " + e, e);
5271 }
5272 }
5273 }
5274 }
5275
5276 // -------------------------------------------------------------
5277 // Client Session State
5278 // -------------------------------------------------------------
5279
5280 private final class Session extends IWindowSession.Stub
5281 implements IBinder.DeathRecipient {
5282 final IInputMethodClient mClient;
5283 final IInputContext mInputContext;
5284 final int mUid;
5285 final int mPid;
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005286 final String mStringName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005287 SurfaceSession mSurfaceSession;
5288 int mNumWindow = 0;
5289 boolean mClientDead = false;
5290
5291 /**
5292 * Current pointer move event being dispatched to client window... must
5293 * hold key lock to access.
5294 */
5295 QueuedEvent mPendingPointerMove;
5296 WindowState mPendingPointerWindow;
5297
5298 /**
5299 * Current trackball move event being dispatched to client window... must
5300 * hold key lock to access.
5301 */
5302 QueuedEvent mPendingTrackballMove;
5303 WindowState mPendingTrackballWindow;
5304
5305 public Session(IInputMethodClient client, IInputContext inputContext) {
5306 mClient = client;
5307 mInputContext = inputContext;
5308 mUid = Binder.getCallingUid();
5309 mPid = Binder.getCallingPid();
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005310 StringBuilder sb = new StringBuilder();
5311 sb.append("Session{");
5312 sb.append(Integer.toHexString(System.identityHashCode(this)));
5313 sb.append(" uid ");
5314 sb.append(mUid);
5315 sb.append("}");
5316 mStringName = sb.toString();
5317
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005318 synchronized (mWindowMap) {
5319 if (mInputMethodManager == null && mHaveInputMethods) {
5320 IBinder b = ServiceManager.getService(
5321 Context.INPUT_METHOD_SERVICE);
5322 mInputMethodManager = IInputMethodManager.Stub.asInterface(b);
5323 }
5324 }
5325 long ident = Binder.clearCallingIdentity();
5326 try {
5327 // Note: it is safe to call in to the input method manager
5328 // here because we are not holding our lock.
5329 if (mInputMethodManager != null) {
5330 mInputMethodManager.addClient(client, inputContext,
5331 mUid, mPid);
5332 } else {
5333 client.setUsingInputMethod(false);
5334 }
5335 client.asBinder().linkToDeath(this, 0);
5336 } catch (RemoteException e) {
5337 // The caller has died, so we can just forget about this.
5338 try {
5339 if (mInputMethodManager != null) {
5340 mInputMethodManager.removeClient(client);
5341 }
5342 } catch (RemoteException ee) {
5343 }
5344 } finally {
5345 Binder.restoreCallingIdentity(ident);
5346 }
5347 }
5348
5349 @Override
5350 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
5351 throws RemoteException {
5352 try {
5353 return super.onTransact(code, data, reply, flags);
5354 } catch (RuntimeException e) {
5355 // Log all 'real' exceptions thrown to the caller
5356 if (!(e instanceof SecurityException)) {
5357 Log.e(TAG, "Window Session Crash", e);
5358 }
5359 throw e;
5360 }
5361 }
5362
5363 public void binderDied() {
5364 // Note: it is safe to call in to the input method manager
5365 // here because we are not holding our lock.
5366 try {
5367 if (mInputMethodManager != null) {
5368 mInputMethodManager.removeClient(mClient);
5369 }
5370 } catch (RemoteException e) {
5371 }
5372 synchronized(mWindowMap) {
5373 mClientDead = true;
5374 killSessionLocked();
5375 }
5376 }
5377
5378 public int add(IWindow window, WindowManager.LayoutParams attrs,
5379 int viewVisibility, Rect outContentInsets) {
5380 return addWindow(this, window, attrs, viewVisibility, outContentInsets);
5381 }
5382
5383 public void remove(IWindow window) {
5384 removeWindow(this, window);
5385 }
5386
5387 public int relayout(IWindow window, WindowManager.LayoutParams attrs,
5388 int requestedWidth, int requestedHeight, int viewFlags,
5389 boolean insetsPending, Rect outFrame, Rect outContentInsets,
5390 Rect outVisibleInsets, Surface outSurface) {
5391 return relayoutWindow(this, window, attrs,
5392 requestedWidth, requestedHeight, viewFlags, insetsPending,
5393 outFrame, outContentInsets, outVisibleInsets, outSurface);
5394 }
5395
5396 public void setTransparentRegion(IWindow window, Region region) {
5397 setTransparentRegionWindow(this, window, region);
5398 }
5399
5400 public void setInsets(IWindow window, int touchableInsets,
5401 Rect contentInsets, Rect visibleInsets) {
5402 setInsetsWindow(this, window, touchableInsets, contentInsets,
5403 visibleInsets);
5404 }
5405
5406 public void getDisplayFrame(IWindow window, Rect outDisplayFrame) {
5407 getWindowDisplayFrame(this, window, outDisplayFrame);
5408 }
5409
5410 public void finishDrawing(IWindow window) {
5411 if (localLOGV) Log.v(
5412 TAG, "IWindow finishDrawing called for " + window);
5413 finishDrawingWindow(this, window);
5414 }
5415
5416 public void finishKey(IWindow window) {
5417 if (localLOGV) Log.v(
5418 TAG, "IWindow finishKey called for " + window);
5419 mKeyWaiter.finishedKey(this, window, false,
5420 KeyWaiter.RETURN_NOTHING);
5421 }
5422
5423 public MotionEvent getPendingPointerMove(IWindow window) {
5424 if (localLOGV) Log.v(
5425 TAG, "IWindow getPendingMotionEvent called for " + window);
5426 return mKeyWaiter.finishedKey(this, window, false,
5427 KeyWaiter.RETURN_PENDING_POINTER);
5428 }
5429
5430 public MotionEvent getPendingTrackballMove(IWindow window) {
5431 if (localLOGV) Log.v(
5432 TAG, "IWindow getPendingMotionEvent called for " + window);
5433 return mKeyWaiter.finishedKey(this, window, false,
5434 KeyWaiter.RETURN_PENDING_TRACKBALL);
5435 }
5436
5437 public void setInTouchMode(boolean mode) {
5438 synchronized(mWindowMap) {
5439 mInTouchMode = mode;
5440 }
5441 }
5442
5443 public boolean getInTouchMode() {
5444 synchronized(mWindowMap) {
5445 return mInTouchMode;
5446 }
5447 }
5448
5449 public boolean performHapticFeedback(IWindow window, int effectId,
5450 boolean always) {
5451 synchronized(mWindowMap) {
5452 long ident = Binder.clearCallingIdentity();
5453 try {
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07005454 return mPolicy.performHapticFeedbackLw(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005455 windowForClientLocked(this, window), effectId, always);
5456 } finally {
5457 Binder.restoreCallingIdentity(ident);
5458 }
5459 }
5460 }
5461
5462 void windowAddedLocked() {
5463 if (mSurfaceSession == null) {
5464 if (localLOGV) Log.v(
5465 TAG, "First window added to " + this + ", creating SurfaceSession");
5466 mSurfaceSession = new SurfaceSession();
5467 mSessions.add(this);
5468 }
5469 mNumWindow++;
5470 }
5471
5472 void windowRemovedLocked() {
5473 mNumWindow--;
5474 killSessionLocked();
5475 }
5476
5477 void killSessionLocked() {
5478 if (mNumWindow <= 0 && mClientDead) {
5479 mSessions.remove(this);
5480 if (mSurfaceSession != null) {
5481 if (localLOGV) Log.v(
5482 TAG, "Last window removed from " + this
5483 + ", destroying " + mSurfaceSession);
5484 try {
5485 mSurfaceSession.kill();
5486 } catch (Exception e) {
5487 Log.w(TAG, "Exception thrown when killing surface session "
5488 + mSurfaceSession + " in session " + this
5489 + ": " + e.toString());
5490 }
5491 mSurfaceSession = null;
5492 }
5493 }
5494 }
5495
5496 void dump(PrintWriter pw, String prefix) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005497 pw.print(prefix); pw.print("mNumWindow="); pw.print(mNumWindow);
5498 pw.print(" mClientDead="); pw.print(mClientDead);
5499 pw.print(" mSurfaceSession="); pw.println(mSurfaceSession);
5500 if (mPendingPointerWindow != null || mPendingPointerMove != null) {
5501 pw.print(prefix);
5502 pw.print("mPendingPointerWindow="); pw.print(mPendingPointerWindow);
5503 pw.print(" mPendingPointerMove="); pw.println(mPendingPointerMove);
5504 }
5505 if (mPendingTrackballWindow != null || mPendingTrackballMove != null) {
5506 pw.print(prefix);
5507 pw.print("mPendingTrackballWindow="); pw.print(mPendingTrackballWindow);
5508 pw.print(" mPendingTrackballMove="); pw.println(mPendingTrackballMove);
5509 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005510 }
5511
5512 @Override
5513 public String toString() {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005514 return mStringName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005515 }
5516 }
5517
5518 // -------------------------------------------------------------
5519 // Client Window State
5520 // -------------------------------------------------------------
5521
5522 private final class WindowState implements WindowManagerPolicy.WindowState {
5523 final Session mSession;
5524 final IWindow mClient;
5525 WindowToken mToken;
The Android Open Source Project10592532009-03-18 17:39:46 -07005526 WindowToken mRootToken;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005527 AppWindowToken mAppToken;
5528 AppWindowToken mTargetAppToken;
5529 final WindowManager.LayoutParams mAttrs = new WindowManager.LayoutParams();
5530 final DeathRecipient mDeathRecipient;
5531 final WindowState mAttachedWindow;
5532 final ArrayList mChildWindows = new ArrayList();
5533 final int mBaseLayer;
5534 final int mSubLayer;
5535 final boolean mLayoutAttached;
5536 final boolean mIsImWindow;
5537 int mViewVisibility;
5538 boolean mPolicyVisibility = true;
5539 boolean mPolicyVisibilityAfterAnim = true;
5540 boolean mAppFreezing;
5541 Surface mSurface;
5542 boolean mAttachedHidden; // is our parent window hidden?
5543 boolean mLastHidden; // was this window last hidden?
5544 int mRequestedWidth;
5545 int mRequestedHeight;
5546 int mLastRequestedWidth;
5547 int mLastRequestedHeight;
5548 int mReqXPos;
5549 int mReqYPos;
5550 int mLayer;
5551 int mAnimLayer;
5552 int mLastLayer;
5553 boolean mHaveFrame;
5554
5555 WindowState mNextOutsideTouch;
5556
5557 // Actual frame shown on-screen (may be modified by animation)
5558 final Rect mShownFrame = new Rect();
5559 final Rect mLastShownFrame = new Rect();
5560
5561 /**
5562 * Insets that determine the actually visible area
5563 */
5564 final Rect mVisibleInsets = new Rect();
5565 final Rect mLastVisibleInsets = new Rect();
5566 boolean mVisibleInsetsChanged;
5567
5568 /**
5569 * Insets that are covered by system windows
5570 */
5571 final Rect mContentInsets = new Rect();
5572 final Rect mLastContentInsets = new Rect();
5573 boolean mContentInsetsChanged;
5574
5575 /**
5576 * Set to true if we are waiting for this window to receive its
5577 * given internal insets before laying out other windows based on it.
5578 */
5579 boolean mGivenInsetsPending;
5580
5581 /**
5582 * These are the content insets that were given during layout for
5583 * this window, to be applied to windows behind it.
5584 */
5585 final Rect mGivenContentInsets = new Rect();
5586
5587 /**
5588 * These are the visible insets that were given during layout for
5589 * this window, to be applied to windows behind it.
5590 */
5591 final Rect mGivenVisibleInsets = new Rect();
5592
5593 /**
5594 * Flag indicating whether the touchable region should be adjusted by
5595 * the visible insets; if false the area outside the visible insets is
5596 * NOT touchable, so we must use those to adjust the frame during hit
5597 * tests.
5598 */
5599 int mTouchableInsets = ViewTreeObserver.InternalInsetsInfo.TOUCHABLE_INSETS_FRAME;
5600
5601 // Current transformation being applied.
5602 float mDsDx=1, mDtDx=0, mDsDy=0, mDtDy=1;
5603 float mLastDsDx=1, mLastDtDx=0, mLastDsDy=0, mLastDtDy=1;
5604 float mHScale=1, mVScale=1;
5605 float mLastHScale=1, mLastVScale=1;
5606 final Matrix mTmpMatrix = new Matrix();
5607
5608 // "Real" frame that the application sees.
5609 final Rect mFrame = new Rect();
5610 final Rect mLastFrame = new Rect();
5611
5612 final Rect mContainingFrame = new Rect();
5613 final Rect mDisplayFrame = new Rect();
5614 final Rect mContentFrame = new Rect();
5615 final Rect mVisibleFrame = new Rect();
5616
5617 float mShownAlpha = 1;
5618 float mAlpha = 1;
5619 float mLastAlpha = 1;
5620
5621 // Set to true if, when the window gets displayed, it should perform
5622 // an enter animation.
5623 boolean mEnterAnimationPending;
5624
5625 // Currently running animation.
5626 boolean mAnimating;
5627 boolean mLocalAnimating;
5628 Animation mAnimation;
5629 boolean mAnimationIsEntrance;
5630 boolean mHasTransformation;
5631 boolean mHasLocalTransformation;
5632 final Transformation mTransformation = new Transformation();
5633
5634 // This is set after IWindowSession.relayout() has been called at
5635 // least once for the window. It allows us to detect the situation
5636 // where we don't yet have a surface, but should have one soon, so
5637 // we can give the window focus before waiting for the relayout.
5638 boolean mRelayoutCalled;
5639
5640 // This is set after the Surface has been created but before the
5641 // window has been drawn. During this time the surface is hidden.
5642 boolean mDrawPending;
5643
5644 // This is set after the window has finished drawing for the first
5645 // time but before its surface is shown. The surface will be
5646 // displayed when the next layout is run.
5647 boolean mCommitDrawPending;
5648
5649 // This is set during the time after the window's drawing has been
5650 // committed, and before its surface is actually shown. It is used
5651 // to delay showing the surface until all windows in a token are ready
5652 // to be shown.
5653 boolean mReadyToShow;
5654
5655 // Set when the window has been shown in the screen the first time.
5656 boolean mHasDrawn;
5657
5658 // Currently running an exit animation?
5659 boolean mExiting;
5660
5661 // Currently on the mDestroySurface list?
5662 boolean mDestroying;
5663
5664 // Completely remove from window manager after exit animation?
5665 boolean mRemoveOnExit;
5666
5667 // Set when the orientation is changing and this window has not yet
5668 // been updated for the new orientation.
5669 boolean mOrientationChanging;
5670
5671 // Is this window now (or just being) removed?
5672 boolean mRemoved;
5673
5674 WindowState(Session s, IWindow c, WindowToken token,
5675 WindowState attachedWindow, WindowManager.LayoutParams a,
5676 int viewVisibility) {
5677 mSession = s;
5678 mClient = c;
5679 mToken = token;
5680 mAttrs.copyFrom(a);
5681 mViewVisibility = viewVisibility;
5682 DeathRecipient deathRecipient = new DeathRecipient();
5683 mAlpha = a.alpha;
5684 if (localLOGV) Log.v(
5685 TAG, "Window " + this + " client=" + c.asBinder()
5686 + " token=" + token + " (" + mAttrs.token + ")");
5687 try {
5688 c.asBinder().linkToDeath(deathRecipient, 0);
5689 } catch (RemoteException e) {
5690 mDeathRecipient = null;
5691 mAttachedWindow = null;
5692 mLayoutAttached = false;
5693 mIsImWindow = false;
5694 mBaseLayer = 0;
5695 mSubLayer = 0;
5696 return;
5697 }
5698 mDeathRecipient = deathRecipient;
5699
5700 if ((mAttrs.type >= FIRST_SUB_WINDOW &&
5701 mAttrs.type <= LAST_SUB_WINDOW)) {
5702 // The multiplier here is to reserve space for multiple
5703 // windows in the same type layer.
5704 mBaseLayer = mPolicy.windowTypeToLayerLw(
5705 attachedWindow.mAttrs.type) * TYPE_LAYER_MULTIPLIER
5706 + TYPE_LAYER_OFFSET;
5707 mSubLayer = mPolicy.subWindowTypeToLayerLw(a.type);
5708 mAttachedWindow = attachedWindow;
5709 mAttachedWindow.mChildWindows.add(this);
5710 mLayoutAttached = mAttrs.type !=
5711 WindowManager.LayoutParams.TYPE_APPLICATION_ATTACHED_DIALOG;
5712 mIsImWindow = attachedWindow.mAttrs.type == TYPE_INPUT_METHOD
5713 || attachedWindow.mAttrs.type == TYPE_INPUT_METHOD_DIALOG;
5714 } else {
5715 // The multiplier here is to reserve space for multiple
5716 // windows in the same type layer.
5717 mBaseLayer = mPolicy.windowTypeToLayerLw(a.type)
5718 * TYPE_LAYER_MULTIPLIER
5719 + TYPE_LAYER_OFFSET;
5720 mSubLayer = 0;
5721 mAttachedWindow = null;
5722 mLayoutAttached = false;
5723 mIsImWindow = mAttrs.type == TYPE_INPUT_METHOD
5724 || mAttrs.type == TYPE_INPUT_METHOD_DIALOG;
5725 }
5726
5727 WindowState appWin = this;
5728 while (appWin.mAttachedWindow != null) {
5729 appWin = mAttachedWindow;
5730 }
5731 WindowToken appToken = appWin.mToken;
5732 while (appToken.appWindowToken == null) {
5733 WindowToken parent = mTokenMap.get(appToken.token);
5734 if (parent == null || appToken == parent) {
5735 break;
5736 }
5737 appToken = parent;
5738 }
The Android Open Source Project10592532009-03-18 17:39:46 -07005739 mRootToken = appToken;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005740 mAppToken = appToken.appWindowToken;
5741
5742 mSurface = null;
5743 mRequestedWidth = 0;
5744 mRequestedHeight = 0;
5745 mLastRequestedWidth = 0;
5746 mLastRequestedHeight = 0;
5747 mReqXPos = 0;
5748 mReqYPos = 0;
5749 mLayer = 0;
5750 mAnimLayer = 0;
5751 mLastLayer = 0;
5752 }
5753
5754 void attach() {
5755 if (localLOGV) Log.v(
5756 TAG, "Attaching " + this + " token=" + mToken
5757 + ", list=" + mToken.windows);
5758 mSession.windowAddedLocked();
5759 }
5760
5761 public void computeFrameLw(Rect pf, Rect df, Rect cf, Rect vf) {
5762 mHaveFrame = true;
5763
5764 final int pw = pf.right-pf.left;
5765 final int ph = pf.bottom-pf.top;
5766
5767 int w,h;
5768 if ((mAttrs.flags & mAttrs.FLAG_SCALED) != 0) {
5769 w = mAttrs.width < 0 ? pw : mAttrs.width;
5770 h = mAttrs.height< 0 ? ph : mAttrs.height;
5771 } else {
5772 w = mAttrs.width == mAttrs.FILL_PARENT ? pw : mRequestedWidth;
5773 h = mAttrs.height== mAttrs.FILL_PARENT ? ph : mRequestedHeight;
5774 }
5775
5776 final Rect container = mContainingFrame;
5777 container.set(pf);
5778
5779 final Rect display = mDisplayFrame;
5780 display.set(df);
5781
5782 final Rect content = mContentFrame;
5783 content.set(cf);
5784
5785 final Rect visible = mVisibleFrame;
5786 visible.set(vf);
5787
5788 final Rect frame = mFrame;
5789
5790 //System.out.println("In: w=" + w + " h=" + h + " container=" +
5791 // container + " x=" + mAttrs.x + " y=" + mAttrs.y);
5792
5793 Gravity.apply(mAttrs.gravity, w, h, container,
5794 (int) (mAttrs.x + mAttrs.horizontalMargin * pw),
5795 (int) (mAttrs.y + mAttrs.verticalMargin * ph), frame);
5796
5797 //System.out.println("Out: " + mFrame);
5798
5799 // Now make sure the window fits in the overall display.
5800 Gravity.applyDisplay(mAttrs.gravity, df, frame);
5801
5802 // Make sure the content and visible frames are inside of the
5803 // final window frame.
5804 if (content.left < frame.left) content.left = frame.left;
5805 if (content.top < frame.top) content.top = frame.top;
5806 if (content.right > frame.right) content.right = frame.right;
5807 if (content.bottom > frame.bottom) content.bottom = frame.bottom;
5808 if (visible.left < frame.left) visible.left = frame.left;
5809 if (visible.top < frame.top) visible.top = frame.top;
5810 if (visible.right > frame.right) visible.right = frame.right;
5811 if (visible.bottom > frame.bottom) visible.bottom = frame.bottom;
5812
5813 final Rect contentInsets = mContentInsets;
5814 contentInsets.left = content.left-frame.left;
5815 contentInsets.top = content.top-frame.top;
5816 contentInsets.right = frame.right-content.right;
5817 contentInsets.bottom = frame.bottom-content.bottom;
5818
5819 final Rect visibleInsets = mVisibleInsets;
5820 visibleInsets.left = visible.left-frame.left;
5821 visibleInsets.top = visible.top-frame.top;
5822 visibleInsets.right = frame.right-visible.right;
5823 visibleInsets.bottom = frame.bottom-visible.bottom;
5824
5825 if (localLOGV) {
5826 //if ("com.google.android.youtube".equals(mAttrs.packageName)
5827 // && mAttrs.type == WindowManager.LayoutParams.TYPE_APPLICATION_PANEL) {
5828 Log.v(TAG, "Resolving (mRequestedWidth="
5829 + mRequestedWidth + ", mRequestedheight="
5830 + mRequestedHeight + ") to" + " (pw=" + pw + ", ph=" + ph
5831 + "): frame=" + mFrame.toShortString()
5832 + " ci=" + contentInsets.toShortString()
5833 + " vi=" + visibleInsets.toShortString());
5834 //}
5835 }
5836 }
5837
5838 public Rect getFrameLw() {
5839 return mFrame;
5840 }
5841
5842 public Rect getShownFrameLw() {
5843 return mShownFrame;
5844 }
5845
5846 public Rect getDisplayFrameLw() {
5847 return mDisplayFrame;
5848 }
5849
5850 public Rect getContentFrameLw() {
5851 return mContentFrame;
5852 }
5853
5854 public Rect getVisibleFrameLw() {
5855 return mVisibleFrame;
5856 }
5857
5858 public boolean getGivenInsetsPendingLw() {
5859 return mGivenInsetsPending;
5860 }
5861
5862 public Rect getGivenContentInsetsLw() {
5863 return mGivenContentInsets;
5864 }
5865
5866 public Rect getGivenVisibleInsetsLw() {
5867 return mGivenVisibleInsets;
5868 }
5869
5870 public WindowManager.LayoutParams getAttrs() {
5871 return mAttrs;
5872 }
5873
5874 public int getSurfaceLayer() {
5875 return mLayer;
5876 }
5877
5878 public IApplicationToken getAppToken() {
5879 return mAppToken != null ? mAppToken.appToken : null;
5880 }
5881
5882 public boolean hasAppShownWindows() {
5883 return mAppToken != null ? mAppToken.firstWindowDrawn : false;
5884 }
5885
5886 public boolean hasAppStartingIcon() {
5887 return mAppToken != null ? (mAppToken.startingData != null) : false;
5888 }
5889
5890 public WindowManagerPolicy.WindowState getAppStartingWindow() {
5891 return mAppToken != null ? mAppToken.startingWindow : null;
5892 }
5893
5894 public void setAnimation(Animation anim) {
5895 if (localLOGV) Log.v(
5896 TAG, "Setting animation in " + this + ": " + anim);
5897 mAnimating = false;
5898 mLocalAnimating = false;
5899 mAnimation = anim;
5900 mAnimation.restrictDuration(MAX_ANIMATION_DURATION);
5901 mAnimation.scaleCurrentDuration(mWindowAnimationScale);
5902 }
5903
5904 public void clearAnimation() {
5905 if (mAnimation != null) {
5906 mAnimating = true;
5907 mLocalAnimating = false;
5908 mAnimation = null;
5909 }
5910 }
5911
5912 Surface createSurfaceLocked() {
5913 if (mSurface == null) {
5914 mDrawPending = true;
5915 mCommitDrawPending = false;
5916 mReadyToShow = false;
5917 if (mAppToken != null) {
5918 mAppToken.allDrawn = false;
5919 }
5920
5921 int flags = 0;
5922 if (mAttrs.memoryType == MEMORY_TYPE_HARDWARE) {
5923 flags |= Surface.HARDWARE;
5924 } else if (mAttrs.memoryType == MEMORY_TYPE_GPU) {
5925 flags |= Surface.GPU;
5926 } else if (mAttrs.memoryType == MEMORY_TYPE_PUSH_BUFFERS) {
5927 flags |= Surface.PUSH_BUFFERS;
5928 }
5929
5930 if ((mAttrs.flags&WindowManager.LayoutParams.FLAG_SECURE) != 0) {
5931 flags |= Surface.SECURE;
5932 }
5933 if (DEBUG_VISIBILITY) Log.v(
5934 TAG, "Creating surface in session "
5935 + mSession.mSurfaceSession + " window " + this
5936 + " w=" + mFrame.width()
5937 + " h=" + mFrame.height() + " format="
5938 + mAttrs.format + " flags=" + flags);
5939
5940 int w = mFrame.width();
5941 int h = mFrame.height();
5942 if ((mAttrs.flags & LayoutParams.FLAG_SCALED) != 0) {
5943 // for a scaled surface, we always want the requested
5944 // size.
5945 w = mRequestedWidth;
5946 h = mRequestedHeight;
5947 }
5948
5949 try {
5950 mSurface = new Surface(
5951 mSession.mSurfaceSession, mSession.mPid,
5952 0, w, h, mAttrs.format, flags);
5953 } catch (Surface.OutOfResourcesException e) {
5954 Log.w(TAG, "OutOfResourcesException creating surface");
5955 reclaimSomeSurfaceMemoryLocked(this, "create");
5956 return null;
5957 } catch (Exception e) {
5958 Log.e(TAG, "Exception creating surface", e);
5959 return null;
5960 }
5961
5962 if (localLOGV) Log.v(
5963 TAG, "Got surface: " + mSurface
5964 + ", set left=" + mFrame.left + " top=" + mFrame.top
5965 + ", animLayer=" + mAnimLayer);
5966 if (SHOW_TRANSACTIONS) {
5967 Log.i(TAG, ">>> OPEN TRANSACTION");
5968 Log.i(TAG, " SURFACE " + mSurface + ": CREATE ("
5969 + mAttrs.getTitle() + ") pos=(" +
5970 mFrame.left + "," + mFrame.top + ") (" +
5971 mFrame.width() + "x" + mFrame.height() + "), layer=" +
5972 mAnimLayer + " HIDE");
5973 }
5974 Surface.openTransaction();
5975 try {
5976 try {
5977 mSurface.setPosition(mFrame.left, mFrame.top);
5978 mSurface.setLayer(mAnimLayer);
5979 mSurface.hide();
5980 if ((mAttrs.flags&WindowManager.LayoutParams.FLAG_DITHER) != 0) {
5981 mSurface.setFlags(Surface.SURFACE_DITHER,
5982 Surface.SURFACE_DITHER);
5983 }
5984 } catch (RuntimeException e) {
5985 Log.w(TAG, "Error creating surface in " + w, e);
5986 reclaimSomeSurfaceMemoryLocked(this, "create-init");
5987 }
5988 mLastHidden = true;
5989 } finally {
5990 if (SHOW_TRANSACTIONS) Log.i(TAG, "<<< CLOSE TRANSACTION");
5991 Surface.closeTransaction();
5992 }
5993 if (localLOGV) Log.v(
5994 TAG, "Created surface " + this);
5995 }
5996 return mSurface;
5997 }
5998
5999 void destroySurfaceLocked() {
6000 // Window is no longer on-screen, so can no longer receive
6001 // key events... if we were waiting for it to finish
6002 // handling a key event, the wait is over!
6003 mKeyWaiter.finishedKey(mSession, mClient, true,
6004 KeyWaiter.RETURN_NOTHING);
6005 mKeyWaiter.releasePendingPointerLocked(mSession);
6006 mKeyWaiter.releasePendingTrackballLocked(mSession);
6007
6008 if (mAppToken != null && this == mAppToken.startingWindow) {
6009 mAppToken.startingDisplayed = false;
6010 }
6011
6012 if (localLOGV) Log.v(
6013 TAG, "Window " + this
6014 + " destroying surface " + mSurface + ", session " + mSession);
6015 if (mSurface != null) {
6016 try {
6017 if (SHOW_TRANSACTIONS) {
6018 RuntimeException ex = new RuntimeException();
6019 ex.fillInStackTrace();
6020 Log.i(TAG, " SURFACE " + mSurface + ": DESTROY ("
6021 + mAttrs.getTitle() + ")", ex);
6022 }
6023 mSurface.clear();
6024 } catch (RuntimeException e) {
6025 Log.w(TAG, "Exception thrown when destroying Window " + this
6026 + " surface " + mSurface + " session " + mSession
6027 + ": " + e.toString());
6028 }
6029 mSurface = null;
6030 mDrawPending = false;
6031 mCommitDrawPending = false;
6032 mReadyToShow = false;
6033
6034 int i = mChildWindows.size();
6035 while (i > 0) {
6036 i--;
6037 WindowState c = (WindowState)mChildWindows.get(i);
6038 c.mAttachedHidden = true;
6039 }
6040 }
6041 }
6042
6043 boolean finishDrawingLocked() {
6044 if (mDrawPending) {
6045 if (SHOW_TRANSACTIONS || DEBUG_ORIENTATION) Log.v(
6046 TAG, "finishDrawingLocked: " + mSurface);
6047 mCommitDrawPending = true;
6048 mDrawPending = false;
6049 return true;
6050 }
6051 return false;
6052 }
6053
6054 // This must be called while inside a transaction.
6055 void commitFinishDrawingLocked(long currentTime) {
6056 //Log.i(TAG, "commitFinishDrawingLocked: " + mSurface);
6057 if (!mCommitDrawPending) {
6058 return;
6059 }
6060 mCommitDrawPending = false;
6061 mReadyToShow = true;
6062 final boolean starting = mAttrs.type == TYPE_APPLICATION_STARTING;
6063 final AppWindowToken atoken = mAppToken;
6064 if (atoken == null || atoken.allDrawn || starting) {
6065 performShowLocked();
6066 }
6067 }
6068
6069 // This must be called while inside a transaction.
6070 boolean performShowLocked() {
6071 if (DEBUG_VISIBILITY) {
6072 RuntimeException e = new RuntimeException();
6073 e.fillInStackTrace();
6074 Log.v(TAG, "performShow on " + this
6075 + ": readyToShow=" + mReadyToShow + " readyForDisplay=" + isReadyForDisplay()
6076 + " starting=" + (mAttrs.type == TYPE_APPLICATION_STARTING), e);
6077 }
6078 if (mReadyToShow && isReadyForDisplay()) {
6079 if (SHOW_TRANSACTIONS || DEBUG_ORIENTATION) Log.i(
6080 TAG, " SURFACE " + mSurface + ": SHOW (performShowLocked)");
6081 if (DEBUG_VISIBILITY) Log.v(TAG, "Showing " + this
6082 + " during animation: policyVis=" + mPolicyVisibility
6083 + " attHidden=" + mAttachedHidden
6084 + " tok.hiddenRequested="
6085 + (mAppToken != null ? mAppToken.hiddenRequested : false)
6086 + " tok.idden="
6087 + (mAppToken != null ? mAppToken.hidden : false)
6088 + " animating=" + mAnimating
6089 + " tok animating="
6090 + (mAppToken != null ? mAppToken.animating : false));
6091 if (!showSurfaceRobustlyLocked(this)) {
6092 return false;
6093 }
6094 mLastAlpha = -1;
6095 mHasDrawn = true;
6096 mLastHidden = false;
6097 mReadyToShow = false;
6098 enableScreenIfNeededLocked();
6099
6100 applyEnterAnimationLocked(this);
6101
6102 int i = mChildWindows.size();
6103 while (i > 0) {
6104 i--;
6105 WindowState c = (WindowState)mChildWindows.get(i);
6106 if (c.mSurface != null && c.mAttachedHidden) {
6107 c.mAttachedHidden = false;
6108 c.performShowLocked();
6109 }
6110 }
6111
6112 if (mAttrs.type != TYPE_APPLICATION_STARTING
6113 && mAppToken != null) {
6114 mAppToken.firstWindowDrawn = true;
6115 if (mAnimation == null && mAppToken.startingData != null) {
6116 if (DEBUG_STARTING_WINDOW) Log.v(TAG, "Finish starting "
6117 + mToken
6118 + ": first real window is shown, no animation");
6119 mFinishedStarting.add(mAppToken);
6120 mH.sendEmptyMessage(H.FINISHED_STARTING);
6121 }
6122 mAppToken.updateReportedVisibilityLocked();
6123 }
6124 }
6125 return true;
6126 }
6127
6128 // This must be called while inside a transaction. Returns true if
6129 // there is more animation to run.
6130 boolean stepAnimationLocked(long currentTime, int dw, int dh) {
6131 if (!mDisplayFrozen) {
6132 // We will run animations as long as the display isn't frozen.
6133
6134 if (!mDrawPending && !mCommitDrawPending && mAnimation != null) {
6135 mHasTransformation = true;
6136 mHasLocalTransformation = true;
6137 if (!mLocalAnimating) {
6138 if (DEBUG_ANIM) Log.v(
6139 TAG, "Starting animation in " + this +
6140 " @ " + currentTime + ": ww=" + mFrame.width() + " wh=" + mFrame.height() +
6141 " dw=" + dw + " dh=" + dh + " scale=" + mWindowAnimationScale);
6142 mAnimation.initialize(mFrame.width(), mFrame.height(), dw, dh);
6143 mAnimation.setStartTime(currentTime);
6144 mLocalAnimating = true;
6145 mAnimating = true;
6146 }
6147 mTransformation.clear();
6148 final boolean more = mAnimation.getTransformation(
6149 currentTime, mTransformation);
6150 if (DEBUG_ANIM) Log.v(
6151 TAG, "Stepped animation in " + this +
6152 ": more=" + more + ", xform=" + mTransformation);
6153 if (more) {
6154 // we're not done!
6155 return true;
6156 }
6157 if (DEBUG_ANIM) Log.v(
6158 TAG, "Finished animation in " + this +
6159 " @ " + currentTime);
6160 mAnimation = null;
6161 //WindowManagerService.this.dump();
6162 }
6163 mHasLocalTransformation = false;
6164 if ((!mLocalAnimating || mAnimationIsEntrance) && mAppToken != null
6165 && mAppToken.hasTransformation) {
6166 // When our app token is animating, we kind-of pretend like
6167 // we are as well. Note the mLocalAnimating mAnimationIsEntrance
6168 // part of this check means that we will only do this if
6169 // our window is not currently exiting, or it is not
6170 // locally animating itself. The idea being that one that
6171 // is exiting and doing a local animation should be removed
6172 // once that animation is done.
6173 mAnimating = true;
6174 mHasTransformation = true;
6175 mTransformation.clear();
6176 return false;
6177 } else if (mHasTransformation) {
6178 // Little trick to get through the path below to act like
6179 // we have finished an animation.
6180 mAnimating = true;
6181 } else if (isAnimating()) {
6182 mAnimating = true;
6183 }
6184 } else if (mAnimation != null) {
6185 // If the display is frozen, and there is a pending animation,
6186 // clear it and make sure we run the cleanup code.
6187 mAnimating = true;
6188 mLocalAnimating = true;
6189 mAnimation = null;
6190 }
6191
6192 if (!mAnimating && !mLocalAnimating) {
6193 return false;
6194 }
6195
6196 if (DEBUG_ANIM) Log.v(
6197 TAG, "Animation done in " + this + ": exiting=" + mExiting
6198 + ", reportedVisible="
6199 + (mAppToken != null ? mAppToken.reportedVisible : false));
6200
6201 mAnimating = false;
6202 mLocalAnimating = false;
6203 mAnimation = null;
6204 mAnimLayer = mLayer;
6205 if (mIsImWindow) {
6206 mAnimLayer += mInputMethodAnimLayerAdjustment;
6207 }
6208 if (DEBUG_LAYERS) Log.v(TAG, "Stepping win " + this
6209 + " anim layer: " + mAnimLayer);
6210 mHasTransformation = false;
6211 mHasLocalTransformation = false;
6212 mPolicyVisibility = mPolicyVisibilityAfterAnim;
6213 mTransformation.clear();
6214 if (mHasDrawn
6215 && mAttrs.type == WindowManager.LayoutParams.TYPE_APPLICATION_STARTING
6216 && mAppToken != null
6217 && mAppToken.firstWindowDrawn
6218 && mAppToken.startingData != null) {
6219 if (DEBUG_STARTING_WINDOW) Log.v(TAG, "Finish starting "
6220 + mToken + ": first real window done animating");
6221 mFinishedStarting.add(mAppToken);
6222 mH.sendEmptyMessage(H.FINISHED_STARTING);
6223 }
6224
6225 finishExit();
6226
6227 if (mAppToken != null) {
6228 mAppToken.updateReportedVisibilityLocked();
6229 }
6230
6231 return false;
6232 }
6233
6234 void finishExit() {
6235 if (DEBUG_ANIM) Log.v(
6236 TAG, "finishExit in " + this
6237 + ": exiting=" + mExiting
6238 + " remove=" + mRemoveOnExit
6239 + " windowAnimating=" + isWindowAnimating());
6240
6241 final int N = mChildWindows.size();
6242 for (int i=0; i<N; i++) {
6243 ((WindowState)mChildWindows.get(i)).finishExit();
6244 }
6245
6246 if (!mExiting) {
6247 return;
6248 }
6249
6250 if (isWindowAnimating()) {
6251 return;
6252 }
6253
6254 if (localLOGV) Log.v(
6255 TAG, "Exit animation finished in " + this
6256 + ": remove=" + mRemoveOnExit);
6257 if (mSurface != null) {
6258 mDestroySurface.add(this);
6259 mDestroying = true;
6260 if (SHOW_TRANSACTIONS) Log.i(
6261 TAG, " SURFACE " + mSurface + ": HIDE (finishExit)");
6262 try {
6263 mSurface.hide();
6264 } catch (RuntimeException e) {
6265 Log.w(TAG, "Error hiding surface in " + this, e);
6266 }
6267 mLastHidden = true;
6268 mKeyWaiter.releasePendingPointerLocked(mSession);
6269 }
6270 mExiting = false;
6271 if (mRemoveOnExit) {
6272 mPendingRemove.add(this);
6273 mRemoveOnExit = false;
6274 }
6275 }
6276
6277 boolean isIdentityMatrix(float dsdx, float dtdx, float dsdy, float dtdy) {
6278 if (dsdx < .99999f || dsdx > 1.00001f) return false;
6279 if (dtdy < .99999f || dtdy > 1.00001f) return false;
6280 if (dtdx < -.000001f || dtdx > .000001f) return false;
6281 if (dsdy < -.000001f || dsdy > .000001f) return false;
6282 return true;
6283 }
6284
6285 void computeShownFrameLocked() {
6286 final boolean selfTransformation = mHasLocalTransformation;
6287 Transformation attachedTransformation =
6288 (mAttachedWindow != null && mAttachedWindow.mHasLocalTransformation)
6289 ? mAttachedWindow.mTransformation : null;
6290 Transformation appTransformation =
6291 (mAppToken != null && mAppToken.hasTransformation)
6292 ? mAppToken.transformation : null;
6293 if (selfTransformation || attachedTransformation != null
6294 || appTransformation != null) {
6295 // cache often used attributes locally
6296 final Rect frame = mFrame;
6297 final float tmpFloats[] = mTmpFloats;
6298 final Matrix tmpMatrix = mTmpMatrix;
6299
6300 // Compute the desired transformation.
6301 tmpMatrix.setTranslate(frame.left, frame.top);
6302 if (selfTransformation) {
6303 tmpMatrix.preConcat(mTransformation.getMatrix());
6304 }
6305 if (attachedTransformation != null) {
6306 tmpMatrix.preConcat(attachedTransformation.getMatrix());
6307 }
6308 if (appTransformation != null) {
6309 tmpMatrix.preConcat(appTransformation.getMatrix());
6310 }
6311
6312 // "convert" it into SurfaceFlinger's format
6313 // (a 2x2 matrix + an offset)
6314 // Here we must not transform the position of the surface
6315 // since it is already included in the transformation.
6316 //Log.i(TAG, "Transform: " + matrix);
6317
6318 tmpMatrix.getValues(tmpFloats);
6319 mDsDx = tmpFloats[Matrix.MSCALE_X];
6320 mDtDx = tmpFloats[Matrix.MSKEW_X];
6321 mDsDy = tmpFloats[Matrix.MSKEW_Y];
6322 mDtDy = tmpFloats[Matrix.MSCALE_Y];
6323 int x = (int)tmpFloats[Matrix.MTRANS_X];
6324 int y = (int)tmpFloats[Matrix.MTRANS_Y];
6325 int w = frame.width();
6326 int h = frame.height();
6327 mShownFrame.set(x, y, x+w, y+h);
6328
6329 // Now set the alpha... but because our current hardware
6330 // can't do alpha transformation on a non-opaque surface,
6331 // turn it off if we are running an animation that is also
6332 // transforming since it is more important to have that
6333 // animation be smooth.
6334 mShownAlpha = mAlpha;
6335 if (!mLimitedAlphaCompositing
6336 || (!PixelFormat.formatHasAlpha(mAttrs.format)
6337 || (isIdentityMatrix(mDsDx, mDtDx, mDsDy, mDtDy)
6338 && x == frame.left && y == frame.top))) {
6339 //Log.i(TAG, "Applying alpha transform");
6340 if (selfTransformation) {
6341 mShownAlpha *= mTransformation.getAlpha();
6342 }
6343 if (attachedTransformation != null) {
6344 mShownAlpha *= attachedTransformation.getAlpha();
6345 }
6346 if (appTransformation != null) {
6347 mShownAlpha *= appTransformation.getAlpha();
6348 }
6349 } else {
6350 //Log.i(TAG, "Not applying alpha transform");
6351 }
6352
6353 if (localLOGV) Log.v(
6354 TAG, "Continuing animation in " + this +
6355 ": " + mShownFrame +
6356 ", alpha=" + mTransformation.getAlpha());
6357 return;
6358 }
6359
6360 mShownFrame.set(mFrame);
6361 mShownAlpha = mAlpha;
6362 mDsDx = 1;
6363 mDtDx = 0;
6364 mDsDy = 0;
6365 mDtDy = 1;
6366 }
6367
6368 /**
6369 * Is this window visible? It is not visible if there is no
6370 * surface, or we are in the process of running an exit animation
6371 * that will remove the surface, or its app token has been hidden.
6372 */
6373 public boolean isVisibleLw() {
6374 final AppWindowToken atoken = mAppToken;
6375 return mSurface != null && mPolicyVisibility && !mAttachedHidden
6376 && (atoken == null || !atoken.hiddenRequested)
6377 && !mExiting && !mDestroying;
6378 }
6379
6380 /**
6381 * Is this window visible, ignoring its app token? It is not visible
6382 * if there is no surface, or we are in the process of running an exit animation
6383 * that will remove the surface.
6384 */
6385 public boolean isWinVisibleLw() {
6386 final AppWindowToken atoken = mAppToken;
6387 return mSurface != null && mPolicyVisibility && !mAttachedHidden
6388 && (atoken == null || !atoken.hiddenRequested || atoken.animating)
6389 && !mExiting && !mDestroying;
6390 }
6391
6392 /**
6393 * The same as isVisible(), but follows the current hidden state of
6394 * the associated app token, not the pending requested hidden state.
6395 */
6396 boolean isVisibleNow() {
6397 return mSurface != null && mPolicyVisibility && !mAttachedHidden
The Android Open Source Project10592532009-03-18 17:39:46 -07006398 && !mRootToken.hidden && !mExiting && !mDestroying;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006399 }
6400
6401 /**
6402 * Same as isVisible(), but we also count it as visible between the
6403 * call to IWindowSession.add() and the first relayout().
6404 */
6405 boolean isVisibleOrAdding() {
6406 final AppWindowToken atoken = mAppToken;
6407 return (mSurface != null
6408 || (!mRelayoutCalled && mViewVisibility == View.VISIBLE))
6409 && mPolicyVisibility && !mAttachedHidden
6410 && (atoken == null || !atoken.hiddenRequested)
6411 && !mExiting && !mDestroying;
6412 }
6413
6414 /**
6415 * Is this window currently on-screen? It is on-screen either if it
6416 * is visible or it is currently running an animation before no longer
6417 * being visible.
6418 */
6419 boolean isOnScreen() {
6420 final AppWindowToken atoken = mAppToken;
6421 if (atoken != null) {
6422 return mSurface != null && mPolicyVisibility && !mDestroying
6423 && ((!mAttachedHidden && !atoken.hiddenRequested)
6424 || mAnimating || atoken.animating);
6425 } else {
6426 return mSurface != null && mPolicyVisibility && !mDestroying
6427 && (!mAttachedHidden || mAnimating);
6428 }
6429 }
6430
6431 /**
6432 * Like isOnScreen(), but we don't return true if the window is part
6433 * of a transition that has not yet been started.
6434 */
6435 boolean isReadyForDisplay() {
6436 final AppWindowToken atoken = mAppToken;
6437 final boolean animating = atoken != null ? atoken.animating : false;
6438 return mSurface != null && mPolicyVisibility && !mDestroying
The Android Open Source Project10592532009-03-18 17:39:46 -07006439 && ((!mAttachedHidden && !mRootToken.hidden)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006440 || mAnimating || animating);
6441 }
6442
6443 /** Is the window or its container currently animating? */
6444 boolean isAnimating() {
6445 final WindowState attached = mAttachedWindow;
6446 final AppWindowToken atoken = mAppToken;
6447 return mAnimation != null
6448 || (attached != null && attached.mAnimation != null)
6449 || (atoken != null &&
6450 (atoken.animation != null
6451 || atoken.inPendingTransaction));
6452 }
6453
6454 /** Is this window currently animating? */
6455 boolean isWindowAnimating() {
6456 return mAnimation != null;
6457 }
6458
6459 /**
6460 * Like isOnScreen, but returns false if the surface hasn't yet
6461 * been drawn.
6462 */
6463 public boolean isDisplayedLw() {
6464 final AppWindowToken atoken = mAppToken;
6465 return mSurface != null && mPolicyVisibility && !mDestroying
6466 && !mDrawPending && !mCommitDrawPending
6467 && ((!mAttachedHidden &&
6468 (atoken == null || !atoken.hiddenRequested))
6469 || mAnimating);
6470 }
6471
6472 public boolean fillsScreenLw(int screenWidth, int screenHeight,
6473 boolean shownFrame, boolean onlyOpaque) {
6474 if (mSurface == null) {
6475 return false;
6476 }
6477 if (mAppToken != null && !mAppToken.appFullscreen) {
6478 return false;
6479 }
6480 if (onlyOpaque && mAttrs.format != PixelFormat.OPAQUE) {
6481 return false;
6482 }
6483 final Rect frame = shownFrame ? mShownFrame : mFrame;
6484 if (frame.left <= 0 && frame.top <= 0
6485 && frame.right >= screenWidth
6486 && frame.bottom >= screenHeight) {
6487 return true;
6488 }
6489 return false;
6490 }
6491
6492 boolean isFullscreenOpaque(int screenWidth, int screenHeight) {
6493 if (mAttrs.format != PixelFormat.OPAQUE || mSurface == null
6494 || mAnimation != null || mDrawPending || mCommitDrawPending) {
6495 return false;
6496 }
6497 if (mFrame.left <= 0 && mFrame.top <= 0 &&
6498 mFrame.right >= screenWidth && mFrame.bottom >= screenHeight) {
6499 return true;
6500 }
6501 return false;
6502 }
6503
6504 void removeLocked() {
6505 if (mAttachedWindow != null) {
6506 mAttachedWindow.mChildWindows.remove(this);
6507 }
6508 destroySurfaceLocked();
6509 mSession.windowRemovedLocked();
6510 try {
6511 mClient.asBinder().unlinkToDeath(mDeathRecipient, 0);
6512 } catch (RuntimeException e) {
6513 // Ignore if it has already been removed (usually because
6514 // we are doing this as part of processing a death note.)
6515 }
6516 }
6517
6518 private class DeathRecipient implements IBinder.DeathRecipient {
6519 public void binderDied() {
6520 try {
6521 synchronized(mWindowMap) {
6522 WindowState win = windowForClientLocked(mSession, mClient);
6523 Log.i(TAG, "WIN DEATH: " + win);
6524 if (win != null) {
6525 removeWindowLocked(mSession, win);
6526 }
6527 }
6528 } catch (IllegalArgumentException ex) {
6529 // This will happen if the window has already been
6530 // removed.
6531 }
6532 }
6533 }
6534
6535 /** Returns true if this window desires key events. */
6536 public final boolean canReceiveKeys() {
6537 return isVisibleOrAdding()
6538 && (mViewVisibility == View.VISIBLE)
6539 && ((mAttrs.flags & WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE) == 0);
6540 }
6541
6542 public boolean hasDrawnLw() {
6543 return mHasDrawn;
6544 }
6545
6546 public boolean showLw(boolean doAnimation) {
6547 if (!mPolicyVisibility || !mPolicyVisibilityAfterAnim) {
6548 mPolicyVisibility = true;
6549 mPolicyVisibilityAfterAnim = true;
6550 if (doAnimation) {
6551 applyAnimationLocked(this, WindowManagerPolicy.TRANSIT_ENTER, true);
6552 }
6553 requestAnimationLocked(0);
6554 return true;
6555 }
6556 return false;
6557 }
6558
6559 public boolean hideLw(boolean doAnimation) {
6560 boolean current = doAnimation ? mPolicyVisibilityAfterAnim
6561 : mPolicyVisibility;
6562 if (current) {
6563 if (doAnimation) {
6564 applyAnimationLocked(this, WindowManagerPolicy.TRANSIT_EXIT, false);
6565 if (mAnimation == null) {
6566 doAnimation = false;
6567 }
6568 }
6569 if (doAnimation) {
6570 mPolicyVisibilityAfterAnim = false;
6571 } else {
6572 mPolicyVisibilityAfterAnim = false;
6573 mPolicyVisibility = false;
6574 }
6575 requestAnimationLocked(0);
6576 return true;
6577 }
6578 return false;
6579 }
6580
6581 void dump(PrintWriter pw, String prefix) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006582 StringBuilder sb = new StringBuilder(64);
6583
6584 pw.print(prefix); pw.print("mSession="); pw.print(mSession);
6585 pw.print(" mClient="); pw.println(mClient.asBinder());
6586 pw.print(prefix); pw.print("mAttrs="); pw.println(mAttrs);
6587 if (mAttachedWindow != null || mLayoutAttached) {
6588 pw.print(prefix); pw.print("mAttachedWindow="); pw.print(mAttachedWindow);
6589 pw.print(" mLayoutAttached="); pw.println(mLayoutAttached);
6590 }
6591 if (mIsImWindow) {
6592 pw.print(prefix); pw.print("mIsImWindow="); pw.println(mIsImWindow);
6593 }
6594 pw.print(prefix); pw.print("mBaseLayer="); pw.print(mBaseLayer);
6595 pw.print(" mSubLayer="); pw.print(mSubLayer);
6596 pw.print(" mAnimLayer="); pw.print(mLayer); pw.print("+");
6597 pw.print((mTargetAppToken != null ? mTargetAppToken.animLayerAdjustment
6598 : (mAppToken != null ? mAppToken.animLayerAdjustment : 0)));
6599 pw.print("="); pw.print(mAnimLayer);
6600 pw.print(" mLastLayer="); pw.println(mLastLayer);
6601 if (mSurface != null) {
6602 pw.print(prefix); pw.print("mSurface="); pw.println(mSurface);
6603 }
6604 pw.print(prefix); pw.print("mToken="); pw.println(mToken);
6605 pw.print(prefix); pw.print("mRootToken="); pw.println(mRootToken);
6606 if (mAppToken != null) {
6607 pw.print(prefix); pw.print("mAppToken="); pw.println(mAppToken);
6608 }
6609 if (mTargetAppToken != null) {
6610 pw.print(prefix); pw.print("mTargetAppToken="); pw.println(mTargetAppToken);
6611 }
6612 pw.print(prefix); pw.print("mViewVisibility=0x");
6613 pw.print(Integer.toHexString(mViewVisibility));
6614 pw.print(" mLastHidden="); pw.print(mLastHidden);
6615 pw.print(" mHaveFrame="); pw.println(mHaveFrame);
6616 if (!mPolicyVisibility || !mPolicyVisibilityAfterAnim || mAttachedHidden) {
6617 pw.print(prefix); pw.print("mPolicyVisibility=");
6618 pw.print(mPolicyVisibility);
6619 pw.print(" mPolicyVisibilityAfterAnim=");
6620 pw.print(mPolicyVisibilityAfterAnim);
6621 pw.print(" mAttachedHidden="); pw.println(mAttachedHidden);
6622 }
6623 pw.print(prefix); pw.print("Requested w="); pw.print(mRequestedWidth);
6624 pw.print(" h="); pw.print(mRequestedHeight);
6625 pw.print(" x="); pw.print(mReqXPos);
6626 pw.print(" y="); pw.println(mReqYPos);
6627 pw.print(prefix); pw.print("mGivenContentInsets=");
6628 mGivenContentInsets.printShortString(pw);
6629 pw.print(" mGivenVisibleInsets=");
6630 mGivenVisibleInsets.printShortString(pw);
6631 pw.println();
6632 if (mTouchableInsets != 0 || mGivenInsetsPending) {
6633 pw.print(prefix); pw.print("mTouchableInsets="); pw.print(mTouchableInsets);
6634 pw.print(" mGivenInsetsPending="); pw.println(mGivenInsetsPending);
6635 }
6636 pw.print(prefix); pw.print("mShownFrame=");
6637 mShownFrame.printShortString(pw);
6638 pw.print(" last="); mLastShownFrame.printShortString(pw);
6639 pw.println();
6640 pw.print(prefix); pw.print("mFrame="); mFrame.printShortString(pw);
6641 pw.print(" last="); mLastFrame.printShortString(pw);
6642 pw.println();
6643 pw.print(prefix); pw.print("mContainingFrame=");
6644 mContainingFrame.printShortString(pw);
6645 pw.print(" mDisplayFrame=");
6646 mDisplayFrame.printShortString(pw);
6647 pw.println();
6648 pw.print(prefix); pw.print("mContentFrame="); mContentFrame.printShortString(pw);
6649 pw.print(" mVisibleFrame="); mVisibleFrame.printShortString(pw);
6650 pw.println();
6651 pw.print(prefix); pw.print("mContentInsets="); mContentInsets.printShortString(pw);
6652 pw.print(" last="); mLastContentInsets.printShortString(pw);
6653 pw.print(" mVisibleInsets="); mVisibleInsets.printShortString(pw);
6654 pw.print(" last="); mLastVisibleInsets.printShortString(pw);
6655 pw.println();
6656 if (mShownAlpha != 1 || mAlpha != 1 || mLastAlpha != 1) {
6657 pw.print(prefix); pw.print("mShownAlpha="); pw.print(mShownAlpha);
6658 pw.print(" mAlpha="); pw.print(mAlpha);
6659 pw.print(" mLastAlpha="); pw.println(mLastAlpha);
6660 }
6661 if (mAnimating || mLocalAnimating || mAnimationIsEntrance
6662 || mAnimation != null) {
6663 pw.print(prefix); pw.print("mAnimating="); pw.print(mAnimating);
6664 pw.print(" mLocalAnimating="); pw.print(mLocalAnimating);
6665 pw.print(" mAnimationIsEntrance="); pw.print(mAnimationIsEntrance);
6666 pw.print(" mAnimation="); pw.println(mAnimation);
6667 }
6668 if (mHasTransformation || mHasLocalTransformation) {
6669 pw.print(prefix); pw.print("XForm: has=");
6670 pw.print(mHasTransformation);
6671 pw.print(" hasLocal="); pw.print(mHasLocalTransformation);
6672 pw.print(" "); mTransformation.printShortString(pw);
6673 pw.println();
6674 }
6675 pw.print(prefix); pw.print("mDrawPending="); pw.print(mDrawPending);
6676 pw.print(" mCommitDrawPending="); pw.print(mCommitDrawPending);
6677 pw.print(" mReadyToShow="); pw.print(mReadyToShow);
6678 pw.print(" mHasDrawn="); pw.println(mHasDrawn);
6679 if (mExiting || mRemoveOnExit || mDestroying || mRemoved) {
6680 pw.print(prefix); pw.print("mExiting="); pw.print(mExiting);
6681 pw.print(" mRemoveOnExit="); pw.print(mRemoveOnExit);
6682 pw.print(" mDestroying="); pw.print(mDestroying);
6683 pw.print(" mRemoved="); pw.println(mRemoved);
6684 }
6685 if (mOrientationChanging || mAppFreezing) {
6686 pw.print(prefix); pw.print("mOrientationChanging=");
6687 pw.print(mOrientationChanging);
6688 pw.print(" mAppFreezing="); pw.println(mAppFreezing);
6689 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006690 }
6691
6692 @Override
6693 public String toString() {
6694 return "Window{"
6695 + Integer.toHexString(System.identityHashCode(this))
6696 + " " + mAttrs.getTitle() + " paused=" + mToken.paused + "}";
6697 }
6698 }
6699
6700 // -------------------------------------------------------------
6701 // Window Token State
6702 // -------------------------------------------------------------
6703
6704 class WindowToken {
6705 // The actual token.
6706 final IBinder token;
6707
6708 // The type of window this token is for, as per WindowManager.LayoutParams.
6709 final int windowType;
6710
6711 // Set if this token was explicitly added by a client, so should
6712 // not be removed when all windows are removed.
6713 final boolean explicit;
6714
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006715 // For printing.
6716 String stringName;
6717
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006718 // If this is an AppWindowToken, this is non-null.
6719 AppWindowToken appWindowToken;
6720
6721 // All of the windows associated with this token.
6722 final ArrayList<WindowState> windows = new ArrayList<WindowState>();
6723
6724 // Is key dispatching paused for this token?
6725 boolean paused = false;
6726
6727 // Should this token's windows be hidden?
6728 boolean hidden;
6729
6730 // Temporary for finding which tokens no longer have visible windows.
6731 boolean hasVisible;
6732
6733 WindowToken(IBinder _token, int type, boolean _explicit) {
6734 token = _token;
6735 windowType = type;
6736 explicit = _explicit;
6737 }
6738
6739 void dump(PrintWriter pw, String prefix) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006740 pw.print(prefix); pw.print("token="); pw.println(token);
6741 pw.print(prefix); pw.print("windows="); pw.println(windows);
6742 pw.print(prefix); pw.print("windowType="); pw.print(windowType);
6743 pw.print(" hidden="); pw.print(hidden);
6744 pw.print(" hasVisible="); pw.println(hasVisible);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006745 }
6746
6747 @Override
6748 public String toString() {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006749 if (stringName == null) {
6750 StringBuilder sb = new StringBuilder();
6751 sb.append("WindowToken{");
6752 sb.append(Integer.toHexString(System.identityHashCode(this)));
6753 sb.append(" token="); sb.append(token); sb.append('}');
6754 stringName = sb.toString();
6755 }
6756 return stringName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006757 }
6758 };
6759
6760 class AppWindowToken extends WindowToken {
6761 // Non-null only for application tokens.
6762 final IApplicationToken appToken;
6763
6764 // All of the windows and child windows that are included in this
6765 // application token. Note this list is NOT sorted!
6766 final ArrayList<WindowState> allAppWindows = new ArrayList<WindowState>();
6767
6768 int groupId = -1;
6769 boolean appFullscreen;
6770 int requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
6771
6772 // These are used for determining when all windows associated with
6773 // an activity have been drawn, so they can be made visible together
6774 // at the same time.
6775 int lastTransactionSequence = mTransactionSequence-1;
6776 int numInterestingWindows;
6777 int numDrawnWindows;
6778 boolean inPendingTransaction;
6779 boolean allDrawn;
6780
6781 // Is this token going to be hidden in a little while? If so, it
6782 // won't be taken into account for setting the screen orientation.
6783 boolean willBeHidden;
6784
6785 // Is this window's surface needed? This is almost like hidden, except
6786 // it will sometimes be true a little earlier: when the token has
6787 // been shown, but is still waiting for its app transition to execute
6788 // before making its windows shown.
6789 boolean hiddenRequested;
6790
6791 // Have we told the window clients to hide themselves?
6792 boolean clientHidden;
6793
6794 // Last visibility state we reported to the app token.
6795 boolean reportedVisible;
6796
6797 // Set to true when the token has been removed from the window mgr.
6798 boolean removed;
6799
6800 // Have we been asked to have this token keep the screen frozen?
6801 boolean freezingScreen;
6802
6803 boolean animating;
6804 Animation animation;
6805 boolean hasTransformation;
6806 final Transformation transformation = new Transformation();
6807
6808 // Offset to the window of all layers in the token, for use by
6809 // AppWindowToken animations.
6810 int animLayerAdjustment;
6811
6812 // Information about an application starting window if displayed.
6813 StartingData startingData;
6814 WindowState startingWindow;
6815 View startingView;
6816 boolean startingDisplayed;
6817 boolean startingMoved;
6818 boolean firstWindowDrawn;
6819
6820 AppWindowToken(IApplicationToken _token) {
6821 super(_token.asBinder(),
6822 WindowManager.LayoutParams.TYPE_APPLICATION, true);
6823 appWindowToken = this;
6824 appToken = _token;
6825 }
6826
6827 public void setAnimation(Animation anim) {
6828 if (localLOGV) Log.v(
6829 TAG, "Setting animation in " + this + ": " + anim);
6830 animation = anim;
6831 animating = false;
6832 anim.restrictDuration(MAX_ANIMATION_DURATION);
6833 anim.scaleCurrentDuration(mTransitionAnimationScale);
6834 int zorder = anim.getZAdjustment();
6835 int adj = 0;
6836 if (zorder == Animation.ZORDER_TOP) {
6837 adj = TYPE_LAYER_OFFSET;
6838 } else if (zorder == Animation.ZORDER_BOTTOM) {
6839 adj = -TYPE_LAYER_OFFSET;
6840 }
6841
6842 if (animLayerAdjustment != adj) {
6843 animLayerAdjustment = adj;
6844 updateLayers();
6845 }
6846 }
6847
6848 public void setDummyAnimation() {
6849 if (animation == null) {
6850 if (localLOGV) Log.v(
6851 TAG, "Setting dummy animation in " + this);
6852 animation = sDummyAnimation;
6853 }
6854 }
6855
6856 public void clearAnimation() {
6857 if (animation != null) {
6858 animation = null;
6859 animating = true;
6860 }
6861 }
6862
6863 void updateLayers() {
6864 final int N = allAppWindows.size();
6865 final int adj = animLayerAdjustment;
6866 for (int i=0; i<N; i++) {
6867 WindowState w = allAppWindows.get(i);
6868 w.mAnimLayer = w.mLayer + adj;
6869 if (DEBUG_LAYERS) Log.v(TAG, "Updating layer " + w + ": "
6870 + w.mAnimLayer);
6871 if (w == mInputMethodTarget) {
6872 setInputMethodAnimLayerAdjustment(adj);
6873 }
6874 }
6875 }
6876
6877 void sendAppVisibilityToClients() {
6878 final int N = allAppWindows.size();
6879 for (int i=0; i<N; i++) {
6880 WindowState win = allAppWindows.get(i);
6881 if (win == startingWindow && clientHidden) {
6882 // Don't hide the starting window.
6883 continue;
6884 }
6885 try {
6886 if (DEBUG_VISIBILITY) Log.v(TAG,
6887 "Setting visibility of " + win + ": " + (!clientHidden));
6888 win.mClient.dispatchAppVisibility(!clientHidden);
6889 } catch (RemoteException e) {
6890 }
6891 }
6892 }
6893
6894 void showAllWindowsLocked() {
6895 final int NW = allAppWindows.size();
6896 for (int i=0; i<NW; i++) {
6897 WindowState w = allAppWindows.get(i);
6898 if (DEBUG_VISIBILITY) Log.v(TAG,
6899 "performing show on: " + w);
6900 w.performShowLocked();
6901 }
6902 }
6903
6904 // This must be called while inside a transaction.
6905 boolean stepAnimationLocked(long currentTime, int dw, int dh) {
6906 if (!mDisplayFrozen) {
6907 // We will run animations as long as the display isn't frozen.
6908
6909 if (animation == sDummyAnimation) {
6910 // This guy is going to animate, but not yet. For now count
6911 // it is not animating for purposes of scheduling transactions;
6912 // when it is really time to animate, this will be set to
6913 // a real animation and the next call will execute normally.
6914 return false;
6915 }
6916
6917 if ((allDrawn || animating || startingDisplayed) && animation != null) {
6918 if (!animating) {
6919 if (DEBUG_ANIM) Log.v(
6920 TAG, "Starting animation in " + this +
6921 " @ " + currentTime + ": dw=" + dw + " dh=" + dh
6922 + " scale=" + mTransitionAnimationScale
6923 + " allDrawn=" + allDrawn + " animating=" + animating);
6924 animation.initialize(dw, dh, dw, dh);
6925 animation.setStartTime(currentTime);
6926 animating = true;
6927 }
6928 transformation.clear();
6929 final boolean more = animation.getTransformation(
6930 currentTime, transformation);
6931 if (DEBUG_ANIM) Log.v(
6932 TAG, "Stepped animation in " + this +
6933 ": more=" + more + ", xform=" + transformation);
6934 if (more) {
6935 // we're done!
6936 hasTransformation = true;
6937 return true;
6938 }
6939 if (DEBUG_ANIM) Log.v(
6940 TAG, "Finished animation in " + this +
6941 " @ " + currentTime);
6942 animation = null;
6943 }
6944 } else if (animation != null) {
6945 // If the display is frozen, and there is a pending animation,
6946 // clear it and make sure we run the cleanup code.
6947 animating = true;
6948 animation = null;
6949 }
6950
6951 hasTransformation = false;
6952
6953 if (!animating) {
6954 return false;
6955 }
6956
6957 clearAnimation();
6958 animating = false;
6959 if (mInputMethodTarget != null && mInputMethodTarget.mAppToken == this) {
6960 moveInputMethodWindowsIfNeededLocked(true);
6961 }
6962
6963 if (DEBUG_ANIM) Log.v(
6964 TAG, "Animation done in " + this
6965 + ": reportedVisible=" + reportedVisible);
6966
6967 transformation.clear();
6968 if (animLayerAdjustment != 0) {
6969 animLayerAdjustment = 0;
6970 updateLayers();
6971 }
6972
6973 final int N = windows.size();
6974 for (int i=0; i<N; i++) {
6975 ((WindowState)windows.get(i)).finishExit();
6976 }
6977 updateReportedVisibilityLocked();
6978
6979 return false;
6980 }
6981
6982 void updateReportedVisibilityLocked() {
6983 if (appToken == null) {
6984 return;
6985 }
6986
6987 int numInteresting = 0;
6988 int numVisible = 0;
6989 boolean nowGone = true;
6990
6991 if (DEBUG_VISIBILITY) Log.v(TAG, "Update reported visibility: " + this);
6992 final int N = allAppWindows.size();
6993 for (int i=0; i<N; i++) {
6994 WindowState win = allAppWindows.get(i);
6995 if (win == startingWindow || win.mAppFreezing) {
6996 continue;
6997 }
6998 if (DEBUG_VISIBILITY) {
6999 Log.v(TAG, "Win " + win + ": isDisplayed="
7000 + win.isDisplayedLw()
7001 + ", isAnimating=" + win.isAnimating());
7002 if (!win.isDisplayedLw()) {
7003 Log.v(TAG, "Not displayed: s=" + win.mSurface
7004 + " pv=" + win.mPolicyVisibility
7005 + " dp=" + win.mDrawPending
7006 + " cdp=" + win.mCommitDrawPending
7007 + " ah=" + win.mAttachedHidden
7008 + " th="
7009 + (win.mAppToken != null
7010 ? win.mAppToken.hiddenRequested : false)
7011 + " a=" + win.mAnimating);
7012 }
7013 }
7014 numInteresting++;
7015 if (win.isDisplayedLw()) {
7016 if (!win.isAnimating()) {
7017 numVisible++;
7018 }
7019 nowGone = false;
7020 } else if (win.isAnimating()) {
7021 nowGone = false;
7022 }
7023 }
7024
7025 boolean nowVisible = numInteresting > 0 && numVisible >= numInteresting;
7026 if (DEBUG_VISIBILITY) Log.v(TAG, "VIS " + this + ": interesting="
7027 + numInteresting + " visible=" + numVisible);
7028 if (nowVisible != reportedVisible) {
7029 if (DEBUG_VISIBILITY) Log.v(
7030 TAG, "Visibility changed in " + this
7031 + ": vis=" + nowVisible);
7032 reportedVisible = nowVisible;
7033 Message m = mH.obtainMessage(
7034 H.REPORT_APPLICATION_TOKEN_WINDOWS,
7035 nowVisible ? 1 : 0,
7036 nowGone ? 1 : 0,
7037 this);
7038 mH.sendMessage(m);
7039 }
7040 }
7041
7042 void dump(PrintWriter pw, String prefix) {
7043 super.dump(pw, prefix);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007044 if (appToken != null) {
7045 pw.print(prefix); pw.println("app=true");
7046 }
7047 if (allAppWindows.size() > 0) {
7048 pw.print(prefix); pw.print("allAppWindows="); pw.println(allAppWindows);
7049 }
7050 pw.print(prefix); pw.print("groupId="); pw.print(groupId);
7051 pw.print(" requestedOrientation="); pw.println(requestedOrientation);
7052 pw.print(prefix); pw.print("hiddenRequested="); pw.print(hiddenRequested);
7053 pw.print(" clientHidden="); pw.print(clientHidden);
7054 pw.print(" willBeHidden="); pw.print(willBeHidden);
7055 pw.print(" reportedVisible="); pw.println(reportedVisible);
7056 if (paused || freezingScreen) {
7057 pw.print(prefix); pw.print("paused="); pw.print(paused);
7058 pw.print(" freezingScreen="); pw.println(freezingScreen);
7059 }
7060 if (numInterestingWindows != 0 || numDrawnWindows != 0
7061 || inPendingTransaction || allDrawn) {
7062 pw.print(prefix); pw.print("numInterestingWindows=");
7063 pw.print(numInterestingWindows);
7064 pw.print(" numDrawnWindows="); pw.print(numDrawnWindows);
7065 pw.print(" inPendingTransaction="); pw.print(inPendingTransaction);
7066 pw.print(" allDrawn="); pw.println(allDrawn);
7067 }
7068 if (animating || animation != null) {
7069 pw.print(prefix); pw.print("animating="); pw.print(animating);
7070 pw.print(" animation="); pw.println(animation);
7071 }
7072 if (animLayerAdjustment != 0) {
7073 pw.print(prefix); pw.print("animLayerAdjustment="); pw.println(animLayerAdjustment);
7074 }
7075 if (hasTransformation) {
7076 pw.print(prefix); pw.print("hasTransformation="); pw.print(hasTransformation);
7077 pw.print(" transformation="); transformation.printShortString(pw);
7078 pw.println();
7079 }
7080 if (startingData != null || removed || firstWindowDrawn) {
7081 pw.print(prefix); pw.print("startingData="); pw.print(startingData);
7082 pw.print(" removed="); pw.print(removed);
7083 pw.print(" firstWindowDrawn="); pw.println(firstWindowDrawn);
7084 }
7085 if (startingWindow != null || startingView != null
7086 || startingDisplayed || startingMoved) {
7087 pw.print(prefix); pw.print("startingWindow="); pw.print(startingWindow);
7088 pw.print(" startingView="); pw.print(startingView);
7089 pw.print(" startingDisplayed="); pw.print(startingDisplayed);
7090 pw.print(" startingMoved"); pw.println(startingMoved);
7091 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007092 }
7093
7094 @Override
7095 public String toString() {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007096 if (stringName == null) {
7097 StringBuilder sb = new StringBuilder();
7098 sb.append("AppWindowToken{");
7099 sb.append(Integer.toHexString(System.identityHashCode(this)));
7100 sb.append(" token="); sb.append(token); sb.append('}');
7101 stringName = sb.toString();
7102 }
7103 return stringName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007104 }
7105 }
7106
7107 public static WindowManager.LayoutParams findAnimations(
7108 ArrayList<AppWindowToken> order,
7109 ArrayList<AppWindowToken> tokenList1,
7110 ArrayList<AppWindowToken> tokenList2) {
7111 // We need to figure out which animation to use...
7112 WindowManager.LayoutParams animParams = null;
7113 int animSrc = 0;
7114
7115 //Log.i(TAG, "Looking for animations...");
7116 for (int i=order.size()-1; i>=0; i--) {
7117 AppWindowToken wtoken = order.get(i);
7118 //Log.i(TAG, "Token " + wtoken + " with " + wtoken.windows.size() + " windows");
7119 if (tokenList1.contains(wtoken) || tokenList2.contains(wtoken)) {
7120 int j = wtoken.windows.size();
7121 while (j > 0) {
7122 j--;
7123 WindowState win = wtoken.windows.get(j);
7124 //Log.i(TAG, "Window " + win + ": type=" + win.mAttrs.type);
7125 if (win.mAttrs.type == WindowManager.LayoutParams.TYPE_BASE_APPLICATION
7126 || win.mAttrs.type == WindowManager.LayoutParams.TYPE_APPLICATION_STARTING) {
7127 //Log.i(TAG, "Found base or application window, done!");
7128 if (wtoken.appFullscreen) {
7129 return win.mAttrs;
7130 }
7131 if (animSrc < 2) {
7132 animParams = win.mAttrs;
7133 animSrc = 2;
7134 }
7135 } else if (animSrc < 1 && win.mAttrs.type == WindowManager.LayoutParams.TYPE_APPLICATION) {
7136 //Log.i(TAG, "Found normal window, we may use this...");
7137 animParams = win.mAttrs;
7138 animSrc = 1;
7139 }
7140 }
7141 }
7142 }
7143
7144 return animParams;
7145 }
7146
7147 // -------------------------------------------------------------
7148 // DummyAnimation
7149 // -------------------------------------------------------------
7150
7151 // This is an animation that does nothing: it just immediately finishes
7152 // itself every time it is called. It is used as a stub animation in cases
7153 // where we want to synchronize multiple things that may be animating.
7154 static final class DummyAnimation extends Animation {
7155 public boolean getTransformation(long currentTime, Transformation outTransformation) {
7156 return false;
7157 }
7158 }
7159 static final Animation sDummyAnimation = new DummyAnimation();
7160
7161 // -------------------------------------------------------------
7162 // Async Handler
7163 // -------------------------------------------------------------
7164
7165 static final class StartingData {
7166 final String pkg;
7167 final int theme;
7168 final CharSequence nonLocalizedLabel;
7169 final int labelRes;
7170 final int icon;
7171
7172 StartingData(String _pkg, int _theme, CharSequence _nonLocalizedLabel,
7173 int _labelRes, int _icon) {
7174 pkg = _pkg;
7175 theme = _theme;
7176 nonLocalizedLabel = _nonLocalizedLabel;
7177 labelRes = _labelRes;
7178 icon = _icon;
7179 }
7180 }
7181
7182 private final class H extends Handler {
7183 public static final int REPORT_FOCUS_CHANGE = 2;
7184 public static final int REPORT_LOSING_FOCUS = 3;
7185 public static final int ANIMATE = 4;
7186 public static final int ADD_STARTING = 5;
7187 public static final int REMOVE_STARTING = 6;
7188 public static final int FINISHED_STARTING = 7;
7189 public static final int REPORT_APPLICATION_TOKEN_WINDOWS = 8;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007190 public static final int WINDOW_FREEZE_TIMEOUT = 11;
7191 public static final int HOLD_SCREEN_CHANGED = 12;
7192 public static final int APP_TRANSITION_TIMEOUT = 13;
7193 public static final int PERSIST_ANIMATION_SCALE = 14;
7194 public static final int FORCE_GC = 15;
7195 public static final int ENABLE_SCREEN = 16;
7196 public static final int APP_FREEZE_TIMEOUT = 17;
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07007197 public static final int COMPUTE_AND_SEND_NEW_CONFIGURATION = 18;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007198
7199 private Session mLastReportedHold;
7200
7201 public H() {
7202 }
7203
7204 @Override
7205 public void handleMessage(Message msg) {
7206 switch (msg.what) {
7207 case REPORT_FOCUS_CHANGE: {
7208 WindowState lastFocus;
7209 WindowState newFocus;
7210
7211 synchronized(mWindowMap) {
7212 lastFocus = mLastFocus;
7213 newFocus = mCurrentFocus;
7214 if (lastFocus == newFocus) {
7215 // Focus is not changing, so nothing to do.
7216 return;
7217 }
7218 mLastFocus = newFocus;
7219 //Log.i(TAG, "Focus moving from " + lastFocus
7220 // + " to " + newFocus);
7221 if (newFocus != null && lastFocus != null
7222 && !newFocus.isDisplayedLw()) {
7223 //Log.i(TAG, "Delaying loss of focus...");
7224 mLosingFocus.add(lastFocus);
7225 lastFocus = null;
7226 }
7227 }
7228
7229 if (lastFocus != newFocus) {
7230 //System.out.println("Changing focus from " + lastFocus
7231 // + " to " + newFocus);
7232 if (newFocus != null) {
7233 try {
7234 //Log.i(TAG, "Gaining focus: " + newFocus);
7235 newFocus.mClient.windowFocusChanged(true, mInTouchMode);
7236 } catch (RemoteException e) {
7237 // Ignore if process has died.
7238 }
7239 }
7240
7241 if (lastFocus != null) {
7242 try {
7243 //Log.i(TAG, "Losing focus: " + lastFocus);
7244 lastFocus.mClient.windowFocusChanged(false, mInTouchMode);
7245 } catch (RemoteException e) {
7246 // Ignore if process has died.
7247 }
7248 }
7249 }
7250 } break;
7251
7252 case REPORT_LOSING_FOCUS: {
7253 ArrayList<WindowState> losers;
7254
7255 synchronized(mWindowMap) {
7256 losers = mLosingFocus;
7257 mLosingFocus = new ArrayList<WindowState>();
7258 }
7259
7260 final int N = losers.size();
7261 for (int i=0; i<N; i++) {
7262 try {
7263 //Log.i(TAG, "Losing delayed focus: " + losers.get(i));
7264 losers.get(i).mClient.windowFocusChanged(false, mInTouchMode);
7265 } catch (RemoteException e) {
7266 // Ignore if process has died.
7267 }
7268 }
7269 } break;
7270
7271 case ANIMATE: {
7272 synchronized(mWindowMap) {
7273 mAnimationPending = false;
7274 performLayoutAndPlaceSurfacesLocked();
7275 }
7276 } break;
7277
7278 case ADD_STARTING: {
7279 final AppWindowToken wtoken = (AppWindowToken)msg.obj;
7280 final StartingData sd = wtoken.startingData;
7281
7282 if (sd == null) {
7283 // Animation has been canceled... do nothing.
7284 return;
7285 }
7286
7287 if (DEBUG_STARTING_WINDOW) Log.v(TAG, "Add starting "
7288 + wtoken + ": pkg=" + sd.pkg);
7289
7290 View view = null;
7291 try {
7292 view = mPolicy.addStartingWindow(
7293 wtoken.token, sd.pkg,
7294 sd.theme, sd.nonLocalizedLabel, sd.labelRes,
7295 sd.icon);
7296 } catch (Exception e) {
7297 Log.w(TAG, "Exception when adding starting window", e);
7298 }
7299
7300 if (view != null) {
7301 boolean abort = false;
7302
7303 synchronized(mWindowMap) {
7304 if (wtoken.removed || wtoken.startingData == null) {
7305 // If the window was successfully added, then
7306 // we need to remove it.
7307 if (wtoken.startingWindow != null) {
7308 if (DEBUG_STARTING_WINDOW) Log.v(TAG,
7309 "Aborted starting " + wtoken
7310 + ": removed=" + wtoken.removed
7311 + " startingData=" + wtoken.startingData);
7312 wtoken.startingWindow = null;
7313 wtoken.startingData = null;
7314 abort = true;
7315 }
7316 } else {
7317 wtoken.startingView = view;
7318 }
7319 if (DEBUG_STARTING_WINDOW && !abort) Log.v(TAG,
7320 "Added starting " + wtoken
7321 + ": startingWindow="
7322 + wtoken.startingWindow + " startingView="
7323 + wtoken.startingView);
7324 }
7325
7326 if (abort) {
7327 try {
7328 mPolicy.removeStartingWindow(wtoken.token, view);
7329 } catch (Exception e) {
7330 Log.w(TAG, "Exception when removing starting window", e);
7331 }
7332 }
7333 }
7334 } break;
7335
7336 case REMOVE_STARTING: {
7337 final AppWindowToken wtoken = (AppWindowToken)msg.obj;
7338 IBinder token = null;
7339 View view = null;
7340 synchronized (mWindowMap) {
7341 if (DEBUG_STARTING_WINDOW) Log.v(TAG, "Remove starting "
7342 + wtoken + ": startingWindow="
7343 + wtoken.startingWindow + " startingView="
7344 + wtoken.startingView);
7345 if (wtoken.startingWindow != null) {
7346 view = wtoken.startingView;
7347 token = wtoken.token;
7348 wtoken.startingData = null;
7349 wtoken.startingView = null;
7350 wtoken.startingWindow = null;
7351 }
7352 }
7353 if (view != null) {
7354 try {
7355 mPolicy.removeStartingWindow(token, view);
7356 } catch (Exception e) {
7357 Log.w(TAG, "Exception when removing starting window", e);
7358 }
7359 }
7360 } break;
7361
7362 case FINISHED_STARTING: {
7363 IBinder token = null;
7364 View view = null;
7365 while (true) {
7366 synchronized (mWindowMap) {
7367 final int N = mFinishedStarting.size();
7368 if (N <= 0) {
7369 break;
7370 }
7371 AppWindowToken wtoken = mFinishedStarting.remove(N-1);
7372
7373 if (DEBUG_STARTING_WINDOW) Log.v(TAG,
7374 "Finished starting " + wtoken
7375 + ": startingWindow=" + wtoken.startingWindow
7376 + " startingView=" + wtoken.startingView);
7377
7378 if (wtoken.startingWindow == null) {
7379 continue;
7380 }
7381
7382 view = wtoken.startingView;
7383 token = wtoken.token;
7384 wtoken.startingData = null;
7385 wtoken.startingView = null;
7386 wtoken.startingWindow = null;
7387 }
7388
7389 try {
7390 mPolicy.removeStartingWindow(token, view);
7391 } catch (Exception e) {
7392 Log.w(TAG, "Exception when removing starting window", e);
7393 }
7394 }
7395 } break;
7396
7397 case REPORT_APPLICATION_TOKEN_WINDOWS: {
7398 final AppWindowToken wtoken = (AppWindowToken)msg.obj;
7399
7400 boolean nowVisible = msg.arg1 != 0;
7401 boolean nowGone = msg.arg2 != 0;
7402
7403 try {
7404 if (DEBUG_VISIBILITY) Log.v(
7405 TAG, "Reporting visible in " + wtoken
7406 + " visible=" + nowVisible
7407 + " gone=" + nowGone);
7408 if (nowVisible) {
7409 wtoken.appToken.windowsVisible();
7410 } else {
7411 wtoken.appToken.windowsGone();
7412 }
7413 } catch (RemoteException ex) {
7414 }
7415 } break;
7416
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007417 case WINDOW_FREEZE_TIMEOUT: {
7418 synchronized (mWindowMap) {
7419 Log.w(TAG, "Window freeze timeout expired.");
7420 int i = mWindows.size();
7421 while (i > 0) {
7422 i--;
7423 WindowState w = (WindowState)mWindows.get(i);
7424 if (w.mOrientationChanging) {
7425 w.mOrientationChanging = false;
7426 Log.w(TAG, "Force clearing orientation change: " + w);
7427 }
7428 }
7429 performLayoutAndPlaceSurfacesLocked();
7430 }
7431 break;
7432 }
7433
7434 case HOLD_SCREEN_CHANGED: {
7435 Session oldHold;
7436 Session newHold;
7437 synchronized (mWindowMap) {
7438 oldHold = mLastReportedHold;
7439 newHold = (Session)msg.obj;
7440 mLastReportedHold = newHold;
7441 }
7442
7443 if (oldHold != newHold) {
7444 try {
7445 if (oldHold != null) {
7446 mBatteryStats.noteStopWakelock(oldHold.mUid,
7447 "window",
7448 BatteryStats.WAKE_TYPE_WINDOW);
7449 }
7450 if (newHold != null) {
7451 mBatteryStats.noteStartWakelock(newHold.mUid,
7452 "window",
7453 BatteryStats.WAKE_TYPE_WINDOW);
7454 }
7455 } catch (RemoteException e) {
7456 }
7457 }
7458 break;
7459 }
7460
7461 case APP_TRANSITION_TIMEOUT: {
7462 synchronized (mWindowMap) {
7463 if (mNextAppTransition != WindowManagerPolicy.TRANSIT_NONE) {
7464 if (DEBUG_APP_TRANSITIONS) Log.v(TAG,
7465 "*** APP TRANSITION TIMEOUT");
7466 mAppTransitionReady = true;
7467 mAppTransitionTimeout = true;
7468 performLayoutAndPlaceSurfacesLocked();
7469 }
7470 }
7471 break;
7472 }
7473
7474 case PERSIST_ANIMATION_SCALE: {
7475 Settings.System.putFloat(mContext.getContentResolver(),
7476 Settings.System.WINDOW_ANIMATION_SCALE, mWindowAnimationScale);
7477 Settings.System.putFloat(mContext.getContentResolver(),
7478 Settings.System.TRANSITION_ANIMATION_SCALE, mTransitionAnimationScale);
7479 break;
7480 }
7481
7482 case FORCE_GC: {
7483 synchronized(mWindowMap) {
7484 if (mAnimationPending) {
7485 // If we are animating, don't do the gc now but
7486 // delay a bit so we don't interrupt the animation.
7487 mH.sendMessageDelayed(mH.obtainMessage(H.FORCE_GC),
7488 2000);
7489 return;
7490 }
7491 // If we are currently rotating the display, it will
7492 // schedule a new message when done.
7493 if (mDisplayFrozen) {
7494 return;
7495 }
7496 mFreezeGcPending = 0;
7497 }
7498 Runtime.getRuntime().gc();
7499 break;
7500 }
7501
7502 case ENABLE_SCREEN: {
7503 performEnableScreen();
7504 break;
7505 }
7506
7507 case APP_FREEZE_TIMEOUT: {
7508 synchronized (mWindowMap) {
7509 Log.w(TAG, "App freeze timeout expired.");
7510 int i = mAppTokens.size();
7511 while (i > 0) {
7512 i--;
7513 AppWindowToken tok = mAppTokens.get(i);
7514 if (tok.freezingScreen) {
7515 Log.w(TAG, "Force clearing freeze: " + tok);
7516 unsetAppFreezingScreenLocked(tok, true, true);
7517 }
7518 }
7519 }
7520 break;
7521 }
7522
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07007523 case COMPUTE_AND_SEND_NEW_CONFIGURATION: {
The Android Open Source Project10592532009-03-18 17:39:46 -07007524 if (updateOrientationFromAppTokens(null, null) != null) {
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07007525 sendNewConfiguration();
7526 }
7527 break;
7528 }
7529
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007530 }
7531 }
7532 }
7533
7534 // -------------------------------------------------------------
7535 // IWindowManager API
7536 // -------------------------------------------------------------
7537
7538 public IWindowSession openSession(IInputMethodClient client,
7539 IInputContext inputContext) {
7540 if (client == null) throw new IllegalArgumentException("null client");
7541 if (inputContext == null) throw new IllegalArgumentException("null inputContext");
7542 return new Session(client, inputContext);
7543 }
7544
7545 public boolean inputMethodClientHasFocus(IInputMethodClient client) {
7546 synchronized (mWindowMap) {
7547 // The focus for the client is the window immediately below
7548 // where we would place the input method window.
7549 int idx = findDesiredInputMethodWindowIndexLocked(false);
7550 WindowState imFocus;
7551 if (idx > 0) {
7552 imFocus = (WindowState)mWindows.get(idx-1);
7553 if (imFocus != null) {
7554 if (imFocus.mSession.mClient != null &&
7555 imFocus.mSession.mClient.asBinder() == client.asBinder()) {
7556 return true;
7557 }
7558 }
7559 }
7560 }
7561 return false;
7562 }
7563
7564 // -------------------------------------------------------------
7565 // Internals
7566 // -------------------------------------------------------------
7567
7568 final WindowState windowForClientLocked(Session session, IWindow client) {
7569 return windowForClientLocked(session, client.asBinder());
7570 }
7571
7572 final WindowState windowForClientLocked(Session session, IBinder client) {
7573 WindowState win = mWindowMap.get(client);
7574 if (localLOGV) Log.v(
7575 TAG, "Looking up client " + client + ": " + win);
7576 if (win == null) {
7577 RuntimeException ex = new RuntimeException();
7578 Log.w(TAG, "Requested window " + client + " does not exist", ex);
7579 return null;
7580 }
7581 if (session != null && win.mSession != session) {
7582 RuntimeException ex = new RuntimeException();
7583 Log.w(TAG, "Requested window " + client + " is in session " +
7584 win.mSession + ", not " + session, ex);
7585 return null;
7586 }
7587
7588 return win;
7589 }
7590
7591 private final void assignLayersLocked() {
7592 int N = mWindows.size();
7593 int curBaseLayer = 0;
7594 int curLayer = 0;
7595 int i;
7596
7597 for (i=0; i<N; i++) {
7598 WindowState w = (WindowState)mWindows.get(i);
7599 if (w.mBaseLayer == curBaseLayer || w.mIsImWindow) {
7600 curLayer += WINDOW_LAYER_MULTIPLIER;
7601 w.mLayer = curLayer;
7602 } else {
7603 curBaseLayer = curLayer = w.mBaseLayer;
7604 w.mLayer = curLayer;
7605 }
7606 if (w.mTargetAppToken != null) {
7607 w.mAnimLayer = w.mLayer + w.mTargetAppToken.animLayerAdjustment;
7608 } else if (w.mAppToken != null) {
7609 w.mAnimLayer = w.mLayer + w.mAppToken.animLayerAdjustment;
7610 } else {
7611 w.mAnimLayer = w.mLayer;
7612 }
7613 if (w.mIsImWindow) {
7614 w.mAnimLayer += mInputMethodAnimLayerAdjustment;
7615 }
7616 if (DEBUG_LAYERS) Log.v(TAG, "Assign layer " + w + ": "
7617 + w.mAnimLayer);
7618 //System.out.println(
7619 // "Assigned layer " + curLayer + " to " + w.mClient.asBinder());
7620 }
7621 }
7622
7623 private boolean mInLayout = false;
7624 private final void performLayoutAndPlaceSurfacesLocked() {
7625 if (mInLayout) {
Dave Bortcfe65242009-04-09 14:51:04 -07007626 if (DEBUG) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007627 throw new RuntimeException("Recursive call!");
7628 }
7629 Log.w(TAG, "performLayoutAndPlaceSurfacesLocked called while in layout");
7630 return;
7631 }
7632
7633 boolean recoveringMemory = false;
7634 if (mForceRemoves != null) {
7635 recoveringMemory = true;
7636 // Wait a little it for things to settle down, and off we go.
7637 for (int i=0; i<mForceRemoves.size(); i++) {
7638 WindowState ws = mForceRemoves.get(i);
7639 Log.i(TAG, "Force removing: " + ws);
7640 removeWindowInnerLocked(ws.mSession, ws);
7641 }
7642 mForceRemoves = null;
7643 Log.w(TAG, "Due to memory failure, waiting a bit for next layout");
7644 Object tmp = new Object();
7645 synchronized (tmp) {
7646 try {
7647 tmp.wait(250);
7648 } catch (InterruptedException e) {
7649 }
7650 }
7651 }
7652
7653 mInLayout = true;
7654 try {
7655 performLayoutAndPlaceSurfacesLockedInner(recoveringMemory);
7656
7657 int i = mPendingRemove.size()-1;
7658 if (i >= 0) {
7659 while (i >= 0) {
7660 WindowState w = mPendingRemove.get(i);
7661 removeWindowInnerLocked(w.mSession, w);
7662 i--;
7663 }
7664 mPendingRemove.clear();
7665
7666 mInLayout = false;
7667 assignLayersLocked();
7668 mLayoutNeeded = true;
7669 performLayoutAndPlaceSurfacesLocked();
7670
7671 } else {
7672 mInLayout = false;
7673 if (mLayoutNeeded) {
7674 requestAnimationLocked(0);
7675 }
7676 }
7677 } catch (RuntimeException e) {
7678 mInLayout = false;
7679 Log.e(TAG, "Unhandled exception while layout out windows", e);
7680 }
7681 }
7682
7683 private final void performLayoutLockedInner() {
7684 final int dw = mDisplay.getWidth();
7685 final int dh = mDisplay.getHeight();
7686
7687 final int N = mWindows.size();
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07007688 int repeats = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007689 int i;
7690
7691 // FIRST LOOP: Perform a layout, if needed.
7692
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07007693 while (mLayoutNeeded) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007694 mPolicy.beginLayoutLw(dw, dh);
7695
7696 // First perform layout of any root windows (not attached
7697 // to another window).
7698 int topAttached = -1;
7699 for (i = N-1; i >= 0; i--) {
7700 WindowState win = (WindowState) mWindows.get(i);
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07007701
7702 // Don't do layout of a window if it is not visible, or
7703 // soon won't be visible, to avoid wasting time and funky
7704 // changes while a window is animating away.
7705 final AppWindowToken atoken = win.mAppToken;
7706 final boolean gone = win.mViewVisibility == View.GONE
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007707 || !win.mRelayoutCalled
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07007708 || win.mRootToken.hidden
7709 || (atoken != null && atoken.hiddenRequested)
7710 || !win.mPolicyVisibility
7711 || win.mAttachedHidden
7712 || win.mExiting || win.mDestroying;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007713
7714 // If this view is GONE, then skip it -- keep the current
7715 // frame, and let the caller know so they can ignore it
7716 // if they want. (We do the normal layout for INVISIBLE
7717 // windows, since that means "perform layout as normal,
7718 // just don't display").
7719 if (!gone || !win.mHaveFrame) {
7720 if (!win.mLayoutAttached) {
7721 mPolicy.layoutWindowLw(win, win.mAttrs, null);
7722 } else {
7723 if (topAttached < 0) topAttached = i;
7724 }
7725 }
7726 }
7727
7728 // Now perform layout of attached windows, which usually
7729 // depend on the position of the window they are attached to.
7730 // XXX does not deal with windows that are attached to windows
7731 // that are themselves attached.
7732 for (i = topAttached; i >= 0; i--) {
7733 WindowState win = (WindowState) mWindows.get(i);
7734
7735 // If this view is GONE, then skip it -- keep the current
7736 // frame, and let the caller know so they can ignore it
7737 // if they want. (We do the normal layout for INVISIBLE
7738 // windows, since that means "perform layout as normal,
7739 // just don't display").
7740 if (win.mLayoutAttached) {
7741 if ((win.mViewVisibility != View.GONE && win.mRelayoutCalled)
7742 || !win.mHaveFrame) {
7743 mPolicy.layoutWindowLw(win, win.mAttrs, win.mAttachedWindow);
7744 }
7745 }
7746 }
7747
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07007748 if (!mPolicy.finishLayoutLw()) {
7749 mLayoutNeeded = false;
7750 } else if (repeats > 2) {
7751 Log.w(TAG, "Layout repeat aborted after too many iterations");
7752 mLayoutNeeded = false;
7753 } else {
7754 repeats++;
7755 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007756 }
7757 }
7758
7759 private final void performLayoutAndPlaceSurfacesLockedInner(
7760 boolean recoveringMemory) {
7761 final long currentTime = SystemClock.uptimeMillis();
7762 final int dw = mDisplay.getWidth();
7763 final int dh = mDisplay.getHeight();
7764
7765 final int N = mWindows.size();
7766 int i;
7767
7768 // FIRST LOOP: Perform a layout, if needed.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007769 performLayoutLockedInner();
7770
7771 if (mFxSession == null) {
7772 mFxSession = new SurfaceSession();
7773 }
7774
7775 if (SHOW_TRANSACTIONS) Log.i(TAG, ">>> OPEN TRANSACTION");
7776
7777 // Initialize state of exiting tokens.
7778 for (i=mExitingTokens.size()-1; i>=0; i--) {
7779 mExitingTokens.get(i).hasVisible = false;
7780 }
7781
7782 // Initialize state of exiting applications.
7783 for (i=mExitingAppTokens.size()-1; i>=0; i--) {
7784 mExitingAppTokens.get(i).hasVisible = false;
7785 }
7786
7787 // SECOND LOOP: Execute animations and update visibility of windows.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007788 boolean orientationChangeComplete = true;
7789 Session holdScreen = null;
7790 float screenBrightness = -1;
7791 boolean focusDisplayed = false;
7792 boolean animating = false;
7793
7794 Surface.openTransaction();
7795 try {
7796 boolean restart;
7797
7798 do {
7799 final int transactionSequence = ++mTransactionSequence;
7800
7801 // Update animations of all applications, including those
7802 // associated with exiting/removed apps
7803 boolean tokensAnimating = false;
7804 final int NAT = mAppTokens.size();
7805 for (i=0; i<NAT; i++) {
7806 if (mAppTokens.get(i).stepAnimationLocked(currentTime, dw, dh)) {
7807 tokensAnimating = true;
7808 }
7809 }
7810 final int NEAT = mExitingAppTokens.size();
7811 for (i=0; i<NEAT; i++) {
7812 if (mExitingAppTokens.get(i).stepAnimationLocked(currentTime, dw, dh)) {
7813 tokensAnimating = true;
7814 }
7815 }
7816
7817 animating = tokensAnimating;
7818 restart = false;
7819
7820 boolean tokenMayBeDrawn = false;
7821
7822 mPolicy.beginAnimationLw(dw, dh);
7823
7824 for (i=N-1; i>=0; i--) {
7825 WindowState w = (WindowState)mWindows.get(i);
7826
7827 final WindowManager.LayoutParams attrs = w.mAttrs;
7828
7829 if (w.mSurface != null) {
7830 // Execute animation.
7831 w.commitFinishDrawingLocked(currentTime);
7832 if (w.stepAnimationLocked(currentTime, dw, dh)) {
7833 animating = true;
7834 //w.dump(" ");
7835 }
7836
7837 mPolicy.animatingWindowLw(w, attrs);
7838 }
7839
7840 final AppWindowToken atoken = w.mAppToken;
7841 if (atoken != null && (!atoken.allDrawn || atoken.freezingScreen)) {
7842 if (atoken.lastTransactionSequence != transactionSequence) {
7843 atoken.lastTransactionSequence = transactionSequence;
7844 atoken.numInterestingWindows = atoken.numDrawnWindows = 0;
7845 atoken.startingDisplayed = false;
7846 }
7847 if ((w.isOnScreen() || w.mAttrs.type
7848 == WindowManager.LayoutParams.TYPE_BASE_APPLICATION)
7849 && !w.mExiting && !w.mDestroying) {
7850 if (DEBUG_VISIBILITY || DEBUG_ORIENTATION) {
7851 Log.v(TAG, "Eval win " + w + ": isDisplayed="
7852 + w.isDisplayedLw()
7853 + ", isAnimating=" + w.isAnimating());
7854 if (!w.isDisplayedLw()) {
7855 Log.v(TAG, "Not displayed: s=" + w.mSurface
7856 + " pv=" + w.mPolicyVisibility
7857 + " dp=" + w.mDrawPending
7858 + " cdp=" + w.mCommitDrawPending
7859 + " ah=" + w.mAttachedHidden
7860 + " th=" + atoken.hiddenRequested
7861 + " a=" + w.mAnimating);
7862 }
7863 }
7864 if (w != atoken.startingWindow) {
7865 if (!atoken.freezingScreen || !w.mAppFreezing) {
7866 atoken.numInterestingWindows++;
7867 if (w.isDisplayedLw()) {
7868 atoken.numDrawnWindows++;
7869 if (DEBUG_VISIBILITY || DEBUG_ORIENTATION) Log.v(TAG,
7870 "tokenMayBeDrawn: " + atoken
7871 + " freezingScreen=" + atoken.freezingScreen
7872 + " mAppFreezing=" + w.mAppFreezing);
7873 tokenMayBeDrawn = true;
7874 }
7875 }
7876 } else if (w.isDisplayedLw()) {
7877 atoken.startingDisplayed = true;
7878 }
7879 }
7880 } else if (w.mReadyToShow) {
7881 w.performShowLocked();
7882 }
7883 }
7884
7885 if (mPolicy.finishAnimationLw()) {
7886 restart = true;
7887 }
7888
7889 if (tokenMayBeDrawn) {
7890 // See if any windows have been drawn, so they (and others
7891 // associated with them) can now be shown.
7892 final int NT = mTokenList.size();
7893 for (i=0; i<NT; i++) {
7894 AppWindowToken wtoken = mTokenList.get(i).appWindowToken;
7895 if (wtoken == null) {
7896 continue;
7897 }
7898 if (wtoken.freezingScreen) {
7899 int numInteresting = wtoken.numInterestingWindows;
7900 if (numInteresting > 0 && wtoken.numDrawnWindows >= numInteresting) {
7901 if (DEBUG_VISIBILITY) Log.v(TAG,
7902 "allDrawn: " + wtoken
7903 + " interesting=" + numInteresting
7904 + " drawn=" + wtoken.numDrawnWindows);
7905 wtoken.showAllWindowsLocked();
7906 unsetAppFreezingScreenLocked(wtoken, false, true);
7907 orientationChangeComplete = true;
7908 }
7909 } else if (!wtoken.allDrawn) {
7910 int numInteresting = wtoken.numInterestingWindows;
7911 if (numInteresting > 0 && wtoken.numDrawnWindows >= numInteresting) {
7912 if (DEBUG_VISIBILITY) Log.v(TAG,
7913 "allDrawn: " + wtoken
7914 + " interesting=" + numInteresting
7915 + " drawn=" + wtoken.numDrawnWindows);
7916 wtoken.allDrawn = true;
7917 restart = true;
7918
7919 // We can now show all of the drawn windows!
7920 if (!mOpeningApps.contains(wtoken)) {
7921 wtoken.showAllWindowsLocked();
7922 }
7923 }
7924 }
7925 }
7926 }
7927
7928 // If we are ready to perform an app transition, check through
7929 // all of the app tokens to be shown and see if they are ready
7930 // to go.
7931 if (mAppTransitionReady) {
7932 int NN = mOpeningApps.size();
7933 boolean goodToGo = true;
7934 if (DEBUG_APP_TRANSITIONS) Log.v(TAG,
7935 "Checking " + NN + " opening apps (frozen="
7936 + mDisplayFrozen + " timeout="
7937 + mAppTransitionTimeout + ")...");
7938 if (!mDisplayFrozen && !mAppTransitionTimeout) {
7939 // If the display isn't frozen, wait to do anything until
7940 // all of the apps are ready. Otherwise just go because
7941 // we'll unfreeze the display when everyone is ready.
7942 for (i=0; i<NN && goodToGo; i++) {
7943 AppWindowToken wtoken = mOpeningApps.get(i);
7944 if (DEBUG_APP_TRANSITIONS) Log.v(TAG,
7945 "Check opening app" + wtoken + ": allDrawn="
7946 + wtoken.allDrawn + " startingDisplayed="
7947 + wtoken.startingDisplayed);
7948 if (!wtoken.allDrawn && !wtoken.startingDisplayed
7949 && !wtoken.startingMoved) {
7950 goodToGo = false;
7951 }
7952 }
7953 }
7954 if (goodToGo) {
7955 if (DEBUG_APP_TRANSITIONS) Log.v(TAG, "**** GOOD TO GO");
7956 int transit = mNextAppTransition;
7957 if (mSkipAppTransitionAnimation) {
7958 transit = WindowManagerPolicy.TRANSIT_NONE;
7959 }
7960 mNextAppTransition = WindowManagerPolicy.TRANSIT_NONE;
7961 mAppTransitionReady = false;
7962 mAppTransitionTimeout = false;
7963 mStartingIconInTransition = false;
7964 mSkipAppTransitionAnimation = false;
7965
7966 mH.removeMessages(H.APP_TRANSITION_TIMEOUT);
7967
7968 // We need to figure out which animation to use...
7969 WindowManager.LayoutParams lp = findAnimations(mAppTokens,
7970 mOpeningApps, mClosingApps);
7971
7972 NN = mOpeningApps.size();
7973 for (i=0; i<NN; i++) {
7974 AppWindowToken wtoken = mOpeningApps.get(i);
7975 if (DEBUG_APP_TRANSITIONS) Log.v(TAG,
7976 "Now opening app" + wtoken);
7977 wtoken.reportedVisible = false;
7978 wtoken.inPendingTransaction = false;
7979 setTokenVisibilityLocked(wtoken, lp, true, transit, false);
7980 wtoken.updateReportedVisibilityLocked();
7981 wtoken.showAllWindowsLocked();
7982 }
7983 NN = mClosingApps.size();
7984 for (i=0; i<NN; i++) {
7985 AppWindowToken wtoken = mClosingApps.get(i);
7986 if (DEBUG_APP_TRANSITIONS) Log.v(TAG,
7987 "Now closing app" + wtoken);
7988 wtoken.inPendingTransaction = false;
7989 setTokenVisibilityLocked(wtoken, lp, false, transit, false);
7990 wtoken.updateReportedVisibilityLocked();
7991 // Force the allDrawn flag, because we want to start
7992 // this guy's animations regardless of whether it's
7993 // gotten drawn.
7994 wtoken.allDrawn = true;
7995 }
7996
7997 mOpeningApps.clear();
7998 mClosingApps.clear();
7999
8000 // This has changed the visibility of windows, so perform
8001 // a new layout to get them all up-to-date.
8002 mLayoutNeeded = true;
8003 moveInputMethodWindowsIfNeededLocked(true);
8004 performLayoutLockedInner();
8005 updateFocusedWindowLocked(UPDATE_FOCUS_PLACING_SURFACES);
8006
8007 restart = true;
8008 }
8009 }
8010 } while (restart);
8011
8012 // THIRD LOOP: Update the surfaces of all windows.
8013
8014 final boolean someoneLosingFocus = mLosingFocus.size() != 0;
8015
8016 boolean obscured = false;
8017 boolean blurring = false;
8018 boolean dimming = false;
8019 boolean covered = false;
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07008020 boolean syswin = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008021
8022 for (i=N-1; i>=0; i--) {
8023 WindowState w = (WindowState)mWindows.get(i);
8024
8025 boolean displayed = false;
8026 final WindowManager.LayoutParams attrs = w.mAttrs;
8027 final int attrFlags = attrs.flags;
8028
8029 if (w.mSurface != null) {
8030 w.computeShownFrameLocked();
8031 if (localLOGV) Log.v(
8032 TAG, "Placing surface #" + i + " " + w.mSurface
8033 + ": new=" + w.mShownFrame + ", old="
8034 + w.mLastShownFrame);
8035
8036 boolean resize;
8037 int width, height;
8038 if ((w.mAttrs.flags & w.mAttrs.FLAG_SCALED) != 0) {
8039 resize = w.mLastRequestedWidth != w.mRequestedWidth ||
8040 w.mLastRequestedHeight != w.mRequestedHeight;
8041 // for a scaled surface, we just want to use
8042 // the requested size.
8043 width = w.mRequestedWidth;
8044 height = w.mRequestedHeight;
8045 w.mLastRequestedWidth = width;
8046 w.mLastRequestedHeight = height;
8047 w.mLastShownFrame.set(w.mShownFrame);
8048 try {
8049 w.mSurface.setPosition(w.mShownFrame.left, w.mShownFrame.top);
8050 } catch (RuntimeException e) {
8051 Log.w(TAG, "Error positioning surface in " + w, e);
8052 if (!recoveringMemory) {
8053 reclaimSomeSurfaceMemoryLocked(w, "position");
8054 }
8055 }
8056 } else {
8057 resize = !w.mLastShownFrame.equals(w.mShownFrame);
8058 width = w.mShownFrame.width();
8059 height = w.mShownFrame.height();
8060 w.mLastShownFrame.set(w.mShownFrame);
8061 if (resize) {
8062 if (SHOW_TRANSACTIONS) Log.i(
8063 TAG, " SURFACE " + w.mSurface + ": ("
8064 + w.mShownFrame.left + ","
8065 + w.mShownFrame.top + ") ("
8066 + w.mShownFrame.width() + "x"
8067 + w.mShownFrame.height() + ")");
8068 }
8069 }
8070
8071 if (resize) {
8072 if (width < 1) width = 1;
8073 if (height < 1) height = 1;
8074 if (w.mSurface != null) {
8075 try {
8076 w.mSurface.setSize(width, height);
8077 w.mSurface.setPosition(w.mShownFrame.left,
8078 w.mShownFrame.top);
8079 } catch (RuntimeException e) {
8080 // If something goes wrong with the surface (such
8081 // as running out of memory), don't take down the
8082 // entire system.
8083 Log.e(TAG, "Failure updating surface of " + w
8084 + "size=(" + width + "x" + height
8085 + "), pos=(" + w.mShownFrame.left
8086 + "," + w.mShownFrame.top + ")", e);
8087 if (!recoveringMemory) {
8088 reclaimSomeSurfaceMemoryLocked(w, "size");
8089 }
8090 }
8091 }
8092 }
8093 if (!w.mAppFreezing) {
8094 w.mContentInsetsChanged =
8095 !w.mLastContentInsets.equals(w.mContentInsets);
8096 w.mVisibleInsetsChanged =
8097 !w.mLastVisibleInsets.equals(w.mVisibleInsets);
8098 if (!w.mLastFrame.equals(w.mFrame)
8099 || w.mContentInsetsChanged
8100 || w.mVisibleInsetsChanged) {
8101 w.mLastFrame.set(w.mFrame);
8102 w.mLastContentInsets.set(w.mContentInsets);
8103 w.mLastVisibleInsets.set(w.mVisibleInsets);
8104 // If the orientation is changing, then we need to
8105 // hold off on unfreezing the display until this
8106 // window has been redrawn; to do that, we need
8107 // to go through the process of getting informed
8108 // by the application when it has finished drawing.
8109 if (w.mOrientationChanging) {
8110 if (DEBUG_ORIENTATION) Log.v(TAG,
8111 "Orientation start waiting for draw in "
8112 + w + ", surface " + w.mSurface);
8113 w.mDrawPending = true;
8114 w.mCommitDrawPending = false;
8115 w.mReadyToShow = false;
8116 if (w.mAppToken != null) {
8117 w.mAppToken.allDrawn = false;
8118 }
8119 }
8120 if (DEBUG_ORIENTATION) Log.v(TAG,
8121 "Resizing window " + w + " to " + w.mFrame);
8122 mResizingWindows.add(w);
8123 } else if (w.mOrientationChanging) {
8124 if (!w.mDrawPending && !w.mCommitDrawPending) {
8125 if (DEBUG_ORIENTATION) Log.v(TAG,
8126 "Orientation not waiting for draw in "
8127 + w + ", surface " + w.mSurface);
8128 w.mOrientationChanging = false;
8129 }
8130 }
8131 }
8132
8133 if (w.mAttachedHidden) {
8134 if (!w.mLastHidden) {
8135 //dump();
8136 w.mLastHidden = true;
8137 if (SHOW_TRANSACTIONS) Log.i(
8138 TAG, " SURFACE " + w.mSurface + ": HIDE (performLayout-attached)");
8139 if (w.mSurface != null) {
8140 try {
8141 w.mSurface.hide();
8142 } catch (RuntimeException e) {
8143 Log.w(TAG, "Exception hiding surface in " + w);
8144 }
8145 }
8146 mKeyWaiter.releasePendingPointerLocked(w.mSession);
8147 }
8148 // If we are waiting for this window to handle an
8149 // orientation change, well, it is hidden, so
8150 // doesn't really matter. Note that this does
8151 // introduce a potential glitch if the window
8152 // becomes unhidden before it has drawn for the
8153 // new orientation.
8154 if (w.mOrientationChanging) {
8155 w.mOrientationChanging = false;
8156 if (DEBUG_ORIENTATION) Log.v(TAG,
8157 "Orientation change skips hidden " + w);
8158 }
8159 } else if (!w.isReadyForDisplay()) {
8160 if (!w.mLastHidden) {
8161 //dump();
8162 w.mLastHidden = true;
8163 if (SHOW_TRANSACTIONS) Log.i(
8164 TAG, " SURFACE " + w.mSurface + ": HIDE (performLayout-ready)");
8165 if (w.mSurface != null) {
8166 try {
8167 w.mSurface.hide();
8168 } catch (RuntimeException e) {
8169 Log.w(TAG, "Exception exception hiding surface in " + w);
8170 }
8171 }
8172 mKeyWaiter.releasePendingPointerLocked(w.mSession);
8173 }
8174 // If we are waiting for this window to handle an
8175 // orientation change, well, it is hidden, so
8176 // doesn't really matter. Note that this does
8177 // introduce a potential glitch if the window
8178 // becomes unhidden before it has drawn for the
8179 // new orientation.
8180 if (w.mOrientationChanging) {
8181 w.mOrientationChanging = false;
8182 if (DEBUG_ORIENTATION) Log.v(TAG,
8183 "Orientation change skips hidden " + w);
8184 }
8185 } else if (w.mLastLayer != w.mAnimLayer
8186 || w.mLastAlpha != w.mShownAlpha
8187 || w.mLastDsDx != w.mDsDx
8188 || w.mLastDtDx != w.mDtDx
8189 || w.mLastDsDy != w.mDsDy
8190 || w.mLastDtDy != w.mDtDy
8191 || w.mLastHScale != w.mHScale
8192 || w.mLastVScale != w.mVScale
8193 || w.mLastHidden) {
8194 displayed = true;
8195 w.mLastAlpha = w.mShownAlpha;
8196 w.mLastLayer = w.mAnimLayer;
8197 w.mLastDsDx = w.mDsDx;
8198 w.mLastDtDx = w.mDtDx;
8199 w.mLastDsDy = w.mDsDy;
8200 w.mLastDtDy = w.mDtDy;
8201 w.mLastHScale = w.mHScale;
8202 w.mLastVScale = w.mVScale;
8203 if (SHOW_TRANSACTIONS) Log.i(
8204 TAG, " SURFACE " + w.mSurface + ": alpha="
8205 + w.mShownAlpha + " layer=" + w.mAnimLayer);
8206 if (w.mSurface != null) {
8207 try {
8208 w.mSurface.setAlpha(w.mShownAlpha);
8209 w.mSurface.setLayer(w.mAnimLayer);
8210 w.mSurface.setMatrix(
8211 w.mDsDx*w.mHScale, w.mDtDx*w.mVScale,
8212 w.mDsDy*w.mHScale, w.mDtDy*w.mVScale);
8213 } catch (RuntimeException e) {
8214 Log.w(TAG, "Error updating surface in " + w, e);
8215 if (!recoveringMemory) {
8216 reclaimSomeSurfaceMemoryLocked(w, "update");
8217 }
8218 }
8219 }
8220
8221 if (w.mLastHidden && !w.mDrawPending
8222 && !w.mCommitDrawPending
8223 && !w.mReadyToShow) {
8224 if (SHOW_TRANSACTIONS) Log.i(
8225 TAG, " SURFACE " + w.mSurface + ": SHOW (performLayout)");
8226 if (DEBUG_VISIBILITY) Log.v(TAG, "Showing " + w
8227 + " during relayout");
8228 if (showSurfaceRobustlyLocked(w)) {
8229 w.mHasDrawn = true;
8230 w.mLastHidden = false;
8231 } else {
8232 w.mOrientationChanging = false;
8233 }
8234 }
8235 if (w.mSurface != null) {
8236 w.mToken.hasVisible = true;
8237 }
8238 } else {
8239 displayed = true;
8240 }
8241
8242 if (displayed) {
8243 if (!covered) {
8244 if (attrs.width == LayoutParams.FILL_PARENT
8245 && attrs.height == LayoutParams.FILL_PARENT) {
8246 covered = true;
8247 }
8248 }
8249 if (w.mOrientationChanging) {
8250 if (w.mDrawPending || w.mCommitDrawPending) {
8251 orientationChangeComplete = false;
8252 if (DEBUG_ORIENTATION) Log.v(TAG,
8253 "Orientation continue waiting for draw in " + w);
8254 } else {
8255 w.mOrientationChanging = false;
8256 if (DEBUG_ORIENTATION) Log.v(TAG,
8257 "Orientation change complete in " + w);
8258 }
8259 }
8260 w.mToken.hasVisible = true;
8261 }
8262 } else if (w.mOrientationChanging) {
8263 if (DEBUG_ORIENTATION) Log.v(TAG,
8264 "Orientation change skips hidden " + w);
8265 w.mOrientationChanging = false;
8266 }
8267
8268 final boolean canBeSeen = w.isDisplayedLw();
8269
8270 if (someoneLosingFocus && w == mCurrentFocus && canBeSeen) {
8271 focusDisplayed = true;
8272 }
8273
8274 // Update effect.
8275 if (!obscured) {
8276 if (w.mSurface != null) {
8277 if ((attrFlags&FLAG_KEEP_SCREEN_ON) != 0) {
8278 holdScreen = w.mSession;
8279 }
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07008280 if (!syswin && w.mAttrs.screenBrightness >= 0
8281 && screenBrightness < 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008282 screenBrightness = w.mAttrs.screenBrightness;
8283 }
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07008284 if (attrs.type == WindowManager.LayoutParams.TYPE_SYSTEM_DIALOG
8285 || attrs.type == WindowManager.LayoutParams.TYPE_KEYGUARD
8286 || attrs.type == WindowManager.LayoutParams.TYPE_SYSTEM_ERROR) {
8287 syswin = true;
8288 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008289 }
8290 if (w.isFullscreenOpaque(dw, dh)) {
8291 // This window completely covers everything behind it,
8292 // so we want to leave all of them as unblurred (for
8293 // performance reasons).
8294 obscured = true;
8295 } else if (canBeSeen && !obscured &&
8296 (attrFlags&FLAG_BLUR_BEHIND|FLAG_DIM_BEHIND) != 0) {
8297 if (localLOGV) Log.v(TAG, "Win " + w
8298 + ": blurring=" + blurring
8299 + " obscured=" + obscured
8300 + " displayed=" + displayed);
8301 if ((attrFlags&FLAG_DIM_BEHIND) != 0) {
8302 if (!dimming) {
8303 //Log.i(TAG, "DIM BEHIND: " + w);
8304 dimming = true;
8305 mDimShown = true;
8306 if (mDimSurface == null) {
8307 if (SHOW_TRANSACTIONS) Log.i(TAG, " DIM "
8308 + mDimSurface + ": CREATE");
8309 try {
8310 mDimSurface = new Surface(mFxSession, 0,
8311 -1, 16, 16,
8312 PixelFormat.OPAQUE,
8313 Surface.FX_SURFACE_DIM);
8314 } catch (Exception e) {
8315 Log.e(TAG, "Exception creating Dim surface", e);
8316 }
8317 }
8318 if (SHOW_TRANSACTIONS) Log.i(TAG, " DIM "
8319 + mDimSurface + ": SHOW pos=(0,0) (" +
8320 dw + "x" + dh + "), layer=" + (w.mAnimLayer-1));
8321 if (mDimSurface != null) {
8322 try {
8323 mDimSurface.setPosition(0, 0);
8324 mDimSurface.setSize(dw, dh);
8325 mDimSurface.show();
8326 } catch (RuntimeException e) {
8327 Log.w(TAG, "Failure showing dim surface", e);
8328 }
8329 }
8330 }
8331 mDimSurface.setLayer(w.mAnimLayer-1);
8332 final float target = w.mExiting ? 0 : attrs.dimAmount;
8333 if (mDimTargetAlpha != target) {
8334 // If the desired dim level has changed, then
8335 // start an animation to it.
8336 mLastDimAnimTime = currentTime;
8337 long duration = (w.mAnimating && w.mAnimation != null)
8338 ? w.mAnimation.computeDurationHint()
8339 : DEFAULT_DIM_DURATION;
8340 if (target > mDimTargetAlpha) {
8341 // This is happening behind the activity UI,
8342 // so we can make it run a little longer to
8343 // give a stronger impression without disrupting
8344 // the user.
8345 duration *= DIM_DURATION_MULTIPLIER;
8346 }
8347 if (duration < 1) {
8348 // Don't divide by zero
8349 duration = 1;
8350 }
8351 mDimTargetAlpha = target;
8352 mDimDeltaPerMs = (mDimTargetAlpha-mDimCurrentAlpha)
8353 / duration;
8354 }
8355 }
8356 if ((attrFlags&FLAG_BLUR_BEHIND) != 0) {
8357 if (!blurring) {
8358 //Log.i(TAG, "BLUR BEHIND: " + w);
8359 blurring = true;
8360 mBlurShown = true;
8361 if (mBlurSurface == null) {
8362 if (SHOW_TRANSACTIONS) Log.i(TAG, " BLUR "
8363 + mBlurSurface + ": CREATE");
8364 try {
8365 mBlurSurface = new Surface(mFxSession, 0,
8366 -1, 16, 16,
8367 PixelFormat.OPAQUE,
8368 Surface.FX_SURFACE_BLUR);
8369 } catch (Exception e) {
8370 Log.e(TAG, "Exception creating Blur surface", e);
8371 }
8372 }
8373 if (SHOW_TRANSACTIONS) Log.i(TAG, " BLUR "
8374 + mBlurSurface + ": SHOW pos=(0,0) (" +
8375 dw + "x" + dh + "), layer=" + (w.mAnimLayer-1));
8376 if (mBlurSurface != null) {
8377 mBlurSurface.setPosition(0, 0);
8378 mBlurSurface.setSize(dw, dh);
8379 try {
8380 mBlurSurface.show();
8381 } catch (RuntimeException e) {
8382 Log.w(TAG, "Failure showing blur surface", e);
8383 }
8384 }
8385 }
8386 mBlurSurface.setLayer(w.mAnimLayer-2);
8387 }
8388 }
8389 }
8390 }
8391
8392 if (!dimming && mDimShown) {
8393 // Time to hide the dim surface... start fading.
8394 if (mDimTargetAlpha != 0) {
8395 mLastDimAnimTime = currentTime;
8396 mDimTargetAlpha = 0;
8397 mDimDeltaPerMs = (-mDimCurrentAlpha) / DEFAULT_DIM_DURATION;
8398 }
8399 }
8400
8401 if (mDimShown && mLastDimAnimTime != 0) {
8402 mDimCurrentAlpha += mDimDeltaPerMs
8403 * (currentTime-mLastDimAnimTime);
8404 boolean more = true;
8405 if (mDisplayFrozen) {
8406 // If the display is frozen, there is no reason to animate.
8407 more = false;
8408 } else if (mDimDeltaPerMs > 0) {
8409 if (mDimCurrentAlpha > mDimTargetAlpha) {
8410 more = false;
8411 }
8412 } else if (mDimDeltaPerMs < 0) {
8413 if (mDimCurrentAlpha < mDimTargetAlpha) {
8414 more = false;
8415 }
8416 } else {
8417 more = false;
8418 }
8419
8420 // Do we need to continue animating?
8421 if (more) {
8422 if (SHOW_TRANSACTIONS) Log.i(TAG, " DIM "
8423 + mDimSurface + ": alpha=" + mDimCurrentAlpha);
8424 mLastDimAnimTime = currentTime;
8425 mDimSurface.setAlpha(mDimCurrentAlpha);
8426 animating = true;
8427 } else {
8428 mDimCurrentAlpha = mDimTargetAlpha;
8429 mLastDimAnimTime = 0;
8430 if (SHOW_TRANSACTIONS) Log.i(TAG, " DIM "
8431 + mDimSurface + ": final alpha=" + mDimCurrentAlpha);
8432 mDimSurface.setAlpha(mDimCurrentAlpha);
8433 if (!dimming) {
8434 if (SHOW_TRANSACTIONS) Log.i(TAG, " DIM " + mDimSurface
8435 + ": HIDE");
8436 try {
8437 mDimSurface.hide();
8438 } catch (RuntimeException e) {
8439 Log.w(TAG, "Illegal argument exception hiding dim surface");
8440 }
8441 mDimShown = false;
8442 }
8443 }
8444 }
8445
8446 if (!blurring && mBlurShown) {
8447 if (SHOW_TRANSACTIONS) Log.i(TAG, " BLUR " + mBlurSurface
8448 + ": HIDE");
8449 try {
8450 mBlurSurface.hide();
8451 } catch (IllegalArgumentException e) {
8452 Log.w(TAG, "Illegal argument exception hiding blur surface");
8453 }
8454 mBlurShown = false;
8455 }
8456
8457 if (SHOW_TRANSACTIONS) Log.i(TAG, "<<< CLOSE TRANSACTION");
8458 } catch (RuntimeException e) {
8459 Log.e(TAG, "Unhandled exception in Window Manager", e);
8460 }
8461
8462 Surface.closeTransaction();
8463
8464 if (DEBUG_ORIENTATION && mDisplayFrozen) Log.v(TAG,
8465 "With display frozen, orientationChangeComplete="
8466 + orientationChangeComplete);
8467 if (orientationChangeComplete) {
8468 if (mWindowsFreezingScreen) {
8469 mWindowsFreezingScreen = false;
8470 mH.removeMessages(H.WINDOW_FREEZE_TIMEOUT);
8471 }
8472 if (mAppsFreezingScreen == 0) {
8473 stopFreezingDisplayLocked();
8474 }
8475 }
8476
8477 i = mResizingWindows.size();
8478 if (i > 0) {
8479 do {
8480 i--;
8481 WindowState win = mResizingWindows.get(i);
8482 try {
8483 win.mClient.resized(win.mFrame.width(),
8484 win.mFrame.height(), win.mLastContentInsets,
8485 win.mLastVisibleInsets, win.mDrawPending);
8486 win.mContentInsetsChanged = false;
8487 win.mVisibleInsetsChanged = false;
8488 } catch (RemoteException e) {
8489 win.mOrientationChanging = false;
8490 }
8491 } while (i > 0);
8492 mResizingWindows.clear();
8493 }
8494
8495 // Destroy the surface of any windows that are no longer visible.
8496 i = mDestroySurface.size();
8497 if (i > 0) {
8498 do {
8499 i--;
8500 WindowState win = mDestroySurface.get(i);
8501 win.mDestroying = false;
8502 if (mInputMethodWindow == win) {
8503 mInputMethodWindow = null;
8504 }
8505 win.destroySurfaceLocked();
8506 } while (i > 0);
8507 mDestroySurface.clear();
8508 }
8509
8510 // Time to remove any exiting tokens?
8511 for (i=mExitingTokens.size()-1; i>=0; i--) {
8512 WindowToken token = mExitingTokens.get(i);
8513 if (!token.hasVisible) {
8514 mExitingTokens.remove(i);
8515 }
8516 }
8517
8518 // Time to remove any exiting applications?
8519 for (i=mExitingAppTokens.size()-1; i>=0; i--) {
8520 AppWindowToken token = mExitingAppTokens.get(i);
8521 if (!token.hasVisible && !mClosingApps.contains(token)) {
8522 mAppTokens.remove(token);
8523 mExitingAppTokens.remove(i);
8524 }
8525 }
8526
8527 if (focusDisplayed) {
8528 mH.sendEmptyMessage(H.REPORT_LOSING_FOCUS);
8529 }
8530 if (animating) {
8531 requestAnimationLocked(currentTime+(1000/60)-SystemClock.uptimeMillis());
8532 }
8533 mQueue.setHoldScreenLocked(holdScreen != null);
8534 if (screenBrightness < 0 || screenBrightness > 1.0f) {
8535 mPowerManager.setScreenBrightnessOverride(-1);
8536 } else {
8537 mPowerManager.setScreenBrightnessOverride((int)
8538 (screenBrightness * Power.BRIGHTNESS_ON));
8539 }
8540 if (holdScreen != mHoldingScreenOn) {
8541 mHoldingScreenOn = holdScreen;
8542 Message m = mH.obtainMessage(H.HOLD_SCREEN_CHANGED, holdScreen);
8543 mH.sendMessage(m);
8544 }
8545 }
8546
8547 void requestAnimationLocked(long delay) {
8548 if (!mAnimationPending) {
8549 mAnimationPending = true;
8550 mH.sendMessageDelayed(mH.obtainMessage(H.ANIMATE), delay);
8551 }
8552 }
8553
8554 /**
8555 * Have the surface flinger show a surface, robustly dealing with
8556 * error conditions. In particular, if there is not enough memory
8557 * to show the surface, then we will try to get rid of other surfaces
8558 * in order to succeed.
8559 *
8560 * @return Returns true if the surface was successfully shown.
8561 */
8562 boolean showSurfaceRobustlyLocked(WindowState win) {
8563 try {
8564 if (win.mSurface != null) {
8565 win.mSurface.show();
8566 }
8567 return true;
8568 } catch (RuntimeException e) {
8569 Log.w(TAG, "Failure showing surface " + win.mSurface + " in " + win);
8570 }
8571
8572 reclaimSomeSurfaceMemoryLocked(win, "show");
8573
8574 return false;
8575 }
8576
8577 void reclaimSomeSurfaceMemoryLocked(WindowState win, String operation) {
8578 final Surface surface = win.mSurface;
8579
8580 EventLog.writeEvent(LOG_WM_NO_SURFACE_MEMORY, win.toString(),
8581 win.mSession.mPid, operation);
8582
8583 if (mForceRemoves == null) {
8584 mForceRemoves = new ArrayList<WindowState>();
8585 }
8586
8587 long callingIdentity = Binder.clearCallingIdentity();
8588 try {
8589 // There was some problem... first, do a sanity check of the
8590 // window list to make sure we haven't left any dangling surfaces
8591 // around.
8592 int N = mWindows.size();
8593 boolean leakedSurface = false;
8594 Log.i(TAG, "Out of memory for surface! Looking for leaks...");
8595 for (int i=0; i<N; i++) {
8596 WindowState ws = (WindowState)mWindows.get(i);
8597 if (ws.mSurface != null) {
8598 if (!mSessions.contains(ws.mSession)) {
8599 Log.w(TAG, "LEAKED SURFACE (session doesn't exist): "
8600 + ws + " surface=" + ws.mSurface
8601 + " token=" + win.mToken
8602 + " pid=" + ws.mSession.mPid
8603 + " uid=" + ws.mSession.mUid);
8604 ws.mSurface.clear();
8605 ws.mSurface = null;
8606 mForceRemoves.add(ws);
8607 i--;
8608 N--;
8609 leakedSurface = true;
8610 } else if (win.mAppToken != null && win.mAppToken.clientHidden) {
8611 Log.w(TAG, "LEAKED SURFACE (app token hidden): "
8612 + ws + " surface=" + ws.mSurface
8613 + " token=" + win.mAppToken);
8614 ws.mSurface.clear();
8615 ws.mSurface = null;
8616 leakedSurface = true;
8617 }
8618 }
8619 }
8620
8621 boolean killedApps = false;
8622 if (!leakedSurface) {
8623 Log.w(TAG, "No leaked surfaces; killing applicatons!");
8624 SparseIntArray pidCandidates = new SparseIntArray();
8625 for (int i=0; i<N; i++) {
8626 WindowState ws = (WindowState)mWindows.get(i);
8627 if (ws.mSurface != null) {
8628 pidCandidates.append(ws.mSession.mPid, ws.mSession.mPid);
8629 }
8630 }
8631 if (pidCandidates.size() > 0) {
8632 int[] pids = new int[pidCandidates.size()];
8633 for (int i=0; i<pids.length; i++) {
8634 pids[i] = pidCandidates.keyAt(i);
8635 }
8636 try {
8637 if (mActivityManager.killPidsForMemory(pids)) {
8638 killedApps = true;
8639 }
8640 } catch (RemoteException e) {
8641 }
8642 }
8643 }
8644
8645 if (leakedSurface || killedApps) {
8646 // We managed to reclaim some memory, so get rid of the trouble
8647 // surface and ask the app to request another one.
8648 Log.w(TAG, "Looks like we have reclaimed some memory, clearing surface for retry.");
8649 if (surface != null) {
8650 surface.clear();
8651 win.mSurface = null;
8652 }
8653
8654 try {
8655 win.mClient.dispatchGetNewSurface();
8656 } catch (RemoteException e) {
8657 }
8658 }
8659 } finally {
8660 Binder.restoreCallingIdentity(callingIdentity);
8661 }
8662 }
8663
8664 private boolean updateFocusedWindowLocked(int mode) {
8665 WindowState newFocus = computeFocusedWindowLocked();
8666 if (mCurrentFocus != newFocus) {
8667 // This check makes sure that we don't already have the focus
8668 // change message pending.
8669 mH.removeMessages(H.REPORT_FOCUS_CHANGE);
8670 mH.sendEmptyMessage(H.REPORT_FOCUS_CHANGE);
8671 if (localLOGV) Log.v(
8672 TAG, "Changing focus from " + mCurrentFocus + " to " + newFocus);
8673 final WindowState oldFocus = mCurrentFocus;
8674 mCurrentFocus = newFocus;
8675 mLosingFocus.remove(newFocus);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008676
8677 final WindowState imWindow = mInputMethodWindow;
8678 if (newFocus != imWindow && oldFocus != imWindow) {
The Android Open Source Projectc474dec2009-03-04 09:49:09 -08008679 if (moveInputMethodWindowsIfNeededLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008680 mode != UPDATE_FOCUS_WILL_ASSIGN_LAYERS &&
The Android Open Source Projectc474dec2009-03-04 09:49:09 -08008681 mode != UPDATE_FOCUS_WILL_PLACE_SURFACES)) {
8682 mLayoutNeeded = true;
8683 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008684 if (mode == UPDATE_FOCUS_PLACING_SURFACES) {
8685 performLayoutLockedInner();
The Android Open Source Projectc474dec2009-03-04 09:49:09 -08008686 } else if (mode == UPDATE_FOCUS_WILL_PLACE_SURFACES) {
8687 // Client will do the layout, but we need to assign layers
8688 // for handleNewWindowLocked() below.
8689 assignLayersLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008690 }
8691 }
The Android Open Source Projectc474dec2009-03-04 09:49:09 -08008692
8693 if (newFocus != null && mode != UPDATE_FOCUS_WILL_ASSIGN_LAYERS) {
8694 mKeyWaiter.handleNewWindowLocked(newFocus);
8695 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008696 return true;
8697 }
8698 return false;
8699 }
8700
8701 private WindowState computeFocusedWindowLocked() {
8702 WindowState result = null;
8703 WindowState win;
8704
8705 int i = mWindows.size() - 1;
8706 int nextAppIndex = mAppTokens.size()-1;
8707 WindowToken nextApp = nextAppIndex >= 0
8708 ? mAppTokens.get(nextAppIndex) : null;
8709
8710 while (i >= 0) {
8711 win = (WindowState)mWindows.get(i);
8712
8713 if (localLOGV || DEBUG_FOCUS) Log.v(
8714 TAG, "Looking for focus: " + i
8715 + " = " + win
8716 + ", flags=" + win.mAttrs.flags
8717 + ", canReceive=" + win.canReceiveKeys());
8718
8719 AppWindowToken thisApp = win.mAppToken;
8720
8721 // If this window's application has been removed, just skip it.
8722 if (thisApp != null && thisApp.removed) {
8723 i--;
8724 continue;
8725 }
8726
8727 // If there is a focused app, don't allow focus to go to any
8728 // windows below it. If this is an application window, step
8729 // through the app tokens until we find its app.
8730 if (thisApp != null && nextApp != null && thisApp != nextApp
8731 && win.mAttrs.type != TYPE_APPLICATION_STARTING) {
8732 int origAppIndex = nextAppIndex;
8733 while (nextAppIndex > 0) {
8734 if (nextApp == mFocusedApp) {
8735 // Whoops, we are below the focused app... no focus
8736 // for you!
8737 if (localLOGV || DEBUG_FOCUS) Log.v(
8738 TAG, "Reached focused app: " + mFocusedApp);
8739 return null;
8740 }
8741 nextAppIndex--;
8742 nextApp = mAppTokens.get(nextAppIndex);
8743 if (nextApp == thisApp) {
8744 break;
8745 }
8746 }
8747 if (thisApp != nextApp) {
8748 // Uh oh, the app token doesn't exist! This shouldn't
8749 // happen, but if it does we can get totally hosed...
8750 // so restart at the original app.
8751 nextAppIndex = origAppIndex;
8752 nextApp = mAppTokens.get(nextAppIndex);
8753 }
8754 }
8755
8756 // Dispatch to this window if it is wants key events.
8757 if (win.canReceiveKeys()) {
8758 if (DEBUG_FOCUS) Log.v(
8759 TAG, "Found focus @ " + i + " = " + win);
8760 result = win;
8761 break;
8762 }
8763
8764 i--;
8765 }
8766
8767 return result;
8768 }
8769
8770 private void startFreezingDisplayLocked() {
8771 if (mDisplayFrozen) {
Chris Tate2ad63a92009-03-25 17:36:48 -07008772 // Freezing the display also suspends key event delivery, to
8773 // keep events from going astray while the display is reconfigured.
8774 // If someone has changed orientation again while the screen is
8775 // still frozen, the events will continue to be blocked while the
8776 // successive orientation change is processed. To prevent spurious
8777 // ANRs, we reset the event dispatch timeout in this case.
8778 synchronized (mKeyWaiter) {
8779 mKeyWaiter.mWasFrozen = true;
8780 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008781 return;
8782 }
8783
8784 mScreenFrozenLock.acquire();
8785
8786 long now = SystemClock.uptimeMillis();
8787 //Log.i(TAG, "Freezing, gc pending: " + mFreezeGcPending + ", now " + now);
8788 if (mFreezeGcPending != 0) {
8789 if (now > (mFreezeGcPending+1000)) {
8790 //Log.i(TAG, "Gc! " + now + " > " + (mFreezeGcPending+1000));
8791 mH.removeMessages(H.FORCE_GC);
8792 Runtime.getRuntime().gc();
8793 mFreezeGcPending = now;
8794 }
8795 } else {
8796 mFreezeGcPending = now;
8797 }
8798
8799 mDisplayFrozen = true;
8800 if (mNextAppTransition != WindowManagerPolicy.TRANSIT_NONE) {
8801 mNextAppTransition = WindowManagerPolicy.TRANSIT_NONE;
8802 mAppTransitionReady = true;
8803 }
8804
8805 if (PROFILE_ORIENTATION) {
8806 File file = new File("/data/system/frozen");
8807 Debug.startMethodTracing(file.toString(), 8 * 1024 * 1024);
8808 }
8809 Surface.freezeDisplay(0);
8810 }
8811
8812 private void stopFreezingDisplayLocked() {
8813 if (!mDisplayFrozen) {
8814 return;
8815 }
8816
8817 mDisplayFrozen = false;
8818 mH.removeMessages(H.APP_FREEZE_TIMEOUT);
8819 if (PROFILE_ORIENTATION) {
8820 Debug.stopMethodTracing();
8821 }
8822 Surface.unfreezeDisplay(0);
8823
Chris Tate2ad63a92009-03-25 17:36:48 -07008824 // Reset the key delivery timeout on unfreeze, too. We force a wakeup here
8825 // too because regular key delivery processing should resume immediately.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008826 synchronized (mKeyWaiter) {
8827 mKeyWaiter.mWasFrozen = true;
8828 mKeyWaiter.notifyAll();
8829 }
8830
8831 // A little kludge: a lot could have happened while the
8832 // display was frozen, so now that we are coming back we
8833 // do a gc so that any remote references the system
8834 // processes holds on others can be released if they are
8835 // no longer needed.
8836 mH.removeMessages(H.FORCE_GC);
8837 mH.sendMessageDelayed(mH.obtainMessage(H.FORCE_GC),
8838 2000);
8839
8840 mScreenFrozenLock.release();
8841 }
8842
8843 @Override
8844 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
8845 if (mContext.checkCallingOrSelfPermission("android.permission.DUMP")
8846 != PackageManager.PERMISSION_GRANTED) {
8847 pw.println("Permission Denial: can't dump WindowManager from from pid="
8848 + Binder.getCallingPid()
8849 + ", uid=" + Binder.getCallingUid());
8850 return;
8851 }
8852
8853 synchronized(mWindowMap) {
8854 pw.println("Current Window Manager state:");
8855 for (int i=mWindows.size()-1; i>=0; i--) {
8856 WindowState w = (WindowState)mWindows.get(i);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008857 pw.print(" Window #"); pw.print(i); pw.print(' ');
8858 pw.print(w); pw.println(":");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008859 w.dump(pw, " ");
8860 }
8861 if (mInputMethodDialogs.size() > 0) {
8862 pw.println(" ");
8863 pw.println(" Input method dialogs:");
8864 for (int i=mInputMethodDialogs.size()-1; i>=0; i--) {
8865 WindowState w = mInputMethodDialogs.get(i);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008866 pw.print(" IM Dialog #"); pw.print(i); pw.print(": "); pw.println(w);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008867 }
8868 }
8869 if (mPendingRemove.size() > 0) {
8870 pw.println(" ");
8871 pw.println(" Remove pending for:");
8872 for (int i=mPendingRemove.size()-1; i>=0; i--) {
8873 WindowState w = mPendingRemove.get(i);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008874 pw.print(" Remove #"); pw.print(i); pw.print(' ');
8875 pw.print(w); pw.println(":");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008876 w.dump(pw, " ");
8877 }
8878 }
8879 if (mForceRemoves != null && mForceRemoves.size() > 0) {
8880 pw.println(" ");
8881 pw.println(" Windows force removing:");
8882 for (int i=mForceRemoves.size()-1; i>=0; i--) {
8883 WindowState w = mForceRemoves.get(i);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008884 pw.print(" Removing #"); pw.print(i); pw.print(' ');
8885 pw.print(w); pw.println(":");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008886 w.dump(pw, " ");
8887 }
8888 }
8889 if (mDestroySurface.size() > 0) {
8890 pw.println(" ");
8891 pw.println(" Windows waiting to destroy their surface:");
8892 for (int i=mDestroySurface.size()-1; i>=0; i--) {
8893 WindowState w = mDestroySurface.get(i);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008894 pw.print(" Destroy #"); pw.print(i); pw.print(' ');
8895 pw.print(w); pw.println(":");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008896 w.dump(pw, " ");
8897 }
8898 }
8899 if (mLosingFocus.size() > 0) {
8900 pw.println(" ");
8901 pw.println(" Windows losing focus:");
8902 for (int i=mLosingFocus.size()-1; i>=0; i--) {
8903 WindowState w = mLosingFocus.get(i);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008904 pw.print(" Losing #"); pw.print(i); pw.print(' ');
8905 pw.print(w); pw.println(":");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008906 w.dump(pw, " ");
8907 }
8908 }
8909 if (mSessions.size() > 0) {
8910 pw.println(" ");
8911 pw.println(" All active sessions:");
8912 Iterator<Session> it = mSessions.iterator();
8913 while (it.hasNext()) {
8914 Session s = it.next();
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008915 pw.print(" Session "); pw.print(s); pw.println(':');
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008916 s.dump(pw, " ");
8917 }
8918 }
8919 if (mTokenMap.size() > 0) {
8920 pw.println(" ");
8921 pw.println(" All tokens:");
8922 Iterator<WindowToken> it = mTokenMap.values().iterator();
8923 while (it.hasNext()) {
8924 WindowToken token = it.next();
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008925 pw.print(" Token "); pw.print(token.token); pw.println(':');
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008926 token.dump(pw, " ");
8927 }
8928 }
8929 if (mTokenList.size() > 0) {
8930 pw.println(" ");
8931 pw.println(" Window token list:");
8932 for (int i=0; i<mTokenList.size(); i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008933 pw.print(" #"); pw.print(i); pw.print(": ");
8934 pw.println(mTokenList.get(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008935 }
8936 }
8937 if (mAppTokens.size() > 0) {
8938 pw.println(" ");
8939 pw.println(" Application tokens in Z order:");
8940 for (int i=mAppTokens.size()-1; i>=0; i--) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008941 pw.print(" App #"); pw.print(i); pw.print(": ");
8942 pw.println(mAppTokens.get(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008943 }
8944 }
8945 if (mFinishedStarting.size() > 0) {
8946 pw.println(" ");
8947 pw.println(" Finishing start of application tokens:");
8948 for (int i=mFinishedStarting.size()-1; i>=0; i--) {
8949 WindowToken token = mFinishedStarting.get(i);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008950 pw.print(" Finished Starting #"); pw.print(i);
8951 pw.print(' '); pw.print(token); pw.println(':');
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008952 token.dump(pw, " ");
8953 }
8954 }
8955 if (mExitingTokens.size() > 0) {
8956 pw.println(" ");
8957 pw.println(" Exiting tokens:");
8958 for (int i=mExitingTokens.size()-1; i>=0; i--) {
8959 WindowToken token = mExitingTokens.get(i);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008960 pw.print(" Exiting #"); pw.print(i);
8961 pw.print(' '); pw.print(token); pw.println(':');
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008962 token.dump(pw, " ");
8963 }
8964 }
8965 if (mExitingAppTokens.size() > 0) {
8966 pw.println(" ");
8967 pw.println(" Exiting application tokens:");
8968 for (int i=mExitingAppTokens.size()-1; i>=0; i--) {
8969 WindowToken token = mExitingAppTokens.get(i);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008970 pw.print(" Exiting App #"); pw.print(i);
8971 pw.print(' '); pw.print(token); pw.println(':');
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008972 token.dump(pw, " ");
8973 }
8974 }
8975 pw.println(" ");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008976 pw.print(" mCurrentFocus="); pw.println(mCurrentFocus);
8977 pw.print(" mLastFocus="); pw.println(mLastFocus);
8978 pw.print(" mFocusedApp="); pw.println(mFocusedApp);
8979 pw.print(" mInputMethodTarget="); pw.println(mInputMethodTarget);
8980 pw.print(" mInputMethodWindow="); pw.println(mInputMethodWindow);
8981 pw.print(" mInTouchMode="); pw.println(mInTouchMode);
8982 pw.print(" mSystemBooted="); pw.print(mSystemBooted);
8983 pw.print(" mDisplayEnabled="); pw.println(mDisplayEnabled);
8984 pw.print(" mLayoutNeeded="); pw.print(mLayoutNeeded);
8985 pw.print(" mBlurShown="); pw.println(mBlurShown);
8986 pw.print(" mDimShown="); pw.print(mDimShown);
8987 pw.print(" current="); pw.print(mDimCurrentAlpha);
8988 pw.print(" target="); pw.print(mDimTargetAlpha);
8989 pw.print(" delta="); pw.print(mDimDeltaPerMs);
8990 pw.print(" lastAnimTime="); pw.println(mLastDimAnimTime);
8991 pw.print(" mInputMethodAnimLayerAdjustment=");
8992 pw.println(mInputMethodAnimLayerAdjustment);
8993 pw.print(" mDisplayFrozen="); pw.print(mDisplayFrozen);
8994 pw.print(" mWindowsFreezingScreen="); pw.print(mWindowsFreezingScreen);
8995 pw.print(" mAppsFreezingScreen="); pw.println(mAppsFreezingScreen);
8996 pw.print(" mRotation="); pw.print(mRotation);
8997 pw.print(", mForcedAppOrientation="); pw.print(mForcedAppOrientation);
8998 pw.print(", mRequestedRotation="); pw.println(mRequestedRotation);
8999 pw.print(" mAnimationPending="); pw.print(mAnimationPending);
9000 pw.print(" mWindowAnimationScale="); pw.print(mWindowAnimationScale);
9001 pw.print(" mTransitionWindowAnimationScale="); pw.println(mTransitionAnimationScale);
9002 pw.print(" mNextAppTransition=0x");
9003 pw.print(Integer.toHexString(mNextAppTransition));
9004 pw.print(", mAppTransitionReady="); pw.print(mAppTransitionReady);
9005 pw.print(", mAppTransitionTimeout="); pw.println( mAppTransitionTimeout);
9006 pw.print(" mStartingIconInTransition="); pw.print(mStartingIconInTransition);
9007 pw.print(", mSkipAppTransitionAnimation="); pw.println(mSkipAppTransitionAnimation);
9008 if (mOpeningApps.size() > 0) {
9009 pw.print(" mOpeningApps="); pw.println(mOpeningApps);
9010 }
9011 if (mClosingApps.size() > 0) {
9012 pw.print(" mClosingApps="); pw.println(mClosingApps);
9013 }
9014 pw.print(" DisplayWidth="); pw.print(mDisplay.getWidth());
9015 pw.print(" DisplayHeight="); pw.println(mDisplay.getHeight());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009016 pw.println(" KeyWaiter state:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009017 pw.print(" mLastWin="); pw.print(mKeyWaiter.mLastWin);
9018 pw.print(" mLastBinder="); pw.println(mKeyWaiter.mLastBinder);
9019 pw.print(" mFinished="); pw.print(mKeyWaiter.mFinished);
9020 pw.print(" mGotFirstWindow="); pw.print(mKeyWaiter.mGotFirstWindow);
9021 pw.print(" mEventDispatching="); pw.print(mKeyWaiter.mEventDispatching);
9022 pw.print(" mTimeToSwitch="); pw.println(mKeyWaiter.mTimeToSwitch);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009023 }
9024 }
9025
9026 public void monitor() {
9027 synchronized (mWindowMap) { }
9028 synchronized (mKeyguardDisabled) { }
9029 synchronized (mKeyWaiter) { }
9030 }
9031}