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