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