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