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