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