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