blob: ed8b23af35520a45422a8ff4c21a4b255a1964c8 [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(
2169 WindowManagerPolicy.USE_LAST_ROTATION);
2170 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.
3261 setRotationUnchecked(WindowManagerPolicy.USE_LAST_ROTATION, false);
3262 }
3263
3264 public void setInTouchMode(boolean mode) {
3265 synchronized(mWindowMap) {
3266 mInTouchMode = mode;
3267 }
3268 }
3269
3270 public void setRotation(int rotation,
3271 boolean alwaysSendConfiguration) {
3272 if (!checkCallingPermission(android.Manifest.permission.SET_ORIENTATION,
3273 "setOrientation()")) {
3274 return;
3275 }
3276
3277 setRotationUnchecked(rotation, alwaysSendConfiguration);
3278 }
3279
3280 public void setRotationUnchecked(int rotation, boolean alwaysSendConfiguration) {
3281 if(DEBUG_ORIENTATION) Log.v(TAG,
3282 "alwaysSendConfiguration set to "+alwaysSendConfiguration);
3283
3284 long origId = Binder.clearCallingIdentity();
3285 boolean changed;
3286 synchronized(mWindowMap) {
3287 changed = setRotationUncheckedLocked(rotation);
3288 }
3289
3290 if (changed) {
3291 sendNewConfiguration();
3292 synchronized(mWindowMap) {
3293 mLayoutNeeded = true;
3294 performLayoutAndPlaceSurfacesLocked();
3295 }
3296 } else if (alwaysSendConfiguration) {
3297 //update configuration ignoring orientation change
3298 sendNewConfiguration();
3299 }
3300
3301 Binder.restoreCallingIdentity(origId);
3302 }
3303
3304 public boolean setRotationUncheckedLocked(int rotation) {
3305 boolean changed;
3306 if (rotation == WindowManagerPolicy.USE_LAST_ROTATION) {
3307 rotation = mRequestedRotation;
3308 } else {
3309 mRequestedRotation = rotation;
3310 }
3311 if (DEBUG_ORIENTATION) Log.v(TAG, "Overwriting rotation value from " + rotation);
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07003312 rotation = mPolicy.rotationForOrientationLw(mForcedAppOrientation,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003313 mRotation, mDisplayEnabled);
3314 if (DEBUG_ORIENTATION) Log.v(TAG, "new rotation is set to " + rotation);
3315 changed = mDisplayEnabled && mRotation != rotation;
3316
3317 if (changed) {
3318 if (DEBUG_ORIENTATION) Log.v(TAG,
3319 "Rotation changed to " + rotation
3320 + " from " + mRotation
3321 + " (forceApp=" + mForcedAppOrientation
3322 + ", req=" + mRequestedRotation + ")");
3323 mRotation = rotation;
3324 mWindowsFreezingScreen = true;
3325 mH.removeMessages(H.WINDOW_FREEZE_TIMEOUT);
3326 mH.sendMessageDelayed(mH.obtainMessage(H.WINDOW_FREEZE_TIMEOUT),
3327 2000);
3328 startFreezingDisplayLocked();
3329 mQueue.setOrientation(rotation);
3330 if (mDisplayEnabled) {
3331 Surface.setOrientation(0, rotation);
3332 }
3333 for (int i=mWindows.size()-1; i>=0; i--) {
3334 WindowState w = (WindowState)mWindows.get(i);
3335 if (w.mSurface != null) {
3336 w.mOrientationChanging = true;
3337 }
3338 }
3339 for (int i=mRotationWatchers.size()-1; i>=0; i--) {
3340 try {
3341 mRotationWatchers.get(i).onRotationChanged(rotation);
3342 } catch (RemoteException e) {
3343 }
3344 }
3345 } //end if changed
3346
3347 return changed;
3348 }
3349
3350 public int getRotation() {
3351 return mRotation;
3352 }
3353
3354 public int watchRotation(IRotationWatcher watcher) {
3355 final IBinder watcherBinder = watcher.asBinder();
3356 IBinder.DeathRecipient dr = new IBinder.DeathRecipient() {
3357 public void binderDied() {
3358 synchronized (mWindowMap) {
3359 for (int i=0; i<mRotationWatchers.size(); i++) {
3360 if (watcherBinder == mRotationWatchers.get(i).asBinder()) {
3361 mRotationWatchers.remove(i);
3362 i--;
3363 }
3364 }
3365 }
3366 }
3367 };
3368
3369 synchronized (mWindowMap) {
3370 try {
3371 watcher.asBinder().linkToDeath(dr, 0);
3372 mRotationWatchers.add(watcher);
3373 } catch (RemoteException e) {
3374 // Client died, no cleanup needed.
3375 }
3376
3377 return mRotation;
3378 }
3379 }
3380
3381 /**
3382 * Starts the view server on the specified port.
3383 *
3384 * @param port The port to listener to.
3385 *
3386 * @return True if the server was successfully started, false otherwise.
3387 *
3388 * @see com.android.server.ViewServer
3389 * @see com.android.server.ViewServer#VIEW_SERVER_DEFAULT_PORT
3390 */
3391 public boolean startViewServer(int port) {
3392 if ("1".equals(SystemProperties.get(SYSTEM_SECURE, "0"))) {
3393 return false;
3394 }
3395
3396 if (!checkCallingPermission(Manifest.permission.DUMP, "startViewServer")) {
3397 return false;
3398 }
3399
3400 if (port < 1024) {
3401 return false;
3402 }
3403
3404 if (mViewServer != null) {
3405 if (!mViewServer.isRunning()) {
3406 try {
3407 return mViewServer.start();
3408 } catch (IOException e) {
3409 Log.w(TAG, "View server did not start");
3410 }
3411 }
3412 return false;
3413 }
3414
3415 try {
3416 mViewServer = new ViewServer(this, port);
3417 return mViewServer.start();
3418 } catch (IOException e) {
3419 Log.w(TAG, "View server did not start");
3420 }
3421 return false;
3422 }
3423
3424 /**
3425 * Stops the view server if it exists.
3426 *
3427 * @return True if the server stopped, false if it wasn't started or
3428 * couldn't be stopped.
3429 *
3430 * @see com.android.server.ViewServer
3431 */
3432 public boolean stopViewServer() {
3433 if ("1".equals(SystemProperties.get(SYSTEM_SECURE, "0"))) {
3434 return false;
3435 }
3436
3437 if (!checkCallingPermission(Manifest.permission.DUMP, "stopViewServer")) {
3438 return false;
3439 }
3440
3441 if (mViewServer != null) {
3442 return mViewServer.stop();
3443 }
3444 return false;
3445 }
3446
3447 /**
3448 * Indicates whether the view server is running.
3449 *
3450 * @return True if the server is running, false otherwise.
3451 *
3452 * @see com.android.server.ViewServer
3453 */
3454 public boolean isViewServerRunning() {
3455 if ("1".equals(SystemProperties.get(SYSTEM_SECURE, "0"))) {
3456 return false;
3457 }
3458
3459 if (!checkCallingPermission(Manifest.permission.DUMP, "isViewServerRunning")) {
3460 return false;
3461 }
3462
3463 return mViewServer != null && mViewServer.isRunning();
3464 }
3465
3466 /**
3467 * Lists all availble windows in the system. The listing is written in the
3468 * specified Socket's output stream with the following syntax:
3469 * windowHashCodeInHexadecimal windowName
3470 * Each line of the ouput represents a different window.
3471 *
3472 * @param client The remote client to send the listing to.
3473 * @return False if an error occured, true otherwise.
3474 */
3475 boolean viewServerListWindows(Socket client) {
3476 if ("1".equals(SystemProperties.get(SYSTEM_SECURE, "0"))) {
3477 return false;
3478 }
3479
3480 boolean result = true;
3481
3482 Object[] windows;
3483 synchronized (mWindowMap) {
3484 windows = new Object[mWindows.size()];
3485 //noinspection unchecked
3486 windows = mWindows.toArray(windows);
3487 }
3488
3489 BufferedWriter out = null;
3490
3491 // Any uncaught exception will crash the system process
3492 try {
3493 OutputStream clientStream = client.getOutputStream();
3494 out = new BufferedWriter(new OutputStreamWriter(clientStream), 8 * 1024);
3495
3496 final int count = windows.length;
3497 for (int i = 0; i < count; i++) {
3498 final WindowState w = (WindowState) windows[i];
3499 out.write(Integer.toHexString(System.identityHashCode(w)));
3500 out.write(' ');
3501 out.append(w.mAttrs.getTitle());
3502 out.write('\n');
3503 }
3504
3505 out.write("DONE.\n");
3506 out.flush();
3507 } catch (Exception e) {
3508 result = false;
3509 } finally {
3510 if (out != null) {
3511 try {
3512 out.close();
3513 } catch (IOException e) {
3514 result = false;
3515 }
3516 }
3517 }
3518
3519 return result;
3520 }
3521
3522 /**
3523 * Sends a command to a target window. The result of the command, if any, will be
3524 * written in the output stream of the specified socket.
3525 *
3526 * The parameters must follow this syntax:
3527 * windowHashcode extra
3528 *
3529 * Where XX is the length in characeters of the windowTitle.
3530 *
3531 * The first parameter is the target window. The window with the specified hashcode
3532 * will be the target. If no target can be found, nothing happens. The extra parameters
3533 * will be delivered to the target window and as parameters to the command itself.
3534 *
3535 * @param client The remote client to sent the result, if any, to.
3536 * @param command The command to execute.
3537 * @param parameters The command parameters.
3538 *
3539 * @return True if the command was successfully delivered, false otherwise. This does
3540 * not indicate whether the command itself was successful.
3541 */
3542 boolean viewServerWindowCommand(Socket client, String command, String parameters) {
3543 if ("1".equals(SystemProperties.get(SYSTEM_SECURE, "0"))) {
3544 return false;
3545 }
3546
3547 boolean success = true;
3548 Parcel data = null;
3549 Parcel reply = null;
3550
3551 // Any uncaught exception will crash the system process
3552 try {
3553 // Find the hashcode of the window
3554 int index = parameters.indexOf(' ');
3555 if (index == -1) {
3556 index = parameters.length();
3557 }
3558 final String code = parameters.substring(0, index);
3559 int hashCode = "ffffffff".equals(code) ? -1 : Integer.parseInt(code, 16);
3560
3561 // Extract the command's parameter after the window description
3562 if (index < parameters.length()) {
3563 parameters = parameters.substring(index + 1);
3564 } else {
3565 parameters = "";
3566 }
3567
3568 final WindowManagerService.WindowState window = findWindow(hashCode);
3569 if (window == null) {
3570 return false;
3571 }
3572
3573 data = Parcel.obtain();
3574 data.writeInterfaceToken("android.view.IWindow");
3575 data.writeString(command);
3576 data.writeString(parameters);
3577 data.writeInt(1);
3578 ParcelFileDescriptor.fromSocket(client).writeToParcel(data, 0);
3579
3580 reply = Parcel.obtain();
3581
3582 final IBinder binder = window.mClient.asBinder();
3583 // TODO: GET THE TRANSACTION CODE IN A SAFER MANNER
3584 binder.transact(IBinder.FIRST_CALL_TRANSACTION, data, reply, 0);
3585
3586 reply.readException();
3587
3588 } catch (Exception e) {
3589 Log.w(TAG, "Could not send command " + command + " with parameters " + parameters, e);
3590 success = false;
3591 } finally {
3592 if (data != null) {
3593 data.recycle();
3594 }
3595 if (reply != null) {
3596 reply.recycle();
3597 }
3598 }
3599
3600 return success;
3601 }
3602
3603 private WindowState findWindow(int hashCode) {
3604 if (hashCode == -1) {
3605 return getFocusedWindow();
3606 }
3607
3608 synchronized (mWindowMap) {
3609 final ArrayList windows = mWindows;
3610 final int count = windows.size();
3611
3612 for (int i = 0; i < count; i++) {
3613 WindowState w = (WindowState) windows.get(i);
3614 if (System.identityHashCode(w) == hashCode) {
3615 return w;
3616 }
3617 }
3618 }
3619
3620 return null;
3621 }
3622
3623 /*
3624 * Instruct the Activity Manager to fetch the current configuration and broadcast
3625 * that to config-changed listeners if appropriate.
3626 */
3627 void sendNewConfiguration() {
3628 try {
3629 mActivityManager.updateConfiguration(null);
3630 } catch (RemoteException e) {
3631 }
3632 }
3633
3634 public Configuration computeNewConfiguration() {
3635 synchronized (mWindowMap) {
Dianne Hackbornc485a602009-03-24 22:39:49 -07003636 return computeNewConfigurationLocked();
3637 }
3638 }
3639
3640 Configuration computeNewConfigurationLocked() {
3641 Configuration config = new Configuration();
3642 if (!computeNewConfigurationLocked(config)) {
3643 return null;
3644 }
3645 Log.i(TAG, "Config changed: " + config);
3646 long now = SystemClock.uptimeMillis();
3647 //Log.i(TAG, "Config changing, gc pending: " + mFreezeGcPending + ", now " + now);
3648 if (mFreezeGcPending != 0) {
3649 if (now > (mFreezeGcPending+1000)) {
3650 //Log.i(TAG, "Gc! " + now + " > " + (mFreezeGcPending+1000));
3651 mH.removeMessages(H.FORCE_GC);
3652 Runtime.getRuntime().gc();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003653 mFreezeGcPending = now;
3654 }
Dianne Hackbornc485a602009-03-24 22:39:49 -07003655 } else {
3656 mFreezeGcPending = now;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003657 }
Dianne Hackbornc485a602009-03-24 22:39:49 -07003658 return config;
3659 }
3660
3661 boolean computeNewConfigurationLocked(Configuration config) {
3662 if (mDisplay == null) {
3663 return false;
3664 }
3665 mQueue.getInputConfiguration(config);
3666 final int dw = mDisplay.getWidth();
3667 final int dh = mDisplay.getHeight();
3668 int orientation = Configuration.ORIENTATION_SQUARE;
3669 if (dw < dh) {
3670 orientation = Configuration.ORIENTATION_PORTRAIT;
3671 } else if (dw > dh) {
3672 orientation = Configuration.ORIENTATION_LANDSCAPE;
3673 }
3674 config.orientation = orientation;
3675 config.keyboardHidden = Configuration.KEYBOARDHIDDEN_NO;
3676 config.hardKeyboardHidden = Configuration.HARDKEYBOARDHIDDEN_NO;
3677 mPolicy.adjustConfigurationLw(config);
3678 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003679 }
3680
3681 // -------------------------------------------------------------
3682 // Input Events and Focus Management
3683 // -------------------------------------------------------------
3684
3685 private final void wakeupIfNeeded(WindowState targetWin, int eventType) {
3686 if (targetWin == null ||
3687 targetWin.mAttrs.type != WindowManager.LayoutParams.TYPE_KEYGUARD) {
3688 mPowerManager.userActivity(SystemClock.uptimeMillis(), false, eventType);
3689 }
3690 }
3691
3692 // tells if it's a cheek event or not -- this function is stateful
3693 private static final int EVENT_NONE = 0;
3694 private static final int EVENT_UNKNOWN = 0;
3695 private static final int EVENT_CHEEK = 0;
3696 private static final int EVENT_IGNORE_DURATION = 300; // ms
3697 private static final float CHEEK_THRESHOLD = 0.6f;
3698 private int mEventState = EVENT_NONE;
3699 private float mEventSize;
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07003700
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003701 private int eventType(MotionEvent ev) {
3702 float size = ev.getSize();
3703 switch (ev.getAction()) {
3704 case MotionEvent.ACTION_DOWN:
3705 mEventSize = size;
3706 return (mEventSize > CHEEK_THRESHOLD) ? CHEEK_EVENT : TOUCH_EVENT;
3707 case MotionEvent.ACTION_UP:
3708 if (size > mEventSize) mEventSize = size;
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07003709 return (mEventSize > CHEEK_THRESHOLD) ? CHEEK_EVENT : TOUCH_UP_EVENT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003710 case MotionEvent.ACTION_MOVE:
3711 final int N = ev.getHistorySize();
3712 if (size > mEventSize) mEventSize = size;
3713 if (mEventSize > CHEEK_THRESHOLD) return CHEEK_EVENT;
3714 for (int i=0; i<N; i++) {
3715 size = ev.getHistoricalSize(i);
3716 if (size > mEventSize) mEventSize = size;
3717 if (mEventSize > CHEEK_THRESHOLD) return CHEEK_EVENT;
3718 }
3719 if (ev.getEventTime() < ev.getDownTime() + EVENT_IGNORE_DURATION) {
3720 return TOUCH_EVENT;
3721 } else {
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07003722 return LONG_TOUCH_EVENT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003723 }
3724 default:
3725 // not good
3726 return OTHER_EVENT;
3727 }
3728 }
3729
3730 /**
3731 * @return Returns true if event was dispatched, false if it was dropped for any reason
3732 */
3733 private boolean dispatchPointer(QueuedEvent qev, MotionEvent ev, int pid, int uid) {
3734 if (DEBUG_INPUT || WindowManagerPolicy.WATCH_POINTER) Log.v(TAG,
3735 "dispatchPointer " + ev);
3736
3737 Object targetObj = mKeyWaiter.waitForNextEventTarget(null, qev,
3738 ev, true, false);
3739
3740 int action = ev.getAction();
3741
3742 if (action == MotionEvent.ACTION_UP) {
3743 // let go of our target
3744 mKeyWaiter.mMotionTarget = null;
3745 mPowerManager.logPointerUpEvent();
3746 } else if (action == MotionEvent.ACTION_DOWN) {
3747 mPowerManager.logPointerDownEvent();
3748 }
3749
3750 if (targetObj == null) {
3751 // In this case we are either dropping the event, or have received
3752 // a move or up without a down. It is common to receive move
3753 // events in such a way, since this means the user is moving the
3754 // pointer without actually pressing down. All other cases should
3755 // be atypical, so let's log them.
3756 if (ev.getAction() != MotionEvent.ACTION_MOVE) {
3757 Log.w(TAG, "No window to dispatch pointer action " + ev.getAction());
3758 }
3759 if (qev != null) {
3760 mQueue.recycleEvent(qev);
3761 }
3762 ev.recycle();
3763 return false;
3764 }
3765 if (targetObj == mKeyWaiter.CONSUMED_EVENT_TOKEN) {
3766 if (qev != null) {
3767 mQueue.recycleEvent(qev);
3768 }
3769 ev.recycle();
3770 return true;
3771 }
3772
3773 WindowState target = (WindowState)targetObj;
3774
3775 final long eventTime = ev.getEventTime();
3776
3777 //Log.i(TAG, "Sending " + ev + " to " + target);
3778
3779 if (uid != 0 && uid != target.mSession.mUid) {
3780 if (mContext.checkPermission(
3781 android.Manifest.permission.INJECT_EVENTS, pid, uid)
3782 != PackageManager.PERMISSION_GRANTED) {
3783 Log.w(TAG, "Permission denied: injecting pointer event from pid "
3784 + pid + " uid " + uid + " to window " + target
3785 + " owned by uid " + target.mSession.mUid);
3786 if (qev != null) {
3787 mQueue.recycleEvent(qev);
3788 }
3789 ev.recycle();
3790 return false;
3791 }
3792 }
3793
3794 if ((target.mAttrs.flags &
3795 WindowManager.LayoutParams.FLAG_IGNORE_CHEEK_PRESSES) != 0) {
3796 //target wants to ignore fat touch events
3797 boolean cheekPress = mPolicy.isCheekPressedAgainstScreen(ev);
3798 //explicit flag to return without processing event further
3799 boolean returnFlag = false;
3800 if((action == MotionEvent.ACTION_DOWN)) {
3801 mFatTouch = false;
3802 if(cheekPress) {
3803 mFatTouch = true;
3804 returnFlag = true;
3805 }
3806 } else {
3807 if(action == MotionEvent.ACTION_UP) {
3808 if(mFatTouch) {
3809 //earlier even was invalid doesnt matter if current up is cheekpress or not
3810 mFatTouch = false;
3811 returnFlag = true;
3812 } else if(cheekPress) {
3813 //cancel the earlier event
3814 ev.setAction(MotionEvent.ACTION_CANCEL);
3815 action = MotionEvent.ACTION_CANCEL;
3816 }
3817 } else if(action == MotionEvent.ACTION_MOVE) {
3818 if(mFatTouch) {
3819 //two cases here
3820 //an invalid down followed by 0 or moves(valid or invalid)
3821 //a valid down, invalid move, more moves. want to ignore till up
3822 returnFlag = true;
3823 } else if(cheekPress) {
3824 //valid down followed by invalid moves
3825 //an invalid move have to cancel earlier action
3826 ev.setAction(MotionEvent.ACTION_CANCEL);
3827 action = MotionEvent.ACTION_CANCEL;
3828 if (DEBUG_INPUT) Log.v(TAG, "Sending cancel for invalid ACTION_MOVE");
3829 //note that the subsequent invalid moves will not get here
3830 mFatTouch = true;
3831 }
3832 }
3833 } //else if action
3834 if(returnFlag) {
3835 //recycle que, ev
3836 if (qev != null) {
3837 mQueue.recycleEvent(qev);
3838 }
3839 ev.recycle();
3840 return false;
3841 }
3842 } //end if target
3843
3844 synchronized(mWindowMap) {
3845 if (qev != null && action == MotionEvent.ACTION_MOVE) {
3846 mKeyWaiter.bindTargetWindowLocked(target,
3847 KeyWaiter.RETURN_PENDING_POINTER, qev);
3848 ev = null;
3849 } else {
3850 if (action == MotionEvent.ACTION_DOWN) {
3851 WindowState out = mKeyWaiter.mOutsideTouchTargets;
3852 if (out != null) {
3853 MotionEvent oev = MotionEvent.obtain(ev);
3854 oev.setAction(MotionEvent.ACTION_OUTSIDE);
3855 do {
3856 final Rect frame = out.mFrame;
3857 oev.offsetLocation(-(float)frame.left, -(float)frame.top);
3858 try {
3859 out.mClient.dispatchPointer(oev, eventTime);
3860 } catch (android.os.RemoteException e) {
3861 Log.i(TAG, "WINDOW DIED during outside motion dispatch: " + out);
3862 }
3863 oev.offsetLocation((float)frame.left, (float)frame.top);
3864 out = out.mNextOutsideTouch;
3865 } while (out != null);
3866 mKeyWaiter.mOutsideTouchTargets = null;
3867 }
3868 }
3869 final Rect frame = target.mFrame;
3870 ev.offsetLocation(-(float)frame.left, -(float)frame.top);
3871 mKeyWaiter.bindTargetWindowLocked(target);
3872 }
3873 }
3874
3875 // finally offset the event to the target's coordinate system and
3876 // dispatch the event.
3877 try {
3878 if (DEBUG_INPUT || DEBUG_FOCUS || WindowManagerPolicy.WATCH_POINTER) {
3879 Log.v(TAG, "Delivering pointer " + qev + " to " + target);
3880 }
3881 target.mClient.dispatchPointer(ev, eventTime);
3882 return true;
3883 } catch (android.os.RemoteException e) {
3884 Log.i(TAG, "WINDOW DIED during motion dispatch: " + target);
3885 mKeyWaiter.mMotionTarget = null;
3886 try {
3887 removeWindow(target.mSession, target.mClient);
3888 } catch (java.util.NoSuchElementException ex) {
3889 // This will happen if the window has already been
3890 // removed.
3891 }
3892 }
3893 return false;
3894 }
3895
3896 /**
3897 * @return Returns true if event was dispatched, false if it was dropped for any reason
3898 */
3899 private boolean dispatchTrackball(QueuedEvent qev, MotionEvent ev, int pid, int uid) {
3900 if (DEBUG_INPUT) Log.v(
3901 TAG, "dispatchTrackball [" + ev.getAction() +"] <" + ev.getX() + ", " + ev.getY() + ">");
3902
3903 Object focusObj = mKeyWaiter.waitForNextEventTarget(null, qev,
3904 ev, false, false);
3905 if (focusObj == null) {
3906 Log.w(TAG, "No focus window, dropping trackball: " + ev);
3907 if (qev != null) {
3908 mQueue.recycleEvent(qev);
3909 }
3910 ev.recycle();
3911 return false;
3912 }
3913 if (focusObj == mKeyWaiter.CONSUMED_EVENT_TOKEN) {
3914 if (qev != null) {
3915 mQueue.recycleEvent(qev);
3916 }
3917 ev.recycle();
3918 return true;
3919 }
3920
3921 WindowState focus = (WindowState)focusObj;
3922
3923 if (uid != 0 && uid != focus.mSession.mUid) {
3924 if (mContext.checkPermission(
3925 android.Manifest.permission.INJECT_EVENTS, pid, uid)
3926 != PackageManager.PERMISSION_GRANTED) {
3927 Log.w(TAG, "Permission denied: injecting key event from pid "
3928 + pid + " uid " + uid + " to window " + focus
3929 + " owned by uid " + focus.mSession.mUid);
3930 if (qev != null) {
3931 mQueue.recycleEvent(qev);
3932 }
3933 ev.recycle();
3934 return false;
3935 }
3936 }
3937
3938 final long eventTime = ev.getEventTime();
3939
3940 synchronized(mWindowMap) {
3941 if (qev != null && ev.getAction() == MotionEvent.ACTION_MOVE) {
3942 mKeyWaiter.bindTargetWindowLocked(focus,
3943 KeyWaiter.RETURN_PENDING_TRACKBALL, qev);
3944 // We don't deliver movement events to the client, we hold
3945 // them and wait for them to call back.
3946 ev = null;
3947 } else {
3948 mKeyWaiter.bindTargetWindowLocked(focus);
3949 }
3950 }
3951
3952 try {
3953 focus.mClient.dispatchTrackball(ev, eventTime);
3954 return true;
3955 } catch (android.os.RemoteException e) {
3956 Log.i(TAG, "WINDOW DIED during key dispatch: " + focus);
3957 try {
3958 removeWindow(focus.mSession, focus.mClient);
3959 } catch (java.util.NoSuchElementException ex) {
3960 // This will happen if the window has already been
3961 // removed.
3962 }
3963 }
3964
3965 return false;
3966 }
3967
3968 /**
3969 * @return Returns true if event was dispatched, false if it was dropped for any reason
3970 */
3971 private boolean dispatchKey(KeyEvent event, int pid, int uid) {
3972 if (DEBUG_INPUT) Log.v(TAG, "Dispatch key: " + event);
3973
3974 Object focusObj = mKeyWaiter.waitForNextEventTarget(event, null,
3975 null, false, false);
3976 if (focusObj == null) {
3977 Log.w(TAG, "No focus window, dropping: " + event);
3978 return false;
3979 }
3980 if (focusObj == mKeyWaiter.CONSUMED_EVENT_TOKEN) {
3981 return true;
3982 }
3983
3984 WindowState focus = (WindowState)focusObj;
3985
3986 if (DEBUG_INPUT) Log.v(
3987 TAG, "Dispatching to " + focus + ": " + event);
3988
3989 if (uid != 0 && uid != focus.mSession.mUid) {
3990 if (mContext.checkPermission(
3991 android.Manifest.permission.INJECT_EVENTS, pid, uid)
3992 != PackageManager.PERMISSION_GRANTED) {
3993 Log.w(TAG, "Permission denied: injecting key event from pid "
3994 + pid + " uid " + uid + " to window " + focus
3995 + " owned by uid " + focus.mSession.mUid);
3996 return false;
3997 }
3998 }
3999
4000 synchronized(mWindowMap) {
4001 mKeyWaiter.bindTargetWindowLocked(focus);
4002 }
4003
4004 // NOSHIP extra state logging
4005 mKeyWaiter.recordDispatchState(event, focus);
4006 // END NOSHIP
4007
4008 try {
4009 if (DEBUG_INPUT || DEBUG_FOCUS) {
4010 Log.v(TAG, "Delivering key " + event.getKeyCode()
4011 + " to " + focus);
4012 }
4013 focus.mClient.dispatchKey(event);
4014 return true;
4015 } catch (android.os.RemoteException e) {
4016 Log.i(TAG, "WINDOW DIED during key dispatch: " + focus);
4017 try {
4018 removeWindow(focus.mSession, focus.mClient);
4019 } catch (java.util.NoSuchElementException ex) {
4020 // This will happen if the window has already been
4021 // removed.
4022 }
4023 }
4024
4025 return false;
4026 }
4027
4028 public void pauseKeyDispatching(IBinder _token) {
4029 if (!checkCallingPermission(android.Manifest.permission.MANAGE_APP_TOKENS,
4030 "pauseKeyDispatching()")) {
4031 return;
4032 }
4033
4034 synchronized (mWindowMap) {
4035 WindowToken token = mTokenMap.get(_token);
4036 if (token != null) {
4037 mKeyWaiter.pauseDispatchingLocked(token);
4038 }
4039 }
4040 }
4041
4042 public void resumeKeyDispatching(IBinder _token) {
4043 if (!checkCallingPermission(android.Manifest.permission.MANAGE_APP_TOKENS,
4044 "resumeKeyDispatching()")) {
4045 return;
4046 }
4047
4048 synchronized (mWindowMap) {
4049 WindowToken token = mTokenMap.get(_token);
4050 if (token != null) {
4051 mKeyWaiter.resumeDispatchingLocked(token);
4052 }
4053 }
4054 }
4055
4056 public void setEventDispatching(boolean enabled) {
4057 if (!checkCallingPermission(android.Manifest.permission.MANAGE_APP_TOKENS,
4058 "resumeKeyDispatching()")) {
4059 return;
4060 }
4061
4062 synchronized (mWindowMap) {
4063 mKeyWaiter.setEventDispatchingLocked(enabled);
4064 }
4065 }
4066
4067 /**
4068 * Injects a keystroke event into the UI.
4069 *
4070 * @param ev A motion event describing the keystroke action. (Be sure to use
4071 * {@link SystemClock#uptimeMillis()} as the timebase.)
4072 * @param sync If true, wait for the event to be completed before returning to the caller.
4073 * @return Returns true if event was dispatched, false if it was dropped for any reason
4074 */
4075 public boolean injectKeyEvent(KeyEvent ev, boolean sync) {
4076 long downTime = ev.getDownTime();
4077 long eventTime = ev.getEventTime();
4078
4079 int action = ev.getAction();
4080 int code = ev.getKeyCode();
4081 int repeatCount = ev.getRepeatCount();
4082 int metaState = ev.getMetaState();
4083 int deviceId = ev.getDeviceId();
4084 int scancode = ev.getScanCode();
4085
4086 if (eventTime == 0) eventTime = SystemClock.uptimeMillis();
4087 if (downTime == 0) downTime = eventTime;
4088
4089 KeyEvent newEvent = new KeyEvent(downTime, eventTime, action, code, repeatCount, metaState,
The Android Open Source Project10592532009-03-18 17:39:46 -07004090 deviceId, scancode, KeyEvent.FLAG_FROM_SYSTEM);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004091
4092 boolean result = dispatchKey(newEvent, Binder.getCallingPid(), Binder.getCallingUid());
4093 if (sync) {
4094 mKeyWaiter.waitForNextEventTarget(null, null, null, false, true);
4095 }
4096 return result;
4097 }
4098
4099 /**
4100 * Inject a pointer (touch) event into the UI.
4101 *
4102 * @param ev A motion event describing the pointer (touch) action. (As noted in
4103 * {@link MotionEvent#obtain(long, long, int, float, float, int)}, be sure to use
4104 * {@link SystemClock#uptimeMillis()} as the timebase.)
4105 * @param sync If true, wait for the event to be completed before returning to the caller.
4106 * @return Returns true if event was dispatched, false if it was dropped for any reason
4107 */
4108 public boolean injectPointerEvent(MotionEvent ev, boolean sync) {
4109 boolean result = dispatchPointer(null, ev, Binder.getCallingPid(), Binder.getCallingUid());
4110 if (sync) {
4111 mKeyWaiter.waitForNextEventTarget(null, null, null, false, true);
4112 }
4113 return result;
4114 }
4115
4116 /**
4117 * Inject a trackball (navigation device) event into the UI.
4118 *
4119 * @param ev A motion event describing the trackball action. (As noted in
4120 * {@link MotionEvent#obtain(long, long, int, float, float, int)}, be sure to use
4121 * {@link SystemClock#uptimeMillis()} as the timebase.)
4122 * @param sync If true, wait for the event to be completed before returning to the caller.
4123 * @return Returns true if event was dispatched, false if it was dropped for any reason
4124 */
4125 public boolean injectTrackballEvent(MotionEvent ev, boolean sync) {
4126 boolean result = dispatchTrackball(null, ev, Binder.getCallingPid(), Binder.getCallingUid());
4127 if (sync) {
4128 mKeyWaiter.waitForNextEventTarget(null, null, null, false, true);
4129 }
4130 return result;
4131 }
4132
4133 private WindowState getFocusedWindow() {
4134 synchronized (mWindowMap) {
4135 return getFocusedWindowLocked();
4136 }
4137 }
4138
4139 private WindowState getFocusedWindowLocked() {
4140 return mCurrentFocus;
4141 }
4142
4143 /**
4144 * This class holds the state for dispatching key events. This state
4145 * is protected by the KeyWaiter instance, NOT by the window lock. You
4146 * can be holding the main window lock while acquire the KeyWaiter lock,
4147 * but not the other way around.
4148 */
4149 final class KeyWaiter {
4150 // NOSHIP debugging
4151 public class DispatchState {
4152 private KeyEvent event;
4153 private WindowState focus;
4154 private long time;
4155 private WindowState lastWin;
4156 private IBinder lastBinder;
4157 private boolean finished;
4158 private boolean gotFirstWindow;
4159 private boolean eventDispatching;
4160 private long timeToSwitch;
4161 private boolean wasFrozen;
4162 private boolean focusPaused;
The Android Open Source Projectc474dec2009-03-04 09:49:09 -08004163 private WindowState curFocus;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004164
4165 DispatchState(KeyEvent theEvent, WindowState theFocus) {
4166 focus = theFocus;
4167 event = theEvent;
4168 time = System.currentTimeMillis();
4169 // snapshot KeyWaiter state
4170 lastWin = mLastWin;
4171 lastBinder = mLastBinder;
4172 finished = mFinished;
4173 gotFirstWindow = mGotFirstWindow;
4174 eventDispatching = mEventDispatching;
4175 timeToSwitch = mTimeToSwitch;
4176 wasFrozen = mWasFrozen;
The Android Open Source Projectc474dec2009-03-04 09:49:09 -08004177 curFocus = mCurrentFocus;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004178 // cache the paused state at ctor time as well
4179 if (theFocus == null || theFocus.mToken == null) {
4180 Log.i(TAG, "focus " + theFocus + " mToken is null at event dispatch!");
4181 focusPaused = false;
4182 } else {
4183 focusPaused = theFocus.mToken.paused;
4184 }
4185 }
4186
4187 public String toString() {
4188 return "{{" + event + " to " + focus + " @ " + time
4189 + " lw=" + lastWin + " lb=" + lastBinder
4190 + " fin=" + finished + " gfw=" + gotFirstWindow
4191 + " ed=" + eventDispatching + " tts=" + timeToSwitch
The Android Open Source Projectc474dec2009-03-04 09:49:09 -08004192 + " wf=" + wasFrozen + " fp=" + focusPaused
4193 + " mcf=" + mCurrentFocus + "}}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004194 }
4195 };
4196 private DispatchState mDispatchState = null;
4197 public void recordDispatchState(KeyEvent theEvent, WindowState theFocus) {
4198 mDispatchState = new DispatchState(theEvent, theFocus);
4199 }
4200 // END NOSHIP
4201
4202 public static final int RETURN_NOTHING = 0;
4203 public static final int RETURN_PENDING_POINTER = 1;
4204 public static final int RETURN_PENDING_TRACKBALL = 2;
4205
4206 final Object SKIP_TARGET_TOKEN = new Object();
4207 final Object CONSUMED_EVENT_TOKEN = new Object();
4208
4209 private WindowState mLastWin = null;
4210 private IBinder mLastBinder = null;
4211 private boolean mFinished = true;
4212 private boolean mGotFirstWindow = false;
4213 private boolean mEventDispatching = true;
4214 private long mTimeToSwitch = 0;
4215 /* package */ boolean mWasFrozen = false;
4216
4217 // Target of Motion events
4218 WindowState mMotionTarget;
4219
4220 // Windows above the target who would like to receive an "outside"
4221 // touch event for any down events outside of them.
4222 WindowState mOutsideTouchTargets;
4223
4224 /**
4225 * Wait for the last event dispatch to complete, then find the next
4226 * target that should receive the given event and wait for that one
4227 * to be ready to receive it.
4228 */
4229 Object waitForNextEventTarget(KeyEvent nextKey, QueuedEvent qev,
4230 MotionEvent nextMotion, boolean isPointerEvent,
4231 boolean failIfTimeout) {
4232 long startTime = SystemClock.uptimeMillis();
4233 long keyDispatchingTimeout = 5 * 1000;
4234 long waitedFor = 0;
4235
4236 while (true) {
4237 // Figure out which window we care about. It is either the
4238 // last window we are waiting to have process the event or,
4239 // if none, then the next window we think the event should go
4240 // to. Note: we retrieve mLastWin outside of the lock, so
4241 // it may change before we lock. Thus we must check it again.
4242 WindowState targetWin = mLastWin;
4243 boolean targetIsNew = targetWin == null;
4244 if (DEBUG_INPUT) Log.v(
4245 TAG, "waitForLastKey: mFinished=" + mFinished +
4246 ", mLastWin=" + mLastWin);
4247 if (targetIsNew) {
4248 Object target = findTargetWindow(nextKey, qev, nextMotion,
4249 isPointerEvent);
4250 if (target == SKIP_TARGET_TOKEN) {
4251 // The user has pressed a special key, and we are
4252 // dropping all pending events before it.
4253 if (DEBUG_INPUT) Log.v(TAG, "Skipping: " + nextKey
4254 + " " + nextMotion);
4255 return null;
4256 }
4257 if (target == CONSUMED_EVENT_TOKEN) {
4258 if (DEBUG_INPUT) Log.v(TAG, "Consumed: " + nextKey
4259 + " " + nextMotion);
4260 return target;
4261 }
4262 targetWin = (WindowState)target;
4263 }
4264
4265 AppWindowToken targetApp = null;
4266
4267 // Now: is it okay to send the next event to this window?
4268 synchronized (this) {
4269 // First: did we come here based on the last window not
4270 // being null, but it changed by the time we got here?
4271 // If so, try again.
4272 if (!targetIsNew && mLastWin == null) {
4273 continue;
4274 }
4275
4276 // We never dispatch events if not finished with the
4277 // last one, or the display is frozen.
4278 if (mFinished && !mDisplayFrozen) {
4279 // If event dispatching is disabled, then we
4280 // just consume the events.
4281 if (!mEventDispatching) {
4282 if (DEBUG_INPUT) Log.v(TAG,
4283 "Skipping event; dispatching disabled: "
4284 + nextKey + " " + nextMotion);
4285 return null;
4286 }
4287 if (targetWin != null) {
4288 // If this is a new target, and that target is not
4289 // paused or unresponsive, then all looks good to
4290 // handle the event.
4291 if (targetIsNew && !targetWin.mToken.paused) {
4292 return targetWin;
4293 }
4294
4295 // If we didn't find a target window, and there is no
4296 // focused app window, then just eat the events.
4297 } else if (mFocusedApp == null) {
4298 if (DEBUG_INPUT) Log.v(TAG,
4299 "Skipping event; no focused app: "
4300 + nextKey + " " + nextMotion);
4301 return null;
4302 }
4303 }
4304
4305 if (DEBUG_INPUT) Log.v(
4306 TAG, "Waiting for last key in " + mLastBinder
4307 + " target=" + targetWin
4308 + " mFinished=" + mFinished
4309 + " mDisplayFrozen=" + mDisplayFrozen
4310 + " targetIsNew=" + targetIsNew
4311 + " paused="
4312 + (targetWin != null ? targetWin.mToken.paused : false)
The Android Open Source Projectc474dec2009-03-04 09:49:09 -08004313 + " mFocusedApp=" + mFocusedApp
4314 + " mCurrentFocus=" + mCurrentFocus);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004315
4316 targetApp = targetWin != null
4317 ? targetWin.mAppToken : mFocusedApp;
4318
4319 long curTimeout = keyDispatchingTimeout;
4320 if (mTimeToSwitch != 0) {
4321 long now = SystemClock.uptimeMillis();
4322 if (mTimeToSwitch <= now) {
4323 // If an app switch key has been pressed, and we have
4324 // waited too long for the current app to finish
4325 // processing keys, then wait no more!
4326 doFinishedKeyLocked(true);
4327 continue;
4328 }
4329 long switchTimeout = mTimeToSwitch - now;
4330 if (curTimeout > switchTimeout) {
4331 curTimeout = switchTimeout;
4332 }
4333 }
4334
4335 try {
4336 // after that continue
4337 // processing keys, so we don't get stuck.
4338 if (DEBUG_INPUT) Log.v(
4339 TAG, "Waiting for key dispatch: " + curTimeout);
4340 wait(curTimeout);
4341 if (DEBUG_INPUT) Log.v(TAG, "Finished waiting @"
4342 + SystemClock.uptimeMillis() + " startTime="
The Android Open Source Projectc474dec2009-03-04 09:49:09 -08004343 + startTime + " switchTime=" + mTimeToSwitch
4344 + " target=" + targetWin + " mLW=" + mLastWin
4345 + " mLB=" + mLastBinder + " fin=" + mFinished
4346 + " mCurrentFocus=" + mCurrentFocus);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004347 } catch (InterruptedException e) {
4348 }
4349 }
4350
4351 // If we were frozen during configuration change, restart the
4352 // timeout checks from now; otherwise look at whether we timed
4353 // out before awakening.
4354 if (mWasFrozen) {
4355 waitedFor = 0;
4356 mWasFrozen = false;
4357 } else {
4358 waitedFor = SystemClock.uptimeMillis() - startTime;
4359 }
4360
4361 if (waitedFor >= keyDispatchingTimeout && mTimeToSwitch == 0) {
4362 IApplicationToken at = null;
4363 synchronized (this) {
4364 Log.w(TAG, "Key dispatching timed out sending to " +
4365 (targetWin != null ? targetWin.mAttrs.getTitle()
4366 : "<null>"));
4367 // NOSHIP debugging
4368 Log.w(TAG, "Dispatch state: " + mDispatchState);
4369 Log.w(TAG, "Current state: " + new DispatchState(nextKey, targetWin));
4370 // END NOSHIP
4371 //dump();
4372 if (targetWin != null) {
4373 at = targetWin.getAppToken();
4374 } else if (targetApp != null) {
4375 at = targetApp.appToken;
4376 }
4377 }
4378
4379 boolean abort = true;
4380 if (at != null) {
4381 try {
4382 long timeout = at.getKeyDispatchingTimeout();
4383 if (timeout > waitedFor) {
4384 // we did not wait the proper amount of time for this application.
4385 // set the timeout to be the real timeout and wait again.
4386 keyDispatchingTimeout = timeout - waitedFor;
4387 continue;
4388 } else {
4389 abort = at.keyDispatchingTimedOut();
4390 }
4391 } catch (RemoteException ex) {
4392 }
4393 }
4394
4395 synchronized (this) {
4396 if (abort && (mLastWin == targetWin || targetWin == null)) {
4397 mFinished = true;
4398 if (mLastWin != null) {
4399 if (DEBUG_INPUT) Log.v(TAG,
4400 "Window " + mLastWin +
4401 " timed out on key input");
4402 if (mLastWin.mToken.paused) {
4403 Log.w(TAG, "Un-pausing dispatching to this window");
4404 mLastWin.mToken.paused = false;
4405 }
4406 }
4407 if (mMotionTarget == targetWin) {
4408 mMotionTarget = null;
4409 }
4410 mLastWin = null;
4411 mLastBinder = null;
4412 if (failIfTimeout || targetWin == null) {
4413 return null;
4414 }
4415 } else {
4416 Log.w(TAG, "Continuing to wait for key to be dispatched");
4417 startTime = SystemClock.uptimeMillis();
4418 }
4419 }
4420 }
4421 }
4422 }
4423
4424 Object findTargetWindow(KeyEvent nextKey, QueuedEvent qev,
4425 MotionEvent nextMotion, boolean isPointerEvent) {
4426 mOutsideTouchTargets = null;
4427
4428 if (nextKey != null) {
4429 // Find the target window for a normal key event.
4430 final int keycode = nextKey.getKeyCode();
4431 final int repeatCount = nextKey.getRepeatCount();
4432 final boolean down = nextKey.getAction() != KeyEvent.ACTION_UP;
4433 boolean dispatch = mKeyWaiter.checkShouldDispatchKey(keycode);
4434 if (!dispatch) {
4435 mPolicy.interceptKeyTi(null, keycode,
4436 nextKey.getMetaState(), down, repeatCount);
4437 Log.w(TAG, "Event timeout during app switch: dropping "
4438 + nextKey);
4439 return SKIP_TARGET_TOKEN;
4440 }
4441
4442 // System.out.println("##### [" + SystemClock.uptimeMillis() + "] WindowManagerService.dispatchKey(" + keycode + ", " + down + ", " + repeatCount + ")");
4443
4444 WindowState focus = null;
4445 synchronized(mWindowMap) {
4446 focus = getFocusedWindowLocked();
4447 }
4448
4449 wakeupIfNeeded(focus, LocalPowerManager.BUTTON_EVENT);
4450
4451 if (mPolicy.interceptKeyTi(focus,
4452 keycode, nextKey.getMetaState(), down, repeatCount)) {
4453 return CONSUMED_EVENT_TOKEN;
4454 }
4455
4456 return focus;
4457
4458 } else if (!isPointerEvent) {
4459 boolean dispatch = mKeyWaiter.checkShouldDispatchKey(-1);
4460 if (!dispatch) {
4461 Log.w(TAG, "Event timeout during app switch: dropping trackball "
4462 + nextMotion);
4463 return SKIP_TARGET_TOKEN;
4464 }
4465
4466 WindowState focus = null;
4467 synchronized(mWindowMap) {
4468 focus = getFocusedWindowLocked();
4469 }
4470
4471 wakeupIfNeeded(focus, LocalPowerManager.BUTTON_EVENT);
4472 return focus;
4473 }
4474
4475 if (nextMotion == null) {
4476 return SKIP_TARGET_TOKEN;
4477 }
4478
4479 boolean dispatch = mKeyWaiter.checkShouldDispatchKey(
4480 KeyEvent.KEYCODE_UNKNOWN);
4481 if (!dispatch) {
4482 Log.w(TAG, "Event timeout during app switch: dropping pointer "
4483 + nextMotion);
4484 return SKIP_TARGET_TOKEN;
4485 }
4486
4487 // Find the target window for a pointer event.
4488 int action = nextMotion.getAction();
4489 final float xf = nextMotion.getX();
4490 final float yf = nextMotion.getY();
4491 final long eventTime = nextMotion.getEventTime();
4492
4493 final boolean screenWasOff = qev != null
4494 && (qev.flags&WindowManagerPolicy.FLAG_BRIGHT_HERE) != 0;
4495
4496 WindowState target = null;
4497
4498 synchronized(mWindowMap) {
4499 synchronized (this) {
4500 if (action == MotionEvent.ACTION_DOWN) {
4501 if (mMotionTarget != null) {
4502 // this is weird, we got a pen down, but we thought it was
4503 // already down!
4504 // XXX: We should probably send an ACTION_UP to the current
4505 // target.
4506 Log.w(TAG, "Pointer down received while already down in: "
4507 + mMotionTarget);
4508 mMotionTarget = null;
4509 }
4510
4511 // ACTION_DOWN is special, because we need to lock next events to
4512 // the window we'll land onto.
4513 final int x = (int)xf;
4514 final int y = (int)yf;
4515
4516 final ArrayList windows = mWindows;
4517 final int N = windows.size();
4518 WindowState topErrWindow = null;
4519 final Rect tmpRect = mTempRect;
4520 for (int i=N-1; i>=0; i--) {
4521 WindowState child = (WindowState)windows.get(i);
4522 //Log.i(TAG, "Checking dispatch to: " + child);
4523 final int flags = child.mAttrs.flags;
4524 if ((flags & WindowManager.LayoutParams.FLAG_SYSTEM_ERROR) != 0) {
4525 if (topErrWindow == null) {
4526 topErrWindow = child;
4527 }
4528 }
4529 if (!child.isVisibleLw()) {
4530 //Log.i(TAG, "Not visible!");
4531 continue;
4532 }
4533 if ((flags & WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE) != 0) {
4534 //Log.i(TAG, "Not touchable!");
4535 if ((flags & WindowManager.LayoutParams
4536 .FLAG_WATCH_OUTSIDE_TOUCH) != 0) {
4537 child.mNextOutsideTouch = mOutsideTouchTargets;
4538 mOutsideTouchTargets = child;
4539 }
4540 continue;
4541 }
4542 tmpRect.set(child.mFrame);
4543 if (child.mTouchableInsets == ViewTreeObserver
4544 .InternalInsetsInfo.TOUCHABLE_INSETS_CONTENT) {
4545 // The touch is inside of the window if it is
4546 // inside the frame, AND the content part of that
4547 // frame that was given by the application.
4548 tmpRect.left += child.mGivenContentInsets.left;
4549 tmpRect.top += child.mGivenContentInsets.top;
4550 tmpRect.right -= child.mGivenContentInsets.right;
4551 tmpRect.bottom -= child.mGivenContentInsets.bottom;
4552 } else if (child.mTouchableInsets == ViewTreeObserver
4553 .InternalInsetsInfo.TOUCHABLE_INSETS_VISIBLE) {
4554 // The touch is inside of the window if it is
4555 // inside the frame, AND the visible part of that
4556 // frame that was given by the application.
4557 tmpRect.left += child.mGivenVisibleInsets.left;
4558 tmpRect.top += child.mGivenVisibleInsets.top;
4559 tmpRect.right -= child.mGivenVisibleInsets.right;
4560 tmpRect.bottom -= child.mGivenVisibleInsets.bottom;
4561 }
4562 final int touchFlags = flags &
4563 (WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
4564 |WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL);
4565 if (tmpRect.contains(x, y) || touchFlags == 0) {
4566 //Log.i(TAG, "Using this target!");
4567 if (!screenWasOff || (flags &
4568 WindowManager.LayoutParams.FLAG_TOUCHABLE_WHEN_WAKING) != 0) {
4569 mMotionTarget = child;
4570 } else {
4571 //Log.i(TAG, "Waking, skip!");
4572 mMotionTarget = null;
4573 }
4574 break;
4575 }
4576
4577 if ((flags & WindowManager.LayoutParams
4578 .FLAG_WATCH_OUTSIDE_TOUCH) != 0) {
4579 child.mNextOutsideTouch = mOutsideTouchTargets;
4580 mOutsideTouchTargets = child;
4581 //Log.i(TAG, "Adding to outside target list: " + child);
4582 }
4583 }
4584
4585 // if there's an error window but it's not accepting
4586 // focus (typically because it is not yet visible) just
4587 // wait for it -- any other focused window may in fact
4588 // be in ANR state.
4589 if (topErrWindow != null && mMotionTarget != topErrWindow) {
4590 mMotionTarget = null;
4591 }
4592 }
4593
4594 target = mMotionTarget;
4595 }
4596 }
4597
4598 wakeupIfNeeded(target, eventType(nextMotion));
4599
4600 // Pointer events are a little different -- if there isn't a
4601 // target found for any event, then just drop it.
4602 return target != null ? target : SKIP_TARGET_TOKEN;
4603 }
4604
4605 boolean checkShouldDispatchKey(int keycode) {
4606 synchronized (this) {
4607 if (mPolicy.isAppSwitchKeyTqTiLwLi(keycode)) {
4608 mTimeToSwitch = 0;
4609 return true;
4610 }
4611 if (mTimeToSwitch != 0
4612 && mTimeToSwitch < SystemClock.uptimeMillis()) {
4613 return false;
4614 }
4615 return true;
4616 }
4617 }
4618
4619 void bindTargetWindowLocked(WindowState win,
4620 int pendingWhat, QueuedEvent pendingMotion) {
4621 synchronized (this) {
4622 bindTargetWindowLockedLocked(win, pendingWhat, pendingMotion);
4623 }
4624 }
4625
4626 void bindTargetWindowLocked(WindowState win) {
4627 synchronized (this) {
4628 bindTargetWindowLockedLocked(win, RETURN_NOTHING, null);
4629 }
4630 }
4631
4632 void bindTargetWindowLockedLocked(WindowState win,
4633 int pendingWhat, QueuedEvent pendingMotion) {
4634 mLastWin = win;
4635 mLastBinder = win.mClient.asBinder();
4636 mFinished = false;
4637 if (pendingMotion != null) {
4638 final Session s = win.mSession;
4639 if (pendingWhat == RETURN_PENDING_POINTER) {
4640 releasePendingPointerLocked(s);
4641 s.mPendingPointerMove = pendingMotion;
4642 s.mPendingPointerWindow = win;
4643 if (DEBUG_INPUT) Log.v(TAG,
4644 "bindTargetToWindow " + s.mPendingPointerMove);
4645 } else if (pendingWhat == RETURN_PENDING_TRACKBALL) {
4646 releasePendingTrackballLocked(s);
4647 s.mPendingTrackballMove = pendingMotion;
4648 s.mPendingTrackballWindow = win;
4649 }
4650 }
4651 }
4652
4653 void releasePendingPointerLocked(Session s) {
4654 if (DEBUG_INPUT) Log.v(TAG,
4655 "releasePendingPointer " + s.mPendingPointerMove);
4656 if (s.mPendingPointerMove != null) {
4657 mQueue.recycleEvent(s.mPendingPointerMove);
4658 s.mPendingPointerMove = null;
4659 }
4660 }
4661
4662 void releasePendingTrackballLocked(Session s) {
4663 if (s.mPendingTrackballMove != null) {
4664 mQueue.recycleEvent(s.mPendingTrackballMove);
4665 s.mPendingTrackballMove = null;
4666 }
4667 }
4668
4669 MotionEvent finishedKey(Session session, IWindow client, boolean force,
4670 int returnWhat) {
4671 if (DEBUG_INPUT) Log.v(
4672 TAG, "finishedKey: client=" + client + ", force=" + force);
4673
4674 if (client == null) {
4675 return null;
4676 }
4677
4678 synchronized (this) {
4679 if (DEBUG_INPUT) Log.v(
4680 TAG, "finishedKey: client=" + client.asBinder()
4681 + ", force=" + force + ", last=" + mLastBinder
4682 + " (token=" + (mLastWin != null ? mLastWin.mToken : null) + ")");
4683
4684 QueuedEvent qev = null;
4685 WindowState win = null;
4686 if (returnWhat == RETURN_PENDING_POINTER) {
4687 qev = session.mPendingPointerMove;
4688 win = session.mPendingPointerWindow;
4689 session.mPendingPointerMove = null;
4690 session.mPendingPointerWindow = null;
4691 } else if (returnWhat == RETURN_PENDING_TRACKBALL) {
4692 qev = session.mPendingTrackballMove;
4693 win = session.mPendingTrackballWindow;
4694 session.mPendingTrackballMove = null;
4695 session.mPendingTrackballWindow = null;
4696 }
4697
4698 if (mLastBinder == client.asBinder()) {
4699 if (DEBUG_INPUT) Log.v(
4700 TAG, "finishedKey: last paused="
4701 + ((mLastWin != null) ? mLastWin.mToken.paused : "null"));
4702 if (mLastWin != null && (!mLastWin.mToken.paused || force
4703 || !mEventDispatching)) {
4704 doFinishedKeyLocked(false);
4705 } else {
4706 // Make sure to wake up anyone currently waiting to
4707 // dispatch a key, so they can re-evaluate their
4708 // current situation.
4709 mFinished = true;
4710 notifyAll();
4711 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004712 }
4713
4714 if (qev != null) {
4715 MotionEvent res = (MotionEvent)qev.event;
4716 if (DEBUG_INPUT) Log.v(TAG,
4717 "Returning pending motion: " + res);
4718 mQueue.recycleEvent(qev);
4719 if (win != null && returnWhat == RETURN_PENDING_POINTER) {
4720 res.offsetLocation(-win.mFrame.left, -win.mFrame.top);
4721 }
4722 return res;
4723 }
4724 return null;
4725 }
4726 }
4727
4728 void tickle() {
4729 synchronized (this) {
4730 notifyAll();
4731 }
4732 }
4733
4734 void handleNewWindowLocked(WindowState newWindow) {
4735 if (!newWindow.canReceiveKeys()) {
4736 return;
4737 }
4738 synchronized (this) {
The Android Open Source Projectc474dec2009-03-04 09:49:09 -08004739 if (DEBUG_INPUT) Log.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004740 TAG, "New key dispatch window: win="
4741 + newWindow.mClient.asBinder()
4742 + ", last=" + mLastBinder
4743 + " (token=" + (mLastWin != null ? mLastWin.mToken : null)
4744 + "), finished=" + mFinished + ", paused="
4745 + newWindow.mToken.paused);
4746
4747 // Displaying a window implicitly causes dispatching to
4748 // be unpaused. (This is to protect against bugs if someone
4749 // pauses dispatching but forgets to resume.)
4750 newWindow.mToken.paused = false;
4751
4752 mGotFirstWindow = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004753
4754 if ((newWindow.mAttrs.flags & FLAG_SYSTEM_ERROR) != 0) {
4755 if (DEBUG_INPUT) Log.v(TAG,
4756 "New SYSTEM_ERROR window; resetting state");
4757 mLastWin = null;
4758 mLastBinder = null;
4759 mMotionTarget = null;
4760 mFinished = true;
4761 } else if (mLastWin != null) {
4762 // If the new window is above the window we are
4763 // waiting on, then stop waiting and let key dispatching
4764 // start on the new guy.
4765 if (DEBUG_INPUT) Log.v(
4766 TAG, "Last win layer=" + mLastWin.mLayer
4767 + ", new win layer=" + newWindow.mLayer);
4768 if (newWindow.mLayer >= mLastWin.mLayer) {
The Android Open Source Projectc474dec2009-03-04 09:49:09 -08004769 // The new window is above the old; finish pending input to the last
4770 // window and start directing it to the new one.
4771 mLastWin.mToken.paused = false;
4772 doFinishedKeyLocked(true); // does a notifyAll()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004773 }
The Android Open Source Projectc474dec2009-03-04 09:49:09 -08004774 // Either the new window is lower, so there is no need to wake key waiters,
4775 // or we just finished key input to the previous window, which implicitly
4776 // notified the key waiters. In both cases, we don't need to issue the
4777 // notification here.
4778 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004779 }
4780
The Android Open Source Projectc474dec2009-03-04 09:49:09 -08004781 // Now that we've put a new window state in place, make the event waiter
4782 // take notice and retarget its attentions.
4783 notifyAll();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004784 }
4785 }
4786
4787 void pauseDispatchingLocked(WindowToken token) {
4788 synchronized (this)
4789 {
4790 if (DEBUG_INPUT) Log.v(TAG, "Pausing WindowToken " + token);
4791 token.paused = true;
4792
4793 /*
4794 if (mLastWin != null && !mFinished && mLastWin.mBaseLayer <= layer) {
4795 mPaused = true;
4796 } else {
4797 if (mLastWin == null) {
4798 if (Config.LOGI) Log.i(
4799 TAG, "Key dispatching not paused: no last window.");
4800 } else if (mFinished) {
4801 if (Config.LOGI) Log.i(
4802 TAG, "Key dispatching not paused: finished last key.");
4803 } else {
4804 if (Config.LOGI) Log.i(
4805 TAG, "Key dispatching not paused: window in higher layer.");
4806 }
4807 }
4808 */
4809 }
4810 }
4811
4812 void resumeDispatchingLocked(WindowToken token) {
4813 synchronized (this) {
4814 if (token.paused) {
4815 if (DEBUG_INPUT) Log.v(
4816 TAG, "Resuming WindowToken " + token
4817 + ", last=" + mLastBinder
4818 + " (token=" + (mLastWin != null ? mLastWin.mToken : null)
4819 + "), finished=" + mFinished + ", paused="
4820 + token.paused);
4821 token.paused = false;
4822 if (mLastWin != null && mLastWin.mToken == token && mFinished) {
4823 doFinishedKeyLocked(true);
4824 } else {
4825 notifyAll();
4826 }
4827 }
4828 }
4829 }
4830
4831 void setEventDispatchingLocked(boolean enabled) {
4832 synchronized (this) {
4833 mEventDispatching = enabled;
4834 notifyAll();
4835 }
4836 }
4837
4838 void appSwitchComing() {
4839 synchronized (this) {
4840 // Don't wait for more than .5 seconds for app to finish
4841 // processing the pending events.
4842 long now = SystemClock.uptimeMillis() + 500;
4843 if (DEBUG_INPUT) Log.v(TAG, "appSwitchComing: " + now);
4844 if (mTimeToSwitch == 0 || now < mTimeToSwitch) {
4845 mTimeToSwitch = now;
4846 }
4847 notifyAll();
4848 }
4849 }
4850
4851 private final void doFinishedKeyLocked(boolean doRecycle) {
4852 if (mLastWin != null) {
4853 releasePendingPointerLocked(mLastWin.mSession);
4854 releasePendingTrackballLocked(mLastWin.mSession);
4855 }
4856
4857 if (mLastWin == null || !mLastWin.mToken.paused
4858 || !mLastWin.isVisibleLw()) {
4859 // If the current window has been paused, we aren't -really-
4860 // finished... so let the waiters still wait.
4861 mLastWin = null;
4862 mLastBinder = null;
4863 }
4864 mFinished = true;
4865 notifyAll();
4866 }
4867 }
4868
4869 private class KeyQ extends KeyInputQueue
4870 implements KeyInputQueue.FilterCallback {
4871 PowerManager.WakeLock mHoldingScreen;
4872
4873 KeyQ() {
4874 super(mContext);
4875 PowerManager pm = (PowerManager)mContext.getSystemService(Context.POWER_SERVICE);
4876 mHoldingScreen = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK,
4877 "KEEP_SCREEN_ON_FLAG");
4878 mHoldingScreen.setReferenceCounted(false);
4879 }
4880
4881 @Override
4882 boolean preprocessEvent(InputDevice device, RawInputEvent event) {
4883 if (mPolicy.preprocessInputEventTq(event)) {
4884 return true;
4885 }
4886
4887 switch (event.type) {
4888 case RawInputEvent.EV_KEY: {
4889 // XXX begin hack
4890 if (DEBUG) {
4891 if (event.keycode == KeyEvent.KEYCODE_G) {
4892 if (event.value != 0) {
4893 // G down
4894 mPolicy.screenTurnedOff(WindowManagerPolicy.OFF_BECAUSE_OF_USER);
4895 }
4896 return false;
4897 }
4898 if (event.keycode == KeyEvent.KEYCODE_D) {
4899 if (event.value != 0) {
4900 //dump();
4901 }
4902 return false;
4903 }
4904 }
4905 // XXX end hack
4906
4907 boolean screenIsOff = !mPowerManager.screenIsOn();
4908 boolean screenIsDim = !mPowerManager.screenIsBright();
4909 int actions = mPolicy.interceptKeyTq(event, !screenIsOff);
4910
4911 if ((actions & WindowManagerPolicy.ACTION_GO_TO_SLEEP) != 0) {
4912 mPowerManager.goToSleep(event.when);
4913 }
4914
4915 if (screenIsOff) {
4916 event.flags |= WindowManagerPolicy.FLAG_WOKE_HERE;
4917 }
4918 if (screenIsDim) {
4919 event.flags |= WindowManagerPolicy.FLAG_BRIGHT_HERE;
4920 }
4921 if ((actions & WindowManagerPolicy.ACTION_POKE_USER_ACTIVITY) != 0) {
4922 mPowerManager.userActivity(event.when, false,
4923 LocalPowerManager.BUTTON_EVENT);
4924 }
4925
4926 if ((actions & WindowManagerPolicy.ACTION_PASS_TO_USER) != 0) {
4927 if (event.value != 0 && mPolicy.isAppSwitchKeyTqTiLwLi(event.keycode)) {
4928 filterQueue(this);
4929 mKeyWaiter.appSwitchComing();
4930 }
4931 return true;
4932 } else {
4933 return false;
4934 }
4935 }
4936
4937 case RawInputEvent.EV_REL: {
4938 boolean screenIsOff = !mPowerManager.screenIsOn();
4939 boolean screenIsDim = !mPowerManager.screenIsBright();
4940 if (screenIsOff) {
4941 if (!mPolicy.isWakeRelMovementTq(event.deviceId,
4942 device.classes, event)) {
4943 //Log.i(TAG, "dropping because screenIsOff and !isWakeKey");
4944 return false;
4945 }
4946 event.flags |= WindowManagerPolicy.FLAG_WOKE_HERE;
4947 }
4948 if (screenIsDim) {
4949 event.flags |= WindowManagerPolicy.FLAG_BRIGHT_HERE;
4950 }
4951 return true;
4952 }
4953
4954 case RawInputEvent.EV_ABS: {
4955 boolean screenIsOff = !mPowerManager.screenIsOn();
4956 boolean screenIsDim = !mPowerManager.screenIsBright();
4957 if (screenIsOff) {
4958 if (!mPolicy.isWakeAbsMovementTq(event.deviceId,
4959 device.classes, event)) {
4960 //Log.i(TAG, "dropping because screenIsOff and !isWakeKey");
4961 return false;
4962 }
4963 event.flags |= WindowManagerPolicy.FLAG_WOKE_HERE;
4964 }
4965 if (screenIsDim) {
4966 event.flags |= WindowManagerPolicy.FLAG_BRIGHT_HERE;
4967 }
4968 return true;
4969 }
4970
4971 default:
4972 return true;
4973 }
4974 }
4975
4976 public int filterEvent(QueuedEvent ev) {
4977 switch (ev.classType) {
4978 case RawInputEvent.CLASS_KEYBOARD:
4979 KeyEvent ke = (KeyEvent)ev.event;
4980 if (mPolicy.isMovementKeyTi(ke.getKeyCode())) {
4981 Log.w(TAG, "Dropping movement key during app switch: "
4982 + ke.getKeyCode() + ", action=" + ke.getAction());
4983 return FILTER_REMOVE;
4984 }
4985 return FILTER_ABORT;
4986 default:
4987 return FILTER_KEEP;
4988 }
4989 }
4990
4991 /**
4992 * Must be called with the main window manager lock held.
4993 */
4994 void setHoldScreenLocked(boolean holding) {
4995 boolean state = mHoldingScreen.isHeld();
4996 if (holding != state) {
4997 if (holding) {
4998 mHoldingScreen.acquire();
4999 } else {
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07005000 mPolicy.screenOnStoppedLw();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005001 mHoldingScreen.release();
5002 }
5003 }
5004 }
5005 };
5006
5007 public boolean detectSafeMode() {
5008 mSafeMode = mPolicy.detectSafeMode();
5009 return mSafeMode;
5010 }
5011
5012 public void systemReady() {
5013 mPolicy.systemReady();
5014 }
5015
5016 private final class InputDispatcherThread extends Thread {
5017 // Time to wait when there is nothing to do: 9999 seconds.
5018 static final int LONG_WAIT=9999*1000;
5019
5020 public InputDispatcherThread() {
5021 super("InputDispatcher");
5022 }
5023
5024 @Override
5025 public void run() {
5026 while (true) {
5027 try {
5028 process();
5029 } catch (Exception e) {
5030 Log.e(TAG, "Exception in input dispatcher", e);
5031 }
5032 }
5033 }
5034
5035 private void process() {
5036 android.os.Process.setThreadPriority(
5037 android.os.Process.THREAD_PRIORITY_URGENT_DISPLAY);
5038
5039 // The last key event we saw
5040 KeyEvent lastKey = null;
5041
5042 // Last keydown time for auto-repeating keys
5043 long lastKeyTime = SystemClock.uptimeMillis();
5044 long nextKeyTime = lastKeyTime+LONG_WAIT;
5045
5046 // How many successive repeats we generated
5047 int keyRepeatCount = 0;
5048
5049 // Need to report that configuration has changed?
5050 boolean configChanged = false;
5051
5052 while (true) {
5053 long curTime = SystemClock.uptimeMillis();
5054
5055 if (DEBUG_INPUT) Log.v(
5056 TAG, "Waiting for next key: now=" + curTime
5057 + ", repeat @ " + nextKeyTime);
5058
5059 // Retrieve next event, waiting only as long as the next
5060 // repeat timeout. If the configuration has changed, then
5061 // don't wait at all -- we'll report the change as soon as
5062 // we have processed all events.
5063 QueuedEvent ev = mQueue.getEvent(
5064 (int)((!configChanged && curTime < nextKeyTime)
5065 ? (nextKeyTime-curTime) : 0));
5066
5067 if (DEBUG_INPUT && ev != null) Log.v(
5068 TAG, "Event: type=" + ev.classType + " data=" + ev.event);
5069
5070 try {
5071 if (ev != null) {
5072 curTime = ev.when;
5073 int eventType;
5074 if (ev.classType == RawInputEvent.CLASS_TOUCHSCREEN) {
5075 eventType = eventType((MotionEvent)ev.event);
5076 } else if (ev.classType == RawInputEvent.CLASS_KEYBOARD ||
5077 ev.classType == RawInputEvent.CLASS_TRACKBALL) {
5078 eventType = LocalPowerManager.BUTTON_EVENT;
5079 } else {
5080 eventType = LocalPowerManager.OTHER_EVENT;
5081 }
5082 mPowerManager.userActivity(curTime, false, eventType);
5083 switch (ev.classType) {
5084 case RawInputEvent.CLASS_KEYBOARD:
5085 KeyEvent ke = (KeyEvent)ev.event;
5086 if (ke.isDown()) {
5087 lastKey = ke;
5088 keyRepeatCount = 0;
5089 lastKeyTime = curTime;
5090 nextKeyTime = lastKeyTime
5091 + KEY_REPEAT_FIRST_DELAY;
5092 if (DEBUG_INPUT) Log.v(
5093 TAG, "Received key down: first repeat @ "
5094 + nextKeyTime);
5095 } else {
5096 lastKey = null;
5097 // Arbitrary long timeout.
5098 lastKeyTime = curTime;
5099 nextKeyTime = curTime + LONG_WAIT;
5100 if (DEBUG_INPUT) Log.v(
5101 TAG, "Received key up: ignore repeat @ "
5102 + nextKeyTime);
5103 }
5104 dispatchKey((KeyEvent)ev.event, 0, 0);
5105 mQueue.recycleEvent(ev);
5106 break;
5107 case RawInputEvent.CLASS_TOUCHSCREEN:
5108 //Log.i(TAG, "Read next event " + ev);
5109 dispatchPointer(ev, (MotionEvent)ev.event, 0, 0);
5110 break;
5111 case RawInputEvent.CLASS_TRACKBALL:
5112 dispatchTrackball(ev, (MotionEvent)ev.event, 0, 0);
5113 break;
5114 case RawInputEvent.CLASS_CONFIGURATION_CHANGED:
5115 configChanged = true;
5116 break;
5117 default:
5118 mQueue.recycleEvent(ev);
5119 break;
5120 }
5121
5122 } else if (configChanged) {
5123 configChanged = false;
5124 sendNewConfiguration();
5125
5126 } else if (lastKey != null) {
5127 curTime = SystemClock.uptimeMillis();
5128
5129 // Timeout occurred while key was down. If it is at or
5130 // past the key repeat time, dispatch the repeat.
5131 if (DEBUG_INPUT) Log.v(
5132 TAG, "Key timeout: repeat=" + nextKeyTime
5133 + ", now=" + curTime);
5134 if (curTime < nextKeyTime) {
5135 continue;
5136 }
5137
5138 lastKeyTime = nextKeyTime;
5139 nextKeyTime = nextKeyTime + KEY_REPEAT_DELAY;
5140 keyRepeatCount++;
5141 if (DEBUG_INPUT) Log.v(
5142 TAG, "Key repeat: count=" + keyRepeatCount
5143 + ", next @ " + nextKeyTime);
The Android Open Source Project10592532009-03-18 17:39:46 -07005144 dispatchKey(KeyEvent.changeTimeRepeat(lastKey, curTime, keyRepeatCount), 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005145
5146 } else {
5147 curTime = SystemClock.uptimeMillis();
5148
5149 lastKeyTime = curTime;
5150 nextKeyTime = curTime + LONG_WAIT;
5151 }
5152
5153 } catch (Exception e) {
5154 Log.e(TAG,
5155 "Input thread received uncaught exception: " + e, e);
5156 }
5157 }
5158 }
5159 }
5160
5161 // -------------------------------------------------------------
5162 // Client Session State
5163 // -------------------------------------------------------------
5164
5165 private final class Session extends IWindowSession.Stub
5166 implements IBinder.DeathRecipient {
5167 final IInputMethodClient mClient;
5168 final IInputContext mInputContext;
5169 final int mUid;
5170 final int mPid;
5171 SurfaceSession mSurfaceSession;
5172 int mNumWindow = 0;
5173 boolean mClientDead = false;
5174
5175 /**
5176 * Current pointer move event being dispatched to client window... must
5177 * hold key lock to access.
5178 */
5179 QueuedEvent mPendingPointerMove;
5180 WindowState mPendingPointerWindow;
5181
5182 /**
5183 * Current trackball move event being dispatched to client window... must
5184 * hold key lock to access.
5185 */
5186 QueuedEvent mPendingTrackballMove;
5187 WindowState mPendingTrackballWindow;
5188
5189 public Session(IInputMethodClient client, IInputContext inputContext) {
5190 mClient = client;
5191 mInputContext = inputContext;
5192 mUid = Binder.getCallingUid();
5193 mPid = Binder.getCallingPid();
5194 synchronized (mWindowMap) {
5195 if (mInputMethodManager == null && mHaveInputMethods) {
5196 IBinder b = ServiceManager.getService(
5197 Context.INPUT_METHOD_SERVICE);
5198 mInputMethodManager = IInputMethodManager.Stub.asInterface(b);
5199 }
5200 }
5201 long ident = Binder.clearCallingIdentity();
5202 try {
5203 // Note: it is safe to call in to the input method manager
5204 // here because we are not holding our lock.
5205 if (mInputMethodManager != null) {
5206 mInputMethodManager.addClient(client, inputContext,
5207 mUid, mPid);
5208 } else {
5209 client.setUsingInputMethod(false);
5210 }
5211 client.asBinder().linkToDeath(this, 0);
5212 } catch (RemoteException e) {
5213 // The caller has died, so we can just forget about this.
5214 try {
5215 if (mInputMethodManager != null) {
5216 mInputMethodManager.removeClient(client);
5217 }
5218 } catch (RemoteException ee) {
5219 }
5220 } finally {
5221 Binder.restoreCallingIdentity(ident);
5222 }
5223 }
5224
5225 @Override
5226 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
5227 throws RemoteException {
5228 try {
5229 return super.onTransact(code, data, reply, flags);
5230 } catch (RuntimeException e) {
5231 // Log all 'real' exceptions thrown to the caller
5232 if (!(e instanceof SecurityException)) {
5233 Log.e(TAG, "Window Session Crash", e);
5234 }
5235 throw e;
5236 }
5237 }
5238
5239 public void binderDied() {
5240 // Note: it is safe to call in to the input method manager
5241 // here because we are not holding our lock.
5242 try {
5243 if (mInputMethodManager != null) {
5244 mInputMethodManager.removeClient(mClient);
5245 }
5246 } catch (RemoteException e) {
5247 }
5248 synchronized(mWindowMap) {
5249 mClientDead = true;
5250 killSessionLocked();
5251 }
5252 }
5253
5254 public int add(IWindow window, WindowManager.LayoutParams attrs,
5255 int viewVisibility, Rect outContentInsets) {
5256 return addWindow(this, window, attrs, viewVisibility, outContentInsets);
5257 }
5258
5259 public void remove(IWindow window) {
5260 removeWindow(this, window);
5261 }
5262
5263 public int relayout(IWindow window, WindowManager.LayoutParams attrs,
5264 int requestedWidth, int requestedHeight, int viewFlags,
5265 boolean insetsPending, Rect outFrame, Rect outContentInsets,
5266 Rect outVisibleInsets, Surface outSurface) {
5267 return relayoutWindow(this, window, attrs,
5268 requestedWidth, requestedHeight, viewFlags, insetsPending,
5269 outFrame, outContentInsets, outVisibleInsets, outSurface);
5270 }
5271
5272 public void setTransparentRegion(IWindow window, Region region) {
5273 setTransparentRegionWindow(this, window, region);
5274 }
5275
5276 public void setInsets(IWindow window, int touchableInsets,
5277 Rect contentInsets, Rect visibleInsets) {
5278 setInsetsWindow(this, window, touchableInsets, contentInsets,
5279 visibleInsets);
5280 }
5281
5282 public void getDisplayFrame(IWindow window, Rect outDisplayFrame) {
5283 getWindowDisplayFrame(this, window, outDisplayFrame);
5284 }
5285
5286 public void finishDrawing(IWindow window) {
5287 if (localLOGV) Log.v(
5288 TAG, "IWindow finishDrawing called for " + window);
5289 finishDrawingWindow(this, window);
5290 }
5291
5292 public void finishKey(IWindow window) {
5293 if (localLOGV) Log.v(
5294 TAG, "IWindow finishKey called for " + window);
5295 mKeyWaiter.finishedKey(this, window, false,
5296 KeyWaiter.RETURN_NOTHING);
5297 }
5298
5299 public MotionEvent getPendingPointerMove(IWindow window) {
5300 if (localLOGV) Log.v(
5301 TAG, "IWindow getPendingMotionEvent called for " + window);
5302 return mKeyWaiter.finishedKey(this, window, false,
5303 KeyWaiter.RETURN_PENDING_POINTER);
5304 }
5305
5306 public MotionEvent getPendingTrackballMove(IWindow window) {
5307 if (localLOGV) Log.v(
5308 TAG, "IWindow getPendingMotionEvent called for " + window);
5309 return mKeyWaiter.finishedKey(this, window, false,
5310 KeyWaiter.RETURN_PENDING_TRACKBALL);
5311 }
5312
5313 public void setInTouchMode(boolean mode) {
5314 synchronized(mWindowMap) {
5315 mInTouchMode = mode;
5316 }
5317 }
5318
5319 public boolean getInTouchMode() {
5320 synchronized(mWindowMap) {
5321 return mInTouchMode;
5322 }
5323 }
5324
5325 public boolean performHapticFeedback(IWindow window, int effectId,
5326 boolean always) {
5327 synchronized(mWindowMap) {
5328 long ident = Binder.clearCallingIdentity();
5329 try {
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07005330 return mPolicy.performHapticFeedbackLw(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005331 windowForClientLocked(this, window), effectId, always);
5332 } finally {
5333 Binder.restoreCallingIdentity(ident);
5334 }
5335 }
5336 }
5337
5338 void windowAddedLocked() {
5339 if (mSurfaceSession == null) {
5340 if (localLOGV) Log.v(
5341 TAG, "First window added to " + this + ", creating SurfaceSession");
5342 mSurfaceSession = new SurfaceSession();
5343 mSessions.add(this);
5344 }
5345 mNumWindow++;
5346 }
5347
5348 void windowRemovedLocked() {
5349 mNumWindow--;
5350 killSessionLocked();
5351 }
5352
5353 void killSessionLocked() {
5354 if (mNumWindow <= 0 && mClientDead) {
5355 mSessions.remove(this);
5356 if (mSurfaceSession != null) {
5357 if (localLOGV) Log.v(
5358 TAG, "Last window removed from " + this
5359 + ", destroying " + mSurfaceSession);
5360 try {
5361 mSurfaceSession.kill();
5362 } catch (Exception e) {
5363 Log.w(TAG, "Exception thrown when killing surface session "
5364 + mSurfaceSession + " in session " + this
5365 + ": " + e.toString());
5366 }
5367 mSurfaceSession = null;
5368 }
5369 }
5370 }
5371
5372 void dump(PrintWriter pw, String prefix) {
5373 pw.println(prefix + this);
5374 pw.println(prefix + "mNumWindow=" + mNumWindow
5375 + " mClientDead=" + mClientDead
5376 + " mSurfaceSession=" + mSurfaceSession);
5377 pw.println(prefix + "mPendingPointerWindow=" + mPendingPointerWindow
5378 + " mPendingPointerMove=" + mPendingPointerMove);
5379 pw.println(prefix + "mPendingTrackballWindow=" + mPendingTrackballWindow
5380 + " mPendingTrackballMove=" + mPendingTrackballMove);
5381 }
5382
5383 @Override
5384 public String toString() {
5385 return "Session{"
5386 + Integer.toHexString(System.identityHashCode(this)) + "}";
5387 }
5388 }
5389
5390 // -------------------------------------------------------------
5391 // Client Window State
5392 // -------------------------------------------------------------
5393
5394 private final class WindowState implements WindowManagerPolicy.WindowState {
5395 final Session mSession;
5396 final IWindow mClient;
5397 WindowToken mToken;
The Android Open Source Project10592532009-03-18 17:39:46 -07005398 WindowToken mRootToken;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005399 AppWindowToken mAppToken;
5400 AppWindowToken mTargetAppToken;
5401 final WindowManager.LayoutParams mAttrs = new WindowManager.LayoutParams();
5402 final DeathRecipient mDeathRecipient;
5403 final WindowState mAttachedWindow;
5404 final ArrayList mChildWindows = new ArrayList();
5405 final int mBaseLayer;
5406 final int mSubLayer;
5407 final boolean mLayoutAttached;
5408 final boolean mIsImWindow;
5409 int mViewVisibility;
5410 boolean mPolicyVisibility = true;
5411 boolean mPolicyVisibilityAfterAnim = true;
5412 boolean mAppFreezing;
5413 Surface mSurface;
5414 boolean mAttachedHidden; // is our parent window hidden?
5415 boolean mLastHidden; // was this window last hidden?
5416 int mRequestedWidth;
5417 int mRequestedHeight;
5418 int mLastRequestedWidth;
5419 int mLastRequestedHeight;
5420 int mReqXPos;
5421 int mReqYPos;
5422 int mLayer;
5423 int mAnimLayer;
5424 int mLastLayer;
5425 boolean mHaveFrame;
5426
5427 WindowState mNextOutsideTouch;
5428
5429 // Actual frame shown on-screen (may be modified by animation)
5430 final Rect mShownFrame = new Rect();
5431 final Rect mLastShownFrame = new Rect();
5432
5433 /**
5434 * Insets that determine the actually visible area
5435 */
5436 final Rect mVisibleInsets = new Rect();
5437 final Rect mLastVisibleInsets = new Rect();
5438 boolean mVisibleInsetsChanged;
5439
5440 /**
5441 * Insets that are covered by system windows
5442 */
5443 final Rect mContentInsets = new Rect();
5444 final Rect mLastContentInsets = new Rect();
5445 boolean mContentInsetsChanged;
5446
5447 /**
5448 * Set to true if we are waiting for this window to receive its
5449 * given internal insets before laying out other windows based on it.
5450 */
5451 boolean mGivenInsetsPending;
5452
5453 /**
5454 * These are the content insets that were given during layout for
5455 * this window, to be applied to windows behind it.
5456 */
5457 final Rect mGivenContentInsets = new Rect();
5458
5459 /**
5460 * These are the visible insets that were given during layout for
5461 * this window, to be applied to windows behind it.
5462 */
5463 final Rect mGivenVisibleInsets = new Rect();
5464
5465 /**
5466 * Flag indicating whether the touchable region should be adjusted by
5467 * the visible insets; if false the area outside the visible insets is
5468 * NOT touchable, so we must use those to adjust the frame during hit
5469 * tests.
5470 */
5471 int mTouchableInsets = ViewTreeObserver.InternalInsetsInfo.TOUCHABLE_INSETS_FRAME;
5472
5473 // Current transformation being applied.
5474 float mDsDx=1, mDtDx=0, mDsDy=0, mDtDy=1;
5475 float mLastDsDx=1, mLastDtDx=0, mLastDsDy=0, mLastDtDy=1;
5476 float mHScale=1, mVScale=1;
5477 float mLastHScale=1, mLastVScale=1;
5478 final Matrix mTmpMatrix = new Matrix();
5479
5480 // "Real" frame that the application sees.
5481 final Rect mFrame = new Rect();
5482 final Rect mLastFrame = new Rect();
5483
5484 final Rect mContainingFrame = new Rect();
5485 final Rect mDisplayFrame = new Rect();
5486 final Rect mContentFrame = new Rect();
5487 final Rect mVisibleFrame = new Rect();
5488
5489 float mShownAlpha = 1;
5490 float mAlpha = 1;
5491 float mLastAlpha = 1;
5492
5493 // Set to true if, when the window gets displayed, it should perform
5494 // an enter animation.
5495 boolean mEnterAnimationPending;
5496
5497 // Currently running animation.
5498 boolean mAnimating;
5499 boolean mLocalAnimating;
5500 Animation mAnimation;
5501 boolean mAnimationIsEntrance;
5502 boolean mHasTransformation;
5503 boolean mHasLocalTransformation;
5504 final Transformation mTransformation = new Transformation();
5505
5506 // This is set after IWindowSession.relayout() has been called at
5507 // least once for the window. It allows us to detect the situation
5508 // where we don't yet have a surface, but should have one soon, so
5509 // we can give the window focus before waiting for the relayout.
5510 boolean mRelayoutCalled;
5511
5512 // This is set after the Surface has been created but before the
5513 // window has been drawn. During this time the surface is hidden.
5514 boolean mDrawPending;
5515
5516 // This is set after the window has finished drawing for the first
5517 // time but before its surface is shown. The surface will be
5518 // displayed when the next layout is run.
5519 boolean mCommitDrawPending;
5520
5521 // This is set during the time after the window's drawing has been
5522 // committed, and before its surface is actually shown. It is used
5523 // to delay showing the surface until all windows in a token are ready
5524 // to be shown.
5525 boolean mReadyToShow;
5526
5527 // Set when the window has been shown in the screen the first time.
5528 boolean mHasDrawn;
5529
5530 // Currently running an exit animation?
5531 boolean mExiting;
5532
5533 // Currently on the mDestroySurface list?
5534 boolean mDestroying;
5535
5536 // Completely remove from window manager after exit animation?
5537 boolean mRemoveOnExit;
5538
5539 // Set when the orientation is changing and this window has not yet
5540 // been updated for the new orientation.
5541 boolean mOrientationChanging;
5542
5543 // Is this window now (or just being) removed?
5544 boolean mRemoved;
5545
5546 WindowState(Session s, IWindow c, WindowToken token,
5547 WindowState attachedWindow, WindowManager.LayoutParams a,
5548 int viewVisibility) {
5549 mSession = s;
5550 mClient = c;
5551 mToken = token;
5552 mAttrs.copyFrom(a);
5553 mViewVisibility = viewVisibility;
5554 DeathRecipient deathRecipient = new DeathRecipient();
5555 mAlpha = a.alpha;
5556 if (localLOGV) Log.v(
5557 TAG, "Window " + this + " client=" + c.asBinder()
5558 + " token=" + token + " (" + mAttrs.token + ")");
5559 try {
5560 c.asBinder().linkToDeath(deathRecipient, 0);
5561 } catch (RemoteException e) {
5562 mDeathRecipient = null;
5563 mAttachedWindow = null;
5564 mLayoutAttached = false;
5565 mIsImWindow = false;
5566 mBaseLayer = 0;
5567 mSubLayer = 0;
5568 return;
5569 }
5570 mDeathRecipient = deathRecipient;
5571
5572 if ((mAttrs.type >= FIRST_SUB_WINDOW &&
5573 mAttrs.type <= LAST_SUB_WINDOW)) {
5574 // The multiplier here is to reserve space for multiple
5575 // windows in the same type layer.
5576 mBaseLayer = mPolicy.windowTypeToLayerLw(
5577 attachedWindow.mAttrs.type) * TYPE_LAYER_MULTIPLIER
5578 + TYPE_LAYER_OFFSET;
5579 mSubLayer = mPolicy.subWindowTypeToLayerLw(a.type);
5580 mAttachedWindow = attachedWindow;
5581 mAttachedWindow.mChildWindows.add(this);
5582 mLayoutAttached = mAttrs.type !=
5583 WindowManager.LayoutParams.TYPE_APPLICATION_ATTACHED_DIALOG;
5584 mIsImWindow = attachedWindow.mAttrs.type == TYPE_INPUT_METHOD
5585 || attachedWindow.mAttrs.type == TYPE_INPUT_METHOD_DIALOG;
5586 } else {
5587 // The multiplier here is to reserve space for multiple
5588 // windows in the same type layer.
5589 mBaseLayer = mPolicy.windowTypeToLayerLw(a.type)
5590 * TYPE_LAYER_MULTIPLIER
5591 + TYPE_LAYER_OFFSET;
5592 mSubLayer = 0;
5593 mAttachedWindow = null;
5594 mLayoutAttached = false;
5595 mIsImWindow = mAttrs.type == TYPE_INPUT_METHOD
5596 || mAttrs.type == TYPE_INPUT_METHOD_DIALOG;
5597 }
5598
5599 WindowState appWin = this;
5600 while (appWin.mAttachedWindow != null) {
5601 appWin = mAttachedWindow;
5602 }
5603 WindowToken appToken = appWin.mToken;
5604 while (appToken.appWindowToken == null) {
5605 WindowToken parent = mTokenMap.get(appToken.token);
5606 if (parent == null || appToken == parent) {
5607 break;
5608 }
5609 appToken = parent;
5610 }
The Android Open Source Project10592532009-03-18 17:39:46 -07005611 mRootToken = appToken;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005612 mAppToken = appToken.appWindowToken;
5613
5614 mSurface = null;
5615 mRequestedWidth = 0;
5616 mRequestedHeight = 0;
5617 mLastRequestedWidth = 0;
5618 mLastRequestedHeight = 0;
5619 mReqXPos = 0;
5620 mReqYPos = 0;
5621 mLayer = 0;
5622 mAnimLayer = 0;
5623 mLastLayer = 0;
5624 }
5625
5626 void attach() {
5627 if (localLOGV) Log.v(
5628 TAG, "Attaching " + this + " token=" + mToken
5629 + ", list=" + mToken.windows);
5630 mSession.windowAddedLocked();
5631 }
5632
5633 public void computeFrameLw(Rect pf, Rect df, Rect cf, Rect vf) {
5634 mHaveFrame = true;
5635
5636 final int pw = pf.right-pf.left;
5637 final int ph = pf.bottom-pf.top;
5638
5639 int w,h;
5640 if ((mAttrs.flags & mAttrs.FLAG_SCALED) != 0) {
5641 w = mAttrs.width < 0 ? pw : mAttrs.width;
5642 h = mAttrs.height< 0 ? ph : mAttrs.height;
5643 } else {
5644 w = mAttrs.width == mAttrs.FILL_PARENT ? pw : mRequestedWidth;
5645 h = mAttrs.height== mAttrs.FILL_PARENT ? ph : mRequestedHeight;
5646 }
5647
5648 final Rect container = mContainingFrame;
5649 container.set(pf);
5650
5651 final Rect display = mDisplayFrame;
5652 display.set(df);
5653
5654 final Rect content = mContentFrame;
5655 content.set(cf);
5656
5657 final Rect visible = mVisibleFrame;
5658 visible.set(vf);
5659
5660 final Rect frame = mFrame;
5661
5662 //System.out.println("In: w=" + w + " h=" + h + " container=" +
5663 // container + " x=" + mAttrs.x + " y=" + mAttrs.y);
5664
5665 Gravity.apply(mAttrs.gravity, w, h, container,
5666 (int) (mAttrs.x + mAttrs.horizontalMargin * pw),
5667 (int) (mAttrs.y + mAttrs.verticalMargin * ph), frame);
5668
5669 //System.out.println("Out: " + mFrame);
5670
5671 // Now make sure the window fits in the overall display.
5672 Gravity.applyDisplay(mAttrs.gravity, df, frame);
5673
5674 // Make sure the content and visible frames are inside of the
5675 // final window frame.
5676 if (content.left < frame.left) content.left = frame.left;
5677 if (content.top < frame.top) content.top = frame.top;
5678 if (content.right > frame.right) content.right = frame.right;
5679 if (content.bottom > frame.bottom) content.bottom = frame.bottom;
5680 if (visible.left < frame.left) visible.left = frame.left;
5681 if (visible.top < frame.top) visible.top = frame.top;
5682 if (visible.right > frame.right) visible.right = frame.right;
5683 if (visible.bottom > frame.bottom) visible.bottom = frame.bottom;
5684
5685 final Rect contentInsets = mContentInsets;
5686 contentInsets.left = content.left-frame.left;
5687 contentInsets.top = content.top-frame.top;
5688 contentInsets.right = frame.right-content.right;
5689 contentInsets.bottom = frame.bottom-content.bottom;
5690
5691 final Rect visibleInsets = mVisibleInsets;
5692 visibleInsets.left = visible.left-frame.left;
5693 visibleInsets.top = visible.top-frame.top;
5694 visibleInsets.right = frame.right-visible.right;
5695 visibleInsets.bottom = frame.bottom-visible.bottom;
5696
5697 if (localLOGV) {
5698 //if ("com.google.android.youtube".equals(mAttrs.packageName)
5699 // && mAttrs.type == WindowManager.LayoutParams.TYPE_APPLICATION_PANEL) {
5700 Log.v(TAG, "Resolving (mRequestedWidth="
5701 + mRequestedWidth + ", mRequestedheight="
5702 + mRequestedHeight + ") to" + " (pw=" + pw + ", ph=" + ph
5703 + "): frame=" + mFrame.toShortString()
5704 + " ci=" + contentInsets.toShortString()
5705 + " vi=" + visibleInsets.toShortString());
5706 //}
5707 }
5708 }
5709
5710 public Rect getFrameLw() {
5711 return mFrame;
5712 }
5713
5714 public Rect getShownFrameLw() {
5715 return mShownFrame;
5716 }
5717
5718 public Rect getDisplayFrameLw() {
5719 return mDisplayFrame;
5720 }
5721
5722 public Rect getContentFrameLw() {
5723 return mContentFrame;
5724 }
5725
5726 public Rect getVisibleFrameLw() {
5727 return mVisibleFrame;
5728 }
5729
5730 public boolean getGivenInsetsPendingLw() {
5731 return mGivenInsetsPending;
5732 }
5733
5734 public Rect getGivenContentInsetsLw() {
5735 return mGivenContentInsets;
5736 }
5737
5738 public Rect getGivenVisibleInsetsLw() {
5739 return mGivenVisibleInsets;
5740 }
5741
5742 public WindowManager.LayoutParams getAttrs() {
5743 return mAttrs;
5744 }
5745
5746 public int getSurfaceLayer() {
5747 return mLayer;
5748 }
5749
5750 public IApplicationToken getAppToken() {
5751 return mAppToken != null ? mAppToken.appToken : null;
5752 }
5753
5754 public boolean hasAppShownWindows() {
5755 return mAppToken != null ? mAppToken.firstWindowDrawn : false;
5756 }
5757
5758 public boolean hasAppStartingIcon() {
5759 return mAppToken != null ? (mAppToken.startingData != null) : false;
5760 }
5761
5762 public WindowManagerPolicy.WindowState getAppStartingWindow() {
5763 return mAppToken != null ? mAppToken.startingWindow : null;
5764 }
5765
5766 public void setAnimation(Animation anim) {
5767 if (localLOGV) Log.v(
5768 TAG, "Setting animation in " + this + ": " + anim);
5769 mAnimating = false;
5770 mLocalAnimating = false;
5771 mAnimation = anim;
5772 mAnimation.restrictDuration(MAX_ANIMATION_DURATION);
5773 mAnimation.scaleCurrentDuration(mWindowAnimationScale);
5774 }
5775
5776 public void clearAnimation() {
5777 if (mAnimation != null) {
5778 mAnimating = true;
5779 mLocalAnimating = false;
5780 mAnimation = null;
5781 }
5782 }
5783
5784 Surface createSurfaceLocked() {
5785 if (mSurface == null) {
5786 mDrawPending = true;
5787 mCommitDrawPending = false;
5788 mReadyToShow = false;
5789 if (mAppToken != null) {
5790 mAppToken.allDrawn = false;
5791 }
5792
5793 int flags = 0;
5794 if (mAttrs.memoryType == MEMORY_TYPE_HARDWARE) {
5795 flags |= Surface.HARDWARE;
5796 } else if (mAttrs.memoryType == MEMORY_TYPE_GPU) {
5797 flags |= Surface.GPU;
5798 } else if (mAttrs.memoryType == MEMORY_TYPE_PUSH_BUFFERS) {
5799 flags |= Surface.PUSH_BUFFERS;
5800 }
5801
5802 if ((mAttrs.flags&WindowManager.LayoutParams.FLAG_SECURE) != 0) {
5803 flags |= Surface.SECURE;
5804 }
5805 if (DEBUG_VISIBILITY) Log.v(
5806 TAG, "Creating surface in session "
5807 + mSession.mSurfaceSession + " window " + this
5808 + " w=" + mFrame.width()
5809 + " h=" + mFrame.height() + " format="
5810 + mAttrs.format + " flags=" + flags);
5811
5812 int w = mFrame.width();
5813 int h = mFrame.height();
5814 if ((mAttrs.flags & LayoutParams.FLAG_SCALED) != 0) {
5815 // for a scaled surface, we always want the requested
5816 // size.
5817 w = mRequestedWidth;
5818 h = mRequestedHeight;
5819 }
5820
5821 try {
5822 mSurface = new Surface(
5823 mSession.mSurfaceSession, mSession.mPid,
5824 0, w, h, mAttrs.format, flags);
5825 } catch (Surface.OutOfResourcesException e) {
5826 Log.w(TAG, "OutOfResourcesException creating surface");
5827 reclaimSomeSurfaceMemoryLocked(this, "create");
5828 return null;
5829 } catch (Exception e) {
5830 Log.e(TAG, "Exception creating surface", e);
5831 return null;
5832 }
5833
5834 if (localLOGV) Log.v(
5835 TAG, "Got surface: " + mSurface
5836 + ", set left=" + mFrame.left + " top=" + mFrame.top
5837 + ", animLayer=" + mAnimLayer);
5838 if (SHOW_TRANSACTIONS) {
5839 Log.i(TAG, ">>> OPEN TRANSACTION");
5840 Log.i(TAG, " SURFACE " + mSurface + ": CREATE ("
5841 + mAttrs.getTitle() + ") pos=(" +
5842 mFrame.left + "," + mFrame.top + ") (" +
5843 mFrame.width() + "x" + mFrame.height() + "), layer=" +
5844 mAnimLayer + " HIDE");
5845 }
5846 Surface.openTransaction();
5847 try {
5848 try {
5849 mSurface.setPosition(mFrame.left, mFrame.top);
5850 mSurface.setLayer(mAnimLayer);
5851 mSurface.hide();
5852 if ((mAttrs.flags&WindowManager.LayoutParams.FLAG_DITHER) != 0) {
5853 mSurface.setFlags(Surface.SURFACE_DITHER,
5854 Surface.SURFACE_DITHER);
5855 }
5856 } catch (RuntimeException e) {
5857 Log.w(TAG, "Error creating surface in " + w, e);
5858 reclaimSomeSurfaceMemoryLocked(this, "create-init");
5859 }
5860 mLastHidden = true;
5861 } finally {
5862 if (SHOW_TRANSACTIONS) Log.i(TAG, "<<< CLOSE TRANSACTION");
5863 Surface.closeTransaction();
5864 }
5865 if (localLOGV) Log.v(
5866 TAG, "Created surface " + this);
5867 }
5868 return mSurface;
5869 }
5870
5871 void destroySurfaceLocked() {
5872 // Window is no longer on-screen, so can no longer receive
5873 // key events... if we were waiting for it to finish
5874 // handling a key event, the wait is over!
5875 mKeyWaiter.finishedKey(mSession, mClient, true,
5876 KeyWaiter.RETURN_NOTHING);
5877 mKeyWaiter.releasePendingPointerLocked(mSession);
5878 mKeyWaiter.releasePendingTrackballLocked(mSession);
5879
5880 if (mAppToken != null && this == mAppToken.startingWindow) {
5881 mAppToken.startingDisplayed = false;
5882 }
5883
5884 if (localLOGV) Log.v(
5885 TAG, "Window " + this
5886 + " destroying surface " + mSurface + ", session " + mSession);
5887 if (mSurface != null) {
5888 try {
5889 if (SHOW_TRANSACTIONS) {
5890 RuntimeException ex = new RuntimeException();
5891 ex.fillInStackTrace();
5892 Log.i(TAG, " SURFACE " + mSurface + ": DESTROY ("
5893 + mAttrs.getTitle() + ")", ex);
5894 }
5895 mSurface.clear();
5896 } catch (RuntimeException e) {
5897 Log.w(TAG, "Exception thrown when destroying Window " + this
5898 + " surface " + mSurface + " session " + mSession
5899 + ": " + e.toString());
5900 }
5901 mSurface = null;
5902 mDrawPending = false;
5903 mCommitDrawPending = false;
5904 mReadyToShow = false;
5905
5906 int i = mChildWindows.size();
5907 while (i > 0) {
5908 i--;
5909 WindowState c = (WindowState)mChildWindows.get(i);
5910 c.mAttachedHidden = true;
5911 }
5912 }
5913 }
5914
5915 boolean finishDrawingLocked() {
5916 if (mDrawPending) {
5917 if (SHOW_TRANSACTIONS || DEBUG_ORIENTATION) Log.v(
5918 TAG, "finishDrawingLocked: " + mSurface);
5919 mCommitDrawPending = true;
5920 mDrawPending = false;
5921 return true;
5922 }
5923 return false;
5924 }
5925
5926 // This must be called while inside a transaction.
5927 void commitFinishDrawingLocked(long currentTime) {
5928 //Log.i(TAG, "commitFinishDrawingLocked: " + mSurface);
5929 if (!mCommitDrawPending) {
5930 return;
5931 }
5932 mCommitDrawPending = false;
5933 mReadyToShow = true;
5934 final boolean starting = mAttrs.type == TYPE_APPLICATION_STARTING;
5935 final AppWindowToken atoken = mAppToken;
5936 if (atoken == null || atoken.allDrawn || starting) {
5937 performShowLocked();
5938 }
5939 }
5940
5941 // This must be called while inside a transaction.
5942 boolean performShowLocked() {
5943 if (DEBUG_VISIBILITY) {
5944 RuntimeException e = new RuntimeException();
5945 e.fillInStackTrace();
5946 Log.v(TAG, "performShow on " + this
5947 + ": readyToShow=" + mReadyToShow + " readyForDisplay=" + isReadyForDisplay()
5948 + " starting=" + (mAttrs.type == TYPE_APPLICATION_STARTING), e);
5949 }
5950 if (mReadyToShow && isReadyForDisplay()) {
5951 if (SHOW_TRANSACTIONS || DEBUG_ORIENTATION) Log.i(
5952 TAG, " SURFACE " + mSurface + ": SHOW (performShowLocked)");
5953 if (DEBUG_VISIBILITY) Log.v(TAG, "Showing " + this
5954 + " during animation: policyVis=" + mPolicyVisibility
5955 + " attHidden=" + mAttachedHidden
5956 + " tok.hiddenRequested="
5957 + (mAppToken != null ? mAppToken.hiddenRequested : false)
5958 + " tok.idden="
5959 + (mAppToken != null ? mAppToken.hidden : false)
5960 + " animating=" + mAnimating
5961 + " tok animating="
5962 + (mAppToken != null ? mAppToken.animating : false));
5963 if (!showSurfaceRobustlyLocked(this)) {
5964 return false;
5965 }
5966 mLastAlpha = -1;
5967 mHasDrawn = true;
5968 mLastHidden = false;
5969 mReadyToShow = false;
5970 enableScreenIfNeededLocked();
5971
5972 applyEnterAnimationLocked(this);
5973
5974 int i = mChildWindows.size();
5975 while (i > 0) {
5976 i--;
5977 WindowState c = (WindowState)mChildWindows.get(i);
5978 if (c.mSurface != null && c.mAttachedHidden) {
5979 c.mAttachedHidden = false;
5980 c.performShowLocked();
5981 }
5982 }
5983
5984 if (mAttrs.type != TYPE_APPLICATION_STARTING
5985 && mAppToken != null) {
5986 mAppToken.firstWindowDrawn = true;
5987 if (mAnimation == null && mAppToken.startingData != null) {
5988 if (DEBUG_STARTING_WINDOW) Log.v(TAG, "Finish starting "
5989 + mToken
5990 + ": first real window is shown, no animation");
5991 mFinishedStarting.add(mAppToken);
5992 mH.sendEmptyMessage(H.FINISHED_STARTING);
5993 }
5994 mAppToken.updateReportedVisibilityLocked();
5995 }
5996 }
5997 return true;
5998 }
5999
6000 // This must be called while inside a transaction. Returns true if
6001 // there is more animation to run.
6002 boolean stepAnimationLocked(long currentTime, int dw, int dh) {
6003 if (!mDisplayFrozen) {
6004 // We will run animations as long as the display isn't frozen.
6005
6006 if (!mDrawPending && !mCommitDrawPending && mAnimation != null) {
6007 mHasTransformation = true;
6008 mHasLocalTransformation = true;
6009 if (!mLocalAnimating) {
6010 if (DEBUG_ANIM) Log.v(
6011 TAG, "Starting animation in " + this +
6012 " @ " + currentTime + ": ww=" + mFrame.width() + " wh=" + mFrame.height() +
6013 " dw=" + dw + " dh=" + dh + " scale=" + mWindowAnimationScale);
6014 mAnimation.initialize(mFrame.width(), mFrame.height(), dw, dh);
6015 mAnimation.setStartTime(currentTime);
6016 mLocalAnimating = true;
6017 mAnimating = true;
6018 }
6019 mTransformation.clear();
6020 final boolean more = mAnimation.getTransformation(
6021 currentTime, mTransformation);
6022 if (DEBUG_ANIM) Log.v(
6023 TAG, "Stepped animation in " + this +
6024 ": more=" + more + ", xform=" + mTransformation);
6025 if (more) {
6026 // we're not done!
6027 return true;
6028 }
6029 if (DEBUG_ANIM) Log.v(
6030 TAG, "Finished animation in " + this +
6031 " @ " + currentTime);
6032 mAnimation = null;
6033 //WindowManagerService.this.dump();
6034 }
6035 mHasLocalTransformation = false;
6036 if ((!mLocalAnimating || mAnimationIsEntrance) && mAppToken != null
6037 && mAppToken.hasTransformation) {
6038 // When our app token is animating, we kind-of pretend like
6039 // we are as well. Note the mLocalAnimating mAnimationIsEntrance
6040 // part of this check means that we will only do this if
6041 // our window is not currently exiting, or it is not
6042 // locally animating itself. The idea being that one that
6043 // is exiting and doing a local animation should be removed
6044 // once that animation is done.
6045 mAnimating = true;
6046 mHasTransformation = true;
6047 mTransformation.clear();
6048 return false;
6049 } else if (mHasTransformation) {
6050 // Little trick to get through the path below to act like
6051 // we have finished an animation.
6052 mAnimating = true;
6053 } else if (isAnimating()) {
6054 mAnimating = true;
6055 }
6056 } else if (mAnimation != null) {
6057 // If the display is frozen, and there is a pending animation,
6058 // clear it and make sure we run the cleanup code.
6059 mAnimating = true;
6060 mLocalAnimating = true;
6061 mAnimation = null;
6062 }
6063
6064 if (!mAnimating && !mLocalAnimating) {
6065 return false;
6066 }
6067
6068 if (DEBUG_ANIM) Log.v(
6069 TAG, "Animation done in " + this + ": exiting=" + mExiting
6070 + ", reportedVisible="
6071 + (mAppToken != null ? mAppToken.reportedVisible : false));
6072
6073 mAnimating = false;
6074 mLocalAnimating = false;
6075 mAnimation = null;
6076 mAnimLayer = mLayer;
6077 if (mIsImWindow) {
6078 mAnimLayer += mInputMethodAnimLayerAdjustment;
6079 }
6080 if (DEBUG_LAYERS) Log.v(TAG, "Stepping win " + this
6081 + " anim layer: " + mAnimLayer);
6082 mHasTransformation = false;
6083 mHasLocalTransformation = false;
6084 mPolicyVisibility = mPolicyVisibilityAfterAnim;
6085 mTransformation.clear();
6086 if (mHasDrawn
6087 && mAttrs.type == WindowManager.LayoutParams.TYPE_APPLICATION_STARTING
6088 && mAppToken != null
6089 && mAppToken.firstWindowDrawn
6090 && mAppToken.startingData != null) {
6091 if (DEBUG_STARTING_WINDOW) Log.v(TAG, "Finish starting "
6092 + mToken + ": first real window done animating");
6093 mFinishedStarting.add(mAppToken);
6094 mH.sendEmptyMessage(H.FINISHED_STARTING);
6095 }
6096
6097 finishExit();
6098
6099 if (mAppToken != null) {
6100 mAppToken.updateReportedVisibilityLocked();
6101 }
6102
6103 return false;
6104 }
6105
6106 void finishExit() {
6107 if (DEBUG_ANIM) Log.v(
6108 TAG, "finishExit in " + this
6109 + ": exiting=" + mExiting
6110 + " remove=" + mRemoveOnExit
6111 + " windowAnimating=" + isWindowAnimating());
6112
6113 final int N = mChildWindows.size();
6114 for (int i=0; i<N; i++) {
6115 ((WindowState)mChildWindows.get(i)).finishExit();
6116 }
6117
6118 if (!mExiting) {
6119 return;
6120 }
6121
6122 if (isWindowAnimating()) {
6123 return;
6124 }
6125
6126 if (localLOGV) Log.v(
6127 TAG, "Exit animation finished in " + this
6128 + ": remove=" + mRemoveOnExit);
6129 if (mSurface != null) {
6130 mDestroySurface.add(this);
6131 mDestroying = true;
6132 if (SHOW_TRANSACTIONS) Log.i(
6133 TAG, " SURFACE " + mSurface + ": HIDE (finishExit)");
6134 try {
6135 mSurface.hide();
6136 } catch (RuntimeException e) {
6137 Log.w(TAG, "Error hiding surface in " + this, e);
6138 }
6139 mLastHidden = true;
6140 mKeyWaiter.releasePendingPointerLocked(mSession);
6141 }
6142 mExiting = false;
6143 if (mRemoveOnExit) {
6144 mPendingRemove.add(this);
6145 mRemoveOnExit = false;
6146 }
6147 }
6148
6149 boolean isIdentityMatrix(float dsdx, float dtdx, float dsdy, float dtdy) {
6150 if (dsdx < .99999f || dsdx > 1.00001f) return false;
6151 if (dtdy < .99999f || dtdy > 1.00001f) return false;
6152 if (dtdx < -.000001f || dtdx > .000001f) return false;
6153 if (dsdy < -.000001f || dsdy > .000001f) return false;
6154 return true;
6155 }
6156
6157 void computeShownFrameLocked() {
6158 final boolean selfTransformation = mHasLocalTransformation;
6159 Transformation attachedTransformation =
6160 (mAttachedWindow != null && mAttachedWindow.mHasLocalTransformation)
6161 ? mAttachedWindow.mTransformation : null;
6162 Transformation appTransformation =
6163 (mAppToken != null && mAppToken.hasTransformation)
6164 ? mAppToken.transformation : null;
6165 if (selfTransformation || attachedTransformation != null
6166 || appTransformation != null) {
6167 // cache often used attributes locally
6168 final Rect frame = mFrame;
6169 final float tmpFloats[] = mTmpFloats;
6170 final Matrix tmpMatrix = mTmpMatrix;
6171
6172 // Compute the desired transformation.
6173 tmpMatrix.setTranslate(frame.left, frame.top);
6174 if (selfTransformation) {
6175 tmpMatrix.preConcat(mTransformation.getMatrix());
6176 }
6177 if (attachedTransformation != null) {
6178 tmpMatrix.preConcat(attachedTransformation.getMatrix());
6179 }
6180 if (appTransformation != null) {
6181 tmpMatrix.preConcat(appTransformation.getMatrix());
6182 }
6183
6184 // "convert" it into SurfaceFlinger's format
6185 // (a 2x2 matrix + an offset)
6186 // Here we must not transform the position of the surface
6187 // since it is already included in the transformation.
6188 //Log.i(TAG, "Transform: " + matrix);
6189
6190 tmpMatrix.getValues(tmpFloats);
6191 mDsDx = tmpFloats[Matrix.MSCALE_X];
6192 mDtDx = tmpFloats[Matrix.MSKEW_X];
6193 mDsDy = tmpFloats[Matrix.MSKEW_Y];
6194 mDtDy = tmpFloats[Matrix.MSCALE_Y];
6195 int x = (int)tmpFloats[Matrix.MTRANS_X];
6196 int y = (int)tmpFloats[Matrix.MTRANS_Y];
6197 int w = frame.width();
6198 int h = frame.height();
6199 mShownFrame.set(x, y, x+w, y+h);
6200
6201 // Now set the alpha... but because our current hardware
6202 // can't do alpha transformation on a non-opaque surface,
6203 // turn it off if we are running an animation that is also
6204 // transforming since it is more important to have that
6205 // animation be smooth.
6206 mShownAlpha = mAlpha;
6207 if (!mLimitedAlphaCompositing
6208 || (!PixelFormat.formatHasAlpha(mAttrs.format)
6209 || (isIdentityMatrix(mDsDx, mDtDx, mDsDy, mDtDy)
6210 && x == frame.left && y == frame.top))) {
6211 //Log.i(TAG, "Applying alpha transform");
6212 if (selfTransformation) {
6213 mShownAlpha *= mTransformation.getAlpha();
6214 }
6215 if (attachedTransformation != null) {
6216 mShownAlpha *= attachedTransformation.getAlpha();
6217 }
6218 if (appTransformation != null) {
6219 mShownAlpha *= appTransformation.getAlpha();
6220 }
6221 } else {
6222 //Log.i(TAG, "Not applying alpha transform");
6223 }
6224
6225 if (localLOGV) Log.v(
6226 TAG, "Continuing animation in " + this +
6227 ": " + mShownFrame +
6228 ", alpha=" + mTransformation.getAlpha());
6229 return;
6230 }
6231
6232 mShownFrame.set(mFrame);
6233 mShownAlpha = mAlpha;
6234 mDsDx = 1;
6235 mDtDx = 0;
6236 mDsDy = 0;
6237 mDtDy = 1;
6238 }
6239
6240 /**
6241 * Is this window visible? It is not visible if there is no
6242 * surface, or we are in the process of running an exit animation
6243 * that will remove the surface, or its app token has been hidden.
6244 */
6245 public boolean isVisibleLw() {
6246 final AppWindowToken atoken = mAppToken;
6247 return mSurface != null && mPolicyVisibility && !mAttachedHidden
6248 && (atoken == null || !atoken.hiddenRequested)
6249 && !mExiting && !mDestroying;
6250 }
6251
6252 /**
6253 * Is this window visible, ignoring its app token? It is not visible
6254 * if there is no surface, or we are in the process of running an exit animation
6255 * that will remove the surface.
6256 */
6257 public boolean isWinVisibleLw() {
6258 final AppWindowToken atoken = mAppToken;
6259 return mSurface != null && mPolicyVisibility && !mAttachedHidden
6260 && (atoken == null || !atoken.hiddenRequested || atoken.animating)
6261 && !mExiting && !mDestroying;
6262 }
6263
6264 /**
6265 * The same as isVisible(), but follows the current hidden state of
6266 * the associated app token, not the pending requested hidden state.
6267 */
6268 boolean isVisibleNow() {
6269 return mSurface != null && mPolicyVisibility && !mAttachedHidden
The Android Open Source Project10592532009-03-18 17:39:46 -07006270 && !mRootToken.hidden && !mExiting && !mDestroying;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006271 }
6272
6273 /**
6274 * Same as isVisible(), but we also count it as visible between the
6275 * call to IWindowSession.add() and the first relayout().
6276 */
6277 boolean isVisibleOrAdding() {
6278 final AppWindowToken atoken = mAppToken;
6279 return (mSurface != null
6280 || (!mRelayoutCalled && mViewVisibility == View.VISIBLE))
6281 && mPolicyVisibility && !mAttachedHidden
6282 && (atoken == null || !atoken.hiddenRequested)
6283 && !mExiting && !mDestroying;
6284 }
6285
6286 /**
6287 * Is this window currently on-screen? It is on-screen either if it
6288 * is visible or it is currently running an animation before no longer
6289 * being visible.
6290 */
6291 boolean isOnScreen() {
6292 final AppWindowToken atoken = mAppToken;
6293 if (atoken != null) {
6294 return mSurface != null && mPolicyVisibility && !mDestroying
6295 && ((!mAttachedHidden && !atoken.hiddenRequested)
6296 || mAnimating || atoken.animating);
6297 } else {
6298 return mSurface != null && mPolicyVisibility && !mDestroying
6299 && (!mAttachedHidden || mAnimating);
6300 }
6301 }
6302
6303 /**
6304 * Like isOnScreen(), but we don't return true if the window is part
6305 * of a transition that has not yet been started.
6306 */
6307 boolean isReadyForDisplay() {
6308 final AppWindowToken atoken = mAppToken;
6309 final boolean animating = atoken != null ? atoken.animating : false;
6310 return mSurface != null && mPolicyVisibility && !mDestroying
The Android Open Source Project10592532009-03-18 17:39:46 -07006311 && ((!mAttachedHidden && !mRootToken.hidden)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006312 || mAnimating || animating);
6313 }
6314
6315 /** Is the window or its container currently animating? */
6316 boolean isAnimating() {
6317 final WindowState attached = mAttachedWindow;
6318 final AppWindowToken atoken = mAppToken;
6319 return mAnimation != null
6320 || (attached != null && attached.mAnimation != null)
6321 || (atoken != null &&
6322 (atoken.animation != null
6323 || atoken.inPendingTransaction));
6324 }
6325
6326 /** Is this window currently animating? */
6327 boolean isWindowAnimating() {
6328 return mAnimation != null;
6329 }
6330
6331 /**
6332 * Like isOnScreen, but returns false if the surface hasn't yet
6333 * been drawn.
6334 */
6335 public boolean isDisplayedLw() {
6336 final AppWindowToken atoken = mAppToken;
6337 return mSurface != null && mPolicyVisibility && !mDestroying
6338 && !mDrawPending && !mCommitDrawPending
6339 && ((!mAttachedHidden &&
6340 (atoken == null || !atoken.hiddenRequested))
6341 || mAnimating);
6342 }
6343
6344 public boolean fillsScreenLw(int screenWidth, int screenHeight,
6345 boolean shownFrame, boolean onlyOpaque) {
6346 if (mSurface == null) {
6347 return false;
6348 }
6349 if (mAppToken != null && !mAppToken.appFullscreen) {
6350 return false;
6351 }
6352 if (onlyOpaque && mAttrs.format != PixelFormat.OPAQUE) {
6353 return false;
6354 }
6355 final Rect frame = shownFrame ? mShownFrame : mFrame;
6356 if (frame.left <= 0 && frame.top <= 0
6357 && frame.right >= screenWidth
6358 && frame.bottom >= screenHeight) {
6359 return true;
6360 }
6361 return false;
6362 }
6363
6364 boolean isFullscreenOpaque(int screenWidth, int screenHeight) {
6365 if (mAttrs.format != PixelFormat.OPAQUE || mSurface == null
6366 || mAnimation != null || mDrawPending || mCommitDrawPending) {
6367 return false;
6368 }
6369 if (mFrame.left <= 0 && mFrame.top <= 0 &&
6370 mFrame.right >= screenWidth && mFrame.bottom >= screenHeight) {
6371 return true;
6372 }
6373 return false;
6374 }
6375
6376 void removeLocked() {
6377 if (mAttachedWindow != null) {
6378 mAttachedWindow.mChildWindows.remove(this);
6379 }
6380 destroySurfaceLocked();
6381 mSession.windowRemovedLocked();
6382 try {
6383 mClient.asBinder().unlinkToDeath(mDeathRecipient, 0);
6384 } catch (RuntimeException e) {
6385 // Ignore if it has already been removed (usually because
6386 // we are doing this as part of processing a death note.)
6387 }
6388 }
6389
6390 private class DeathRecipient implements IBinder.DeathRecipient {
6391 public void binderDied() {
6392 try {
6393 synchronized(mWindowMap) {
6394 WindowState win = windowForClientLocked(mSession, mClient);
6395 Log.i(TAG, "WIN DEATH: " + win);
6396 if (win != null) {
6397 removeWindowLocked(mSession, win);
6398 }
6399 }
6400 } catch (IllegalArgumentException ex) {
6401 // This will happen if the window has already been
6402 // removed.
6403 }
6404 }
6405 }
6406
6407 /** Returns true if this window desires key events. */
6408 public final boolean canReceiveKeys() {
6409 return isVisibleOrAdding()
6410 && (mViewVisibility == View.VISIBLE)
6411 && ((mAttrs.flags & WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE) == 0);
6412 }
6413
6414 public boolean hasDrawnLw() {
6415 return mHasDrawn;
6416 }
6417
6418 public boolean showLw(boolean doAnimation) {
6419 if (!mPolicyVisibility || !mPolicyVisibilityAfterAnim) {
6420 mPolicyVisibility = true;
6421 mPolicyVisibilityAfterAnim = true;
6422 if (doAnimation) {
6423 applyAnimationLocked(this, WindowManagerPolicy.TRANSIT_ENTER, true);
6424 }
6425 requestAnimationLocked(0);
6426 return true;
6427 }
6428 return false;
6429 }
6430
6431 public boolean hideLw(boolean doAnimation) {
6432 boolean current = doAnimation ? mPolicyVisibilityAfterAnim
6433 : mPolicyVisibility;
6434 if (current) {
6435 if (doAnimation) {
6436 applyAnimationLocked(this, WindowManagerPolicy.TRANSIT_EXIT, false);
6437 if (mAnimation == null) {
6438 doAnimation = false;
6439 }
6440 }
6441 if (doAnimation) {
6442 mPolicyVisibilityAfterAnim = false;
6443 } else {
6444 mPolicyVisibilityAfterAnim = false;
6445 mPolicyVisibility = false;
6446 }
6447 requestAnimationLocked(0);
6448 return true;
6449 }
6450 return false;
6451 }
6452
6453 void dump(PrintWriter pw, String prefix) {
6454 pw.println(prefix + this);
6455 pw.println(prefix + "mSession=" + mSession
6456 + " mClient=" + mClient.asBinder());
6457 pw.println(prefix + "mAttrs=" + mAttrs);
6458 pw.println(prefix + "mAttachedWindow=" + mAttachedWindow
6459 + " mLayoutAttached=" + mLayoutAttached
6460 + " mIsImWindow=" + mIsImWindow);
6461 pw.println(prefix + "mBaseLayer=" + mBaseLayer
6462 + " mSubLayer=" + mSubLayer
6463 + " mAnimLayer=" + mLayer + "+"
6464 + (mTargetAppToken != null ? mTargetAppToken.animLayerAdjustment
6465 : (mAppToken != null ? mAppToken.animLayerAdjustment : 0))
6466 + "=" + mAnimLayer
6467 + " mLastLayer=" + mLastLayer);
6468 pw.println(prefix + "mSurface=" + mSurface);
6469 pw.println(prefix + "mToken=" + mToken);
The Android Open Source Project10592532009-03-18 17:39:46 -07006470 pw.println(prefix + "mRootToken=" + mRootToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006471 pw.println(prefix + "mAppToken=" + mAppToken);
6472 pw.println(prefix + "mTargetAppToken=" + mTargetAppToken);
6473 pw.println(prefix + "mViewVisibility=0x" + Integer.toHexString(mViewVisibility)
6474 + " mPolicyVisibility=" + mPolicyVisibility
6475 + " (after=" + mPolicyVisibilityAfterAnim
6476 + ") mAttachedHidden=" + mAttachedHidden
6477 + " mLastHidden=" + mLastHidden
6478 + " mHaveFrame=" + mHaveFrame);
6479 pw.println(prefix + "Requested w=" + mRequestedWidth + " h=" + mRequestedHeight
6480 + " x=" + mReqXPos + " y=" + mReqYPos);
6481 pw.println(prefix + "mGivenContentInsets=" + mGivenContentInsets.toShortString()
6482 + " mGivenVisibleInsets=" + mGivenVisibleInsets.toShortString()
6483 + " mTouchableInsets=" + mTouchableInsets
6484 + " pending=" + mGivenInsetsPending);
6485 pw.println(prefix + "mShownFrame=" + mShownFrame.toShortString()
6486 + " last=" + mLastShownFrame.toShortString());
6487 pw.println(prefix + "mFrame=" + mFrame.toShortString()
6488 + " last=" + mLastFrame.toShortString());
6489 pw.println(prefix + "mContainingFrame=" + mContainingFrame.toShortString()
6490 + " mDisplayFrame=" + mDisplayFrame.toShortString());
6491 pw.println(prefix + "mContentFrame=" + mContentFrame.toShortString()
6492 + " mVisibleFrame=" + mVisibleFrame.toShortString());
6493 pw.println(prefix + "mContentInsets=" + mContentInsets.toShortString()
6494 + " last=" + mLastContentInsets.toShortString()
6495 + " mVisibleInsets=" + mVisibleInsets.toShortString()
6496 + " last=" + mLastVisibleInsets.toShortString());
6497 pw.println(prefix + "mShownAlpha=" + mShownAlpha
6498 + " mAlpha=" + mAlpha + " mLastAlpha=" + mLastAlpha);
6499 pw.println(prefix + "mAnimating=" + mAnimating
6500 + " mLocalAnimating=" + mLocalAnimating
6501 + " mAnimationIsEntrance=" + mAnimationIsEntrance
6502 + " mAnimation=" + mAnimation);
6503 pw.println(prefix + "XForm: has=" + mHasTransformation
6504 + " " + mTransformation.toShortString());
6505 pw.println(prefix + "mDrawPending=" + mDrawPending
6506 + " mCommitDrawPending=" + mCommitDrawPending
6507 + " mReadyToShow=" + mReadyToShow
6508 + " mHasDrawn=" + mHasDrawn);
6509 pw.println(prefix + "mExiting=" + mExiting
6510 + " mRemoveOnExit=" + mRemoveOnExit
6511 + " mDestroying=" + mDestroying
6512 + " mRemoved=" + mRemoved);
6513 pw.println(prefix + "mOrientationChanging=" + mOrientationChanging
6514 + " mAppFreezing=" + mAppFreezing);
6515 }
6516
6517 @Override
6518 public String toString() {
6519 return "Window{"
6520 + Integer.toHexString(System.identityHashCode(this))
6521 + " " + mAttrs.getTitle() + " paused=" + mToken.paused + "}";
6522 }
6523 }
6524
6525 // -------------------------------------------------------------
6526 // Window Token State
6527 // -------------------------------------------------------------
6528
6529 class WindowToken {
6530 // The actual token.
6531 final IBinder token;
6532
6533 // The type of window this token is for, as per WindowManager.LayoutParams.
6534 final int windowType;
6535
6536 // Set if this token was explicitly added by a client, so should
6537 // not be removed when all windows are removed.
6538 final boolean explicit;
6539
6540 // If this is an AppWindowToken, this is non-null.
6541 AppWindowToken appWindowToken;
6542
6543 // All of the windows associated with this token.
6544 final ArrayList<WindowState> windows = new ArrayList<WindowState>();
6545
6546 // Is key dispatching paused for this token?
6547 boolean paused = false;
6548
6549 // Should this token's windows be hidden?
6550 boolean hidden;
6551
6552 // Temporary for finding which tokens no longer have visible windows.
6553 boolean hasVisible;
6554
6555 WindowToken(IBinder _token, int type, boolean _explicit) {
6556 token = _token;
6557 windowType = type;
6558 explicit = _explicit;
6559 }
6560
6561 void dump(PrintWriter pw, String prefix) {
6562 pw.println(prefix + this);
6563 pw.println(prefix + "token=" + token);
6564 pw.println(prefix + "windows=" + windows);
6565 pw.println(prefix + "windowType=" + windowType + " hidden=" + hidden
6566 + " hasVisible=" + hasVisible);
6567 }
6568
6569 @Override
6570 public String toString() {
6571 return "WindowToken{"
6572 + Integer.toHexString(System.identityHashCode(this))
6573 + " token=" + token + "}";
6574 }
6575 };
6576
6577 class AppWindowToken extends WindowToken {
6578 // Non-null only for application tokens.
6579 final IApplicationToken appToken;
6580
6581 // All of the windows and child windows that are included in this
6582 // application token. Note this list is NOT sorted!
6583 final ArrayList<WindowState> allAppWindows = new ArrayList<WindowState>();
6584
6585 int groupId = -1;
6586 boolean appFullscreen;
6587 int requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
6588
6589 // These are used for determining when all windows associated with
6590 // an activity have been drawn, so they can be made visible together
6591 // at the same time.
6592 int lastTransactionSequence = mTransactionSequence-1;
6593 int numInterestingWindows;
6594 int numDrawnWindows;
6595 boolean inPendingTransaction;
6596 boolean allDrawn;
6597
6598 // Is this token going to be hidden in a little while? If so, it
6599 // won't be taken into account for setting the screen orientation.
6600 boolean willBeHidden;
6601
6602 // Is this window's surface needed? This is almost like hidden, except
6603 // it will sometimes be true a little earlier: when the token has
6604 // been shown, but is still waiting for its app transition to execute
6605 // before making its windows shown.
6606 boolean hiddenRequested;
6607
6608 // Have we told the window clients to hide themselves?
6609 boolean clientHidden;
6610
6611 // Last visibility state we reported to the app token.
6612 boolean reportedVisible;
6613
6614 // Set to true when the token has been removed from the window mgr.
6615 boolean removed;
6616
6617 // Have we been asked to have this token keep the screen frozen?
6618 boolean freezingScreen;
6619
6620 boolean animating;
6621 Animation animation;
6622 boolean hasTransformation;
6623 final Transformation transformation = new Transformation();
6624
6625 // Offset to the window of all layers in the token, for use by
6626 // AppWindowToken animations.
6627 int animLayerAdjustment;
6628
6629 // Information about an application starting window if displayed.
6630 StartingData startingData;
6631 WindowState startingWindow;
6632 View startingView;
6633 boolean startingDisplayed;
6634 boolean startingMoved;
6635 boolean firstWindowDrawn;
6636
6637 AppWindowToken(IApplicationToken _token) {
6638 super(_token.asBinder(),
6639 WindowManager.LayoutParams.TYPE_APPLICATION, true);
6640 appWindowToken = this;
6641 appToken = _token;
6642 }
6643
6644 public void setAnimation(Animation anim) {
6645 if (localLOGV) Log.v(
6646 TAG, "Setting animation in " + this + ": " + anim);
6647 animation = anim;
6648 animating = false;
6649 anim.restrictDuration(MAX_ANIMATION_DURATION);
6650 anim.scaleCurrentDuration(mTransitionAnimationScale);
6651 int zorder = anim.getZAdjustment();
6652 int adj = 0;
6653 if (zorder == Animation.ZORDER_TOP) {
6654 adj = TYPE_LAYER_OFFSET;
6655 } else if (zorder == Animation.ZORDER_BOTTOM) {
6656 adj = -TYPE_LAYER_OFFSET;
6657 }
6658
6659 if (animLayerAdjustment != adj) {
6660 animLayerAdjustment = adj;
6661 updateLayers();
6662 }
6663 }
6664
6665 public void setDummyAnimation() {
6666 if (animation == null) {
6667 if (localLOGV) Log.v(
6668 TAG, "Setting dummy animation in " + this);
6669 animation = sDummyAnimation;
6670 }
6671 }
6672
6673 public void clearAnimation() {
6674 if (animation != null) {
6675 animation = null;
6676 animating = true;
6677 }
6678 }
6679
6680 void updateLayers() {
6681 final int N = allAppWindows.size();
6682 final int adj = animLayerAdjustment;
6683 for (int i=0; i<N; i++) {
6684 WindowState w = allAppWindows.get(i);
6685 w.mAnimLayer = w.mLayer + adj;
6686 if (DEBUG_LAYERS) Log.v(TAG, "Updating layer " + w + ": "
6687 + w.mAnimLayer);
6688 if (w == mInputMethodTarget) {
6689 setInputMethodAnimLayerAdjustment(adj);
6690 }
6691 }
6692 }
6693
6694 void sendAppVisibilityToClients() {
6695 final int N = allAppWindows.size();
6696 for (int i=0; i<N; i++) {
6697 WindowState win = allAppWindows.get(i);
6698 if (win == startingWindow && clientHidden) {
6699 // Don't hide the starting window.
6700 continue;
6701 }
6702 try {
6703 if (DEBUG_VISIBILITY) Log.v(TAG,
6704 "Setting visibility of " + win + ": " + (!clientHidden));
6705 win.mClient.dispatchAppVisibility(!clientHidden);
6706 } catch (RemoteException e) {
6707 }
6708 }
6709 }
6710
6711 void showAllWindowsLocked() {
6712 final int NW = allAppWindows.size();
6713 for (int i=0; i<NW; i++) {
6714 WindowState w = allAppWindows.get(i);
6715 if (DEBUG_VISIBILITY) Log.v(TAG,
6716 "performing show on: " + w);
6717 w.performShowLocked();
6718 }
6719 }
6720
6721 // This must be called while inside a transaction.
6722 boolean stepAnimationLocked(long currentTime, int dw, int dh) {
6723 if (!mDisplayFrozen) {
6724 // We will run animations as long as the display isn't frozen.
6725
6726 if (animation == sDummyAnimation) {
6727 // This guy is going to animate, but not yet. For now count
6728 // it is not animating for purposes of scheduling transactions;
6729 // when it is really time to animate, this will be set to
6730 // a real animation and the next call will execute normally.
6731 return false;
6732 }
6733
6734 if ((allDrawn || animating || startingDisplayed) && animation != null) {
6735 if (!animating) {
6736 if (DEBUG_ANIM) Log.v(
6737 TAG, "Starting animation in " + this +
6738 " @ " + currentTime + ": dw=" + dw + " dh=" + dh
6739 + " scale=" + mTransitionAnimationScale
6740 + " allDrawn=" + allDrawn + " animating=" + animating);
6741 animation.initialize(dw, dh, dw, dh);
6742 animation.setStartTime(currentTime);
6743 animating = true;
6744 }
6745 transformation.clear();
6746 final boolean more = animation.getTransformation(
6747 currentTime, transformation);
6748 if (DEBUG_ANIM) Log.v(
6749 TAG, "Stepped animation in " + this +
6750 ": more=" + more + ", xform=" + transformation);
6751 if (more) {
6752 // we're done!
6753 hasTransformation = true;
6754 return true;
6755 }
6756 if (DEBUG_ANIM) Log.v(
6757 TAG, "Finished animation in " + this +
6758 " @ " + currentTime);
6759 animation = null;
6760 }
6761 } else if (animation != null) {
6762 // If the display is frozen, and there is a pending animation,
6763 // clear it and make sure we run the cleanup code.
6764 animating = true;
6765 animation = null;
6766 }
6767
6768 hasTransformation = false;
6769
6770 if (!animating) {
6771 return false;
6772 }
6773
6774 clearAnimation();
6775 animating = false;
6776 if (mInputMethodTarget != null && mInputMethodTarget.mAppToken == this) {
6777 moveInputMethodWindowsIfNeededLocked(true);
6778 }
6779
6780 if (DEBUG_ANIM) Log.v(
6781 TAG, "Animation done in " + this
6782 + ": reportedVisible=" + reportedVisible);
6783
6784 transformation.clear();
6785 if (animLayerAdjustment != 0) {
6786 animLayerAdjustment = 0;
6787 updateLayers();
6788 }
6789
6790 final int N = windows.size();
6791 for (int i=0; i<N; i++) {
6792 ((WindowState)windows.get(i)).finishExit();
6793 }
6794 updateReportedVisibilityLocked();
6795
6796 return false;
6797 }
6798
6799 void updateReportedVisibilityLocked() {
6800 if (appToken == null) {
6801 return;
6802 }
6803
6804 int numInteresting = 0;
6805 int numVisible = 0;
6806 boolean nowGone = true;
6807
6808 if (DEBUG_VISIBILITY) Log.v(TAG, "Update reported visibility: " + this);
6809 final int N = allAppWindows.size();
6810 for (int i=0; i<N; i++) {
6811 WindowState win = allAppWindows.get(i);
6812 if (win == startingWindow || win.mAppFreezing) {
6813 continue;
6814 }
6815 if (DEBUG_VISIBILITY) {
6816 Log.v(TAG, "Win " + win + ": isDisplayed="
6817 + win.isDisplayedLw()
6818 + ", isAnimating=" + win.isAnimating());
6819 if (!win.isDisplayedLw()) {
6820 Log.v(TAG, "Not displayed: s=" + win.mSurface
6821 + " pv=" + win.mPolicyVisibility
6822 + " dp=" + win.mDrawPending
6823 + " cdp=" + win.mCommitDrawPending
6824 + " ah=" + win.mAttachedHidden
6825 + " th="
6826 + (win.mAppToken != null
6827 ? win.mAppToken.hiddenRequested : false)
6828 + " a=" + win.mAnimating);
6829 }
6830 }
6831 numInteresting++;
6832 if (win.isDisplayedLw()) {
6833 if (!win.isAnimating()) {
6834 numVisible++;
6835 }
6836 nowGone = false;
6837 } else if (win.isAnimating()) {
6838 nowGone = false;
6839 }
6840 }
6841
6842 boolean nowVisible = numInteresting > 0 && numVisible >= numInteresting;
6843 if (DEBUG_VISIBILITY) Log.v(TAG, "VIS " + this + ": interesting="
6844 + numInteresting + " visible=" + numVisible);
6845 if (nowVisible != reportedVisible) {
6846 if (DEBUG_VISIBILITY) Log.v(
6847 TAG, "Visibility changed in " + this
6848 + ": vis=" + nowVisible);
6849 reportedVisible = nowVisible;
6850 Message m = mH.obtainMessage(
6851 H.REPORT_APPLICATION_TOKEN_WINDOWS,
6852 nowVisible ? 1 : 0,
6853 nowGone ? 1 : 0,
6854 this);
6855 mH.sendMessage(m);
6856 }
6857 }
6858
6859 void dump(PrintWriter pw, String prefix) {
6860 super.dump(pw, prefix);
6861 pw.println(prefix + "app=" + (appToken != null));
6862 pw.println(prefix + "allAppWindows=" + allAppWindows);
6863 pw.println(prefix + "groupId=" + groupId
6864 + " requestedOrientation=" + requestedOrientation);
6865 pw.println(prefix + "hiddenRequested=" + hiddenRequested
6866 + " clientHidden=" + clientHidden
6867 + " willBeHidden=" + willBeHidden
6868 + " reportedVisible=" + reportedVisible);
6869 pw.println(prefix + "paused=" + paused
6870 + " freezingScreen=" + freezingScreen);
6871 pw.println(prefix + "numInterestingWindows=" + numInterestingWindows
6872 + " numDrawnWindows=" + numDrawnWindows
6873 + " inPendingTransaction=" + inPendingTransaction
6874 + " allDrawn=" + allDrawn);
6875 pw.println(prefix + "animating=" + animating
6876 + " animation=" + animation);
6877 pw.println(prefix + "animLayerAdjustment=" + animLayerAdjustment
6878 + " transformation=" + transformation.toShortString());
6879 pw.println(prefix + "startingData=" + startingData
6880 + " removed=" + removed
6881 + " firstWindowDrawn=" + firstWindowDrawn);
6882 pw.println(prefix + "startingWindow=" + startingWindow
6883 + " startingView=" + startingView
6884 + " startingDisplayed=" + startingDisplayed
6885 + " startingMoved" + startingMoved);
6886 }
6887
6888 @Override
6889 public String toString() {
6890 return "AppWindowToken{"
6891 + Integer.toHexString(System.identityHashCode(this))
6892 + " token=" + token + "}";
6893 }
6894 }
6895
6896 public static WindowManager.LayoutParams findAnimations(
6897 ArrayList<AppWindowToken> order,
6898 ArrayList<AppWindowToken> tokenList1,
6899 ArrayList<AppWindowToken> tokenList2) {
6900 // We need to figure out which animation to use...
6901 WindowManager.LayoutParams animParams = null;
6902 int animSrc = 0;
6903
6904 //Log.i(TAG, "Looking for animations...");
6905 for (int i=order.size()-1; i>=0; i--) {
6906 AppWindowToken wtoken = order.get(i);
6907 //Log.i(TAG, "Token " + wtoken + " with " + wtoken.windows.size() + " windows");
6908 if (tokenList1.contains(wtoken) || tokenList2.contains(wtoken)) {
6909 int j = wtoken.windows.size();
6910 while (j > 0) {
6911 j--;
6912 WindowState win = wtoken.windows.get(j);
6913 //Log.i(TAG, "Window " + win + ": type=" + win.mAttrs.type);
6914 if (win.mAttrs.type == WindowManager.LayoutParams.TYPE_BASE_APPLICATION
6915 || win.mAttrs.type == WindowManager.LayoutParams.TYPE_APPLICATION_STARTING) {
6916 //Log.i(TAG, "Found base or application window, done!");
6917 if (wtoken.appFullscreen) {
6918 return win.mAttrs;
6919 }
6920 if (animSrc < 2) {
6921 animParams = win.mAttrs;
6922 animSrc = 2;
6923 }
6924 } else if (animSrc < 1 && win.mAttrs.type == WindowManager.LayoutParams.TYPE_APPLICATION) {
6925 //Log.i(TAG, "Found normal window, we may use this...");
6926 animParams = win.mAttrs;
6927 animSrc = 1;
6928 }
6929 }
6930 }
6931 }
6932
6933 return animParams;
6934 }
6935
6936 // -------------------------------------------------------------
6937 // DummyAnimation
6938 // -------------------------------------------------------------
6939
6940 // This is an animation that does nothing: it just immediately finishes
6941 // itself every time it is called. It is used as a stub animation in cases
6942 // where we want to synchronize multiple things that may be animating.
6943 static final class DummyAnimation extends Animation {
6944 public boolean getTransformation(long currentTime, Transformation outTransformation) {
6945 return false;
6946 }
6947 }
6948 static final Animation sDummyAnimation = new DummyAnimation();
6949
6950 // -------------------------------------------------------------
6951 // Async Handler
6952 // -------------------------------------------------------------
6953
6954 static final class StartingData {
6955 final String pkg;
6956 final int theme;
6957 final CharSequence nonLocalizedLabel;
6958 final int labelRes;
6959 final int icon;
6960
6961 StartingData(String _pkg, int _theme, CharSequence _nonLocalizedLabel,
6962 int _labelRes, int _icon) {
6963 pkg = _pkg;
6964 theme = _theme;
6965 nonLocalizedLabel = _nonLocalizedLabel;
6966 labelRes = _labelRes;
6967 icon = _icon;
6968 }
6969 }
6970
6971 private final class H extends Handler {
6972 public static final int REPORT_FOCUS_CHANGE = 2;
6973 public static final int REPORT_LOSING_FOCUS = 3;
6974 public static final int ANIMATE = 4;
6975 public static final int ADD_STARTING = 5;
6976 public static final int REMOVE_STARTING = 6;
6977 public static final int FINISHED_STARTING = 7;
6978 public static final int REPORT_APPLICATION_TOKEN_WINDOWS = 8;
6979 public static final int UPDATE_ORIENTATION = 10;
6980 public static final int WINDOW_FREEZE_TIMEOUT = 11;
6981 public static final int HOLD_SCREEN_CHANGED = 12;
6982 public static final int APP_TRANSITION_TIMEOUT = 13;
6983 public static final int PERSIST_ANIMATION_SCALE = 14;
6984 public static final int FORCE_GC = 15;
6985 public static final int ENABLE_SCREEN = 16;
6986 public static final int APP_FREEZE_TIMEOUT = 17;
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07006987 public static final int COMPUTE_AND_SEND_NEW_CONFIGURATION = 18;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006988
6989 private Session mLastReportedHold;
6990
6991 public H() {
6992 }
6993
6994 @Override
6995 public void handleMessage(Message msg) {
6996 switch (msg.what) {
6997 case REPORT_FOCUS_CHANGE: {
6998 WindowState lastFocus;
6999 WindowState newFocus;
7000
7001 synchronized(mWindowMap) {
7002 lastFocus = mLastFocus;
7003 newFocus = mCurrentFocus;
7004 if (lastFocus == newFocus) {
7005 // Focus is not changing, so nothing to do.
7006 return;
7007 }
7008 mLastFocus = newFocus;
7009 //Log.i(TAG, "Focus moving from " + lastFocus
7010 // + " to " + newFocus);
7011 if (newFocus != null && lastFocus != null
7012 && !newFocus.isDisplayedLw()) {
7013 //Log.i(TAG, "Delaying loss of focus...");
7014 mLosingFocus.add(lastFocus);
7015 lastFocus = null;
7016 }
7017 }
7018
7019 if (lastFocus != newFocus) {
7020 //System.out.println("Changing focus from " + lastFocus
7021 // + " to " + newFocus);
7022 if (newFocus != null) {
7023 try {
7024 //Log.i(TAG, "Gaining focus: " + newFocus);
7025 newFocus.mClient.windowFocusChanged(true, mInTouchMode);
7026 } catch (RemoteException e) {
7027 // Ignore if process has died.
7028 }
7029 }
7030
7031 if (lastFocus != null) {
7032 try {
7033 //Log.i(TAG, "Losing focus: " + lastFocus);
7034 lastFocus.mClient.windowFocusChanged(false, mInTouchMode);
7035 } catch (RemoteException e) {
7036 // Ignore if process has died.
7037 }
7038 }
7039 }
7040 } break;
7041
7042 case REPORT_LOSING_FOCUS: {
7043 ArrayList<WindowState> losers;
7044
7045 synchronized(mWindowMap) {
7046 losers = mLosingFocus;
7047 mLosingFocus = new ArrayList<WindowState>();
7048 }
7049
7050 final int N = losers.size();
7051 for (int i=0; i<N; i++) {
7052 try {
7053 //Log.i(TAG, "Losing delayed focus: " + losers.get(i));
7054 losers.get(i).mClient.windowFocusChanged(false, mInTouchMode);
7055 } catch (RemoteException e) {
7056 // Ignore if process has died.
7057 }
7058 }
7059 } break;
7060
7061 case ANIMATE: {
7062 synchronized(mWindowMap) {
7063 mAnimationPending = false;
7064 performLayoutAndPlaceSurfacesLocked();
7065 }
7066 } break;
7067
7068 case ADD_STARTING: {
7069 final AppWindowToken wtoken = (AppWindowToken)msg.obj;
7070 final StartingData sd = wtoken.startingData;
7071
7072 if (sd == null) {
7073 // Animation has been canceled... do nothing.
7074 return;
7075 }
7076
7077 if (DEBUG_STARTING_WINDOW) Log.v(TAG, "Add starting "
7078 + wtoken + ": pkg=" + sd.pkg);
7079
7080 View view = null;
7081 try {
7082 view = mPolicy.addStartingWindow(
7083 wtoken.token, sd.pkg,
7084 sd.theme, sd.nonLocalizedLabel, sd.labelRes,
7085 sd.icon);
7086 } catch (Exception e) {
7087 Log.w(TAG, "Exception when adding starting window", e);
7088 }
7089
7090 if (view != null) {
7091 boolean abort = false;
7092
7093 synchronized(mWindowMap) {
7094 if (wtoken.removed || wtoken.startingData == null) {
7095 // If the window was successfully added, then
7096 // we need to remove it.
7097 if (wtoken.startingWindow != null) {
7098 if (DEBUG_STARTING_WINDOW) Log.v(TAG,
7099 "Aborted starting " + wtoken
7100 + ": removed=" + wtoken.removed
7101 + " startingData=" + wtoken.startingData);
7102 wtoken.startingWindow = null;
7103 wtoken.startingData = null;
7104 abort = true;
7105 }
7106 } else {
7107 wtoken.startingView = view;
7108 }
7109 if (DEBUG_STARTING_WINDOW && !abort) Log.v(TAG,
7110 "Added starting " + wtoken
7111 + ": startingWindow="
7112 + wtoken.startingWindow + " startingView="
7113 + wtoken.startingView);
7114 }
7115
7116 if (abort) {
7117 try {
7118 mPolicy.removeStartingWindow(wtoken.token, view);
7119 } catch (Exception e) {
7120 Log.w(TAG, "Exception when removing starting window", e);
7121 }
7122 }
7123 }
7124 } break;
7125
7126 case REMOVE_STARTING: {
7127 final AppWindowToken wtoken = (AppWindowToken)msg.obj;
7128 IBinder token = null;
7129 View view = null;
7130 synchronized (mWindowMap) {
7131 if (DEBUG_STARTING_WINDOW) Log.v(TAG, "Remove starting "
7132 + wtoken + ": startingWindow="
7133 + wtoken.startingWindow + " startingView="
7134 + wtoken.startingView);
7135 if (wtoken.startingWindow != null) {
7136 view = wtoken.startingView;
7137 token = wtoken.token;
7138 wtoken.startingData = null;
7139 wtoken.startingView = null;
7140 wtoken.startingWindow = null;
7141 }
7142 }
7143 if (view != null) {
7144 try {
7145 mPolicy.removeStartingWindow(token, view);
7146 } catch (Exception e) {
7147 Log.w(TAG, "Exception when removing starting window", e);
7148 }
7149 }
7150 } break;
7151
7152 case FINISHED_STARTING: {
7153 IBinder token = null;
7154 View view = null;
7155 while (true) {
7156 synchronized (mWindowMap) {
7157 final int N = mFinishedStarting.size();
7158 if (N <= 0) {
7159 break;
7160 }
7161 AppWindowToken wtoken = mFinishedStarting.remove(N-1);
7162
7163 if (DEBUG_STARTING_WINDOW) Log.v(TAG,
7164 "Finished starting " + wtoken
7165 + ": startingWindow=" + wtoken.startingWindow
7166 + " startingView=" + wtoken.startingView);
7167
7168 if (wtoken.startingWindow == null) {
7169 continue;
7170 }
7171
7172 view = wtoken.startingView;
7173 token = wtoken.token;
7174 wtoken.startingData = null;
7175 wtoken.startingView = null;
7176 wtoken.startingWindow = null;
7177 }
7178
7179 try {
7180 mPolicy.removeStartingWindow(token, view);
7181 } catch (Exception e) {
7182 Log.w(TAG, "Exception when removing starting window", e);
7183 }
7184 }
7185 } break;
7186
7187 case REPORT_APPLICATION_TOKEN_WINDOWS: {
7188 final AppWindowToken wtoken = (AppWindowToken)msg.obj;
7189
7190 boolean nowVisible = msg.arg1 != 0;
7191 boolean nowGone = msg.arg2 != 0;
7192
7193 try {
7194 if (DEBUG_VISIBILITY) Log.v(
7195 TAG, "Reporting visible in " + wtoken
7196 + " visible=" + nowVisible
7197 + " gone=" + nowGone);
7198 if (nowVisible) {
7199 wtoken.appToken.windowsVisible();
7200 } else {
7201 wtoken.appToken.windowsGone();
7202 }
7203 } catch (RemoteException ex) {
7204 }
7205 } break;
7206
7207 case UPDATE_ORIENTATION: {
7208 setRotationUnchecked(WindowManagerPolicy.USE_LAST_ROTATION, false);
7209 break;
7210 }
7211
7212 case WINDOW_FREEZE_TIMEOUT: {
7213 synchronized (mWindowMap) {
7214 Log.w(TAG, "Window freeze timeout expired.");
7215 int i = mWindows.size();
7216 while (i > 0) {
7217 i--;
7218 WindowState w = (WindowState)mWindows.get(i);
7219 if (w.mOrientationChanging) {
7220 w.mOrientationChanging = false;
7221 Log.w(TAG, "Force clearing orientation change: " + w);
7222 }
7223 }
7224 performLayoutAndPlaceSurfacesLocked();
7225 }
7226 break;
7227 }
7228
7229 case HOLD_SCREEN_CHANGED: {
7230 Session oldHold;
7231 Session newHold;
7232 synchronized (mWindowMap) {
7233 oldHold = mLastReportedHold;
7234 newHold = (Session)msg.obj;
7235 mLastReportedHold = newHold;
7236 }
7237
7238 if (oldHold != newHold) {
7239 try {
7240 if (oldHold != null) {
7241 mBatteryStats.noteStopWakelock(oldHold.mUid,
7242 "window",
7243 BatteryStats.WAKE_TYPE_WINDOW);
7244 }
7245 if (newHold != null) {
7246 mBatteryStats.noteStartWakelock(newHold.mUid,
7247 "window",
7248 BatteryStats.WAKE_TYPE_WINDOW);
7249 }
7250 } catch (RemoteException e) {
7251 }
7252 }
7253 break;
7254 }
7255
7256 case APP_TRANSITION_TIMEOUT: {
7257 synchronized (mWindowMap) {
7258 if (mNextAppTransition != WindowManagerPolicy.TRANSIT_NONE) {
7259 if (DEBUG_APP_TRANSITIONS) Log.v(TAG,
7260 "*** APP TRANSITION TIMEOUT");
7261 mAppTransitionReady = true;
7262 mAppTransitionTimeout = true;
7263 performLayoutAndPlaceSurfacesLocked();
7264 }
7265 }
7266 break;
7267 }
7268
7269 case PERSIST_ANIMATION_SCALE: {
7270 Settings.System.putFloat(mContext.getContentResolver(),
7271 Settings.System.WINDOW_ANIMATION_SCALE, mWindowAnimationScale);
7272 Settings.System.putFloat(mContext.getContentResolver(),
7273 Settings.System.TRANSITION_ANIMATION_SCALE, mTransitionAnimationScale);
7274 break;
7275 }
7276
7277 case FORCE_GC: {
7278 synchronized(mWindowMap) {
7279 if (mAnimationPending) {
7280 // If we are animating, don't do the gc now but
7281 // delay a bit so we don't interrupt the animation.
7282 mH.sendMessageDelayed(mH.obtainMessage(H.FORCE_GC),
7283 2000);
7284 return;
7285 }
7286 // If we are currently rotating the display, it will
7287 // schedule a new message when done.
7288 if (mDisplayFrozen) {
7289 return;
7290 }
7291 mFreezeGcPending = 0;
7292 }
7293 Runtime.getRuntime().gc();
7294 break;
7295 }
7296
7297 case ENABLE_SCREEN: {
7298 performEnableScreen();
7299 break;
7300 }
7301
7302 case APP_FREEZE_TIMEOUT: {
7303 synchronized (mWindowMap) {
7304 Log.w(TAG, "App freeze timeout expired.");
7305 int i = mAppTokens.size();
7306 while (i > 0) {
7307 i--;
7308 AppWindowToken tok = mAppTokens.get(i);
7309 if (tok.freezingScreen) {
7310 Log.w(TAG, "Force clearing freeze: " + tok);
7311 unsetAppFreezingScreenLocked(tok, true, true);
7312 }
7313 }
7314 }
7315 break;
7316 }
7317
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07007318 case COMPUTE_AND_SEND_NEW_CONFIGURATION: {
The Android Open Source Project10592532009-03-18 17:39:46 -07007319 if (updateOrientationFromAppTokens(null, null) != null) {
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07007320 sendNewConfiguration();
7321 }
7322 break;
7323 }
7324
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007325 }
7326 }
7327 }
7328
7329 // -------------------------------------------------------------
7330 // IWindowManager API
7331 // -------------------------------------------------------------
7332
7333 public IWindowSession openSession(IInputMethodClient client,
7334 IInputContext inputContext) {
7335 if (client == null) throw new IllegalArgumentException("null client");
7336 if (inputContext == null) throw new IllegalArgumentException("null inputContext");
7337 return new Session(client, inputContext);
7338 }
7339
7340 public boolean inputMethodClientHasFocus(IInputMethodClient client) {
7341 synchronized (mWindowMap) {
7342 // The focus for the client is the window immediately below
7343 // where we would place the input method window.
7344 int idx = findDesiredInputMethodWindowIndexLocked(false);
7345 WindowState imFocus;
7346 if (idx > 0) {
7347 imFocus = (WindowState)mWindows.get(idx-1);
7348 if (imFocus != null) {
7349 if (imFocus.mSession.mClient != null &&
7350 imFocus.mSession.mClient.asBinder() == client.asBinder()) {
7351 return true;
7352 }
7353 }
7354 }
7355 }
7356 return false;
7357 }
7358
7359 // -------------------------------------------------------------
7360 // Internals
7361 // -------------------------------------------------------------
7362
7363 final WindowState windowForClientLocked(Session session, IWindow client) {
7364 return windowForClientLocked(session, client.asBinder());
7365 }
7366
7367 final WindowState windowForClientLocked(Session session, IBinder client) {
7368 WindowState win = mWindowMap.get(client);
7369 if (localLOGV) Log.v(
7370 TAG, "Looking up client " + client + ": " + win);
7371 if (win == null) {
7372 RuntimeException ex = new RuntimeException();
7373 Log.w(TAG, "Requested window " + client + " does not exist", ex);
7374 return null;
7375 }
7376 if (session != null && win.mSession != session) {
7377 RuntimeException ex = new RuntimeException();
7378 Log.w(TAG, "Requested window " + client + " is in session " +
7379 win.mSession + ", not " + session, ex);
7380 return null;
7381 }
7382
7383 return win;
7384 }
7385
7386 private final void assignLayersLocked() {
7387 int N = mWindows.size();
7388 int curBaseLayer = 0;
7389 int curLayer = 0;
7390 int i;
7391
7392 for (i=0; i<N; i++) {
7393 WindowState w = (WindowState)mWindows.get(i);
7394 if (w.mBaseLayer == curBaseLayer || w.mIsImWindow) {
7395 curLayer += WINDOW_LAYER_MULTIPLIER;
7396 w.mLayer = curLayer;
7397 } else {
7398 curBaseLayer = curLayer = w.mBaseLayer;
7399 w.mLayer = curLayer;
7400 }
7401 if (w.mTargetAppToken != null) {
7402 w.mAnimLayer = w.mLayer + w.mTargetAppToken.animLayerAdjustment;
7403 } else if (w.mAppToken != null) {
7404 w.mAnimLayer = w.mLayer + w.mAppToken.animLayerAdjustment;
7405 } else {
7406 w.mAnimLayer = w.mLayer;
7407 }
7408 if (w.mIsImWindow) {
7409 w.mAnimLayer += mInputMethodAnimLayerAdjustment;
7410 }
7411 if (DEBUG_LAYERS) Log.v(TAG, "Assign layer " + w + ": "
7412 + w.mAnimLayer);
7413 //System.out.println(
7414 // "Assigned layer " + curLayer + " to " + w.mClient.asBinder());
7415 }
7416 }
7417
7418 private boolean mInLayout = false;
7419 private final void performLayoutAndPlaceSurfacesLocked() {
7420 if (mInLayout) {
7421 if (Config.DEBUG) {
7422 throw new RuntimeException("Recursive call!");
7423 }
7424 Log.w(TAG, "performLayoutAndPlaceSurfacesLocked called while in layout");
7425 return;
7426 }
7427
7428 boolean recoveringMemory = false;
7429 if (mForceRemoves != null) {
7430 recoveringMemory = true;
7431 // Wait a little it for things to settle down, and off we go.
7432 for (int i=0; i<mForceRemoves.size(); i++) {
7433 WindowState ws = mForceRemoves.get(i);
7434 Log.i(TAG, "Force removing: " + ws);
7435 removeWindowInnerLocked(ws.mSession, ws);
7436 }
7437 mForceRemoves = null;
7438 Log.w(TAG, "Due to memory failure, waiting a bit for next layout");
7439 Object tmp = new Object();
7440 synchronized (tmp) {
7441 try {
7442 tmp.wait(250);
7443 } catch (InterruptedException e) {
7444 }
7445 }
7446 }
7447
7448 mInLayout = true;
7449 try {
7450 performLayoutAndPlaceSurfacesLockedInner(recoveringMemory);
7451
7452 int i = mPendingRemove.size()-1;
7453 if (i >= 0) {
7454 while (i >= 0) {
7455 WindowState w = mPendingRemove.get(i);
7456 removeWindowInnerLocked(w.mSession, w);
7457 i--;
7458 }
7459 mPendingRemove.clear();
7460
7461 mInLayout = false;
7462 assignLayersLocked();
7463 mLayoutNeeded = true;
7464 performLayoutAndPlaceSurfacesLocked();
7465
7466 } else {
7467 mInLayout = false;
7468 if (mLayoutNeeded) {
7469 requestAnimationLocked(0);
7470 }
7471 }
7472 } catch (RuntimeException e) {
7473 mInLayout = false;
7474 Log.e(TAG, "Unhandled exception while layout out windows", e);
7475 }
7476 }
7477
7478 private final void performLayoutLockedInner() {
7479 final int dw = mDisplay.getWidth();
7480 final int dh = mDisplay.getHeight();
7481
7482 final int N = mWindows.size();
7483 int i;
7484
7485 // FIRST LOOP: Perform a layout, if needed.
7486
7487 if (mLayoutNeeded) {
7488 mPolicy.beginLayoutLw(dw, dh);
7489
7490 // First perform layout of any root windows (not attached
7491 // to another window).
7492 int topAttached = -1;
7493 for (i = N-1; i >= 0; i--) {
7494 WindowState win = (WindowState) mWindows.get(i);
7495
7496 boolean gone = win.mViewVisibility == View.GONE
7497 || !win.mRelayoutCalled
The Android Open Source Project10592532009-03-18 17:39:46 -07007498 || win.mRootToken.hidden;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007499
7500 // If this view is GONE, then skip it -- keep the current
7501 // frame, and let the caller know so they can ignore it
7502 // if they want. (We do the normal layout for INVISIBLE
7503 // windows, since that means "perform layout as normal,
7504 // just don't display").
7505 if (!gone || !win.mHaveFrame) {
7506 if (!win.mLayoutAttached) {
7507 mPolicy.layoutWindowLw(win, win.mAttrs, null);
7508 } else {
7509 if (topAttached < 0) topAttached = i;
7510 }
7511 }
7512 }
7513
7514 // Now perform layout of attached windows, which usually
7515 // depend on the position of the window they are attached to.
7516 // XXX does not deal with windows that are attached to windows
7517 // that are themselves attached.
7518 for (i = topAttached; i >= 0; i--) {
7519 WindowState win = (WindowState) mWindows.get(i);
7520
7521 // If this view is GONE, then skip it -- keep the current
7522 // frame, and let the caller know so they can ignore it
7523 // if they want. (We do the normal layout for INVISIBLE
7524 // windows, since that means "perform layout as normal,
7525 // just don't display").
7526 if (win.mLayoutAttached) {
7527 if ((win.mViewVisibility != View.GONE && win.mRelayoutCalled)
7528 || !win.mHaveFrame) {
7529 mPolicy.layoutWindowLw(win, win.mAttrs, win.mAttachedWindow);
7530 }
7531 }
7532 }
7533
7534 mPolicy.finishLayoutLw();
7535 mLayoutNeeded = false;
7536 }
7537 }
7538
7539 private final void performLayoutAndPlaceSurfacesLockedInner(
7540 boolean recoveringMemory) {
7541 final long currentTime = SystemClock.uptimeMillis();
7542 final int dw = mDisplay.getWidth();
7543 final int dh = mDisplay.getHeight();
7544
7545 final int N = mWindows.size();
7546 int i;
7547
7548 // FIRST LOOP: Perform a layout, if needed.
7549
7550 performLayoutLockedInner();
7551
7552 if (mFxSession == null) {
7553 mFxSession = new SurfaceSession();
7554 }
7555
7556 if (SHOW_TRANSACTIONS) Log.i(TAG, ">>> OPEN TRANSACTION");
7557
7558 // Initialize state of exiting tokens.
7559 for (i=mExitingTokens.size()-1; i>=0; i--) {
7560 mExitingTokens.get(i).hasVisible = false;
7561 }
7562
7563 // Initialize state of exiting applications.
7564 for (i=mExitingAppTokens.size()-1; i>=0; i--) {
7565 mExitingAppTokens.get(i).hasVisible = false;
7566 }
7567
7568 // SECOND LOOP: Execute animations and update visibility of windows.
7569
7570 boolean orientationChangeComplete = true;
7571 Session holdScreen = null;
7572 float screenBrightness = -1;
7573 boolean focusDisplayed = false;
7574 boolean animating = false;
7575
7576 Surface.openTransaction();
7577 try {
7578 boolean restart;
7579
7580 do {
7581 final int transactionSequence = ++mTransactionSequence;
7582
7583 // Update animations of all applications, including those
7584 // associated with exiting/removed apps
7585 boolean tokensAnimating = false;
7586 final int NAT = mAppTokens.size();
7587 for (i=0; i<NAT; i++) {
7588 if (mAppTokens.get(i).stepAnimationLocked(currentTime, dw, dh)) {
7589 tokensAnimating = true;
7590 }
7591 }
7592 final int NEAT = mExitingAppTokens.size();
7593 for (i=0; i<NEAT; i++) {
7594 if (mExitingAppTokens.get(i).stepAnimationLocked(currentTime, dw, dh)) {
7595 tokensAnimating = true;
7596 }
7597 }
7598
7599 animating = tokensAnimating;
7600 restart = false;
7601
7602 boolean tokenMayBeDrawn = false;
7603
7604 mPolicy.beginAnimationLw(dw, dh);
7605
7606 for (i=N-1; i>=0; i--) {
7607 WindowState w = (WindowState)mWindows.get(i);
7608
7609 final WindowManager.LayoutParams attrs = w.mAttrs;
7610
7611 if (w.mSurface != null) {
7612 // Execute animation.
7613 w.commitFinishDrawingLocked(currentTime);
7614 if (w.stepAnimationLocked(currentTime, dw, dh)) {
7615 animating = true;
7616 //w.dump(" ");
7617 }
7618
7619 mPolicy.animatingWindowLw(w, attrs);
7620 }
7621
7622 final AppWindowToken atoken = w.mAppToken;
7623 if (atoken != null && (!atoken.allDrawn || atoken.freezingScreen)) {
7624 if (atoken.lastTransactionSequence != transactionSequence) {
7625 atoken.lastTransactionSequence = transactionSequence;
7626 atoken.numInterestingWindows = atoken.numDrawnWindows = 0;
7627 atoken.startingDisplayed = false;
7628 }
7629 if ((w.isOnScreen() || w.mAttrs.type
7630 == WindowManager.LayoutParams.TYPE_BASE_APPLICATION)
7631 && !w.mExiting && !w.mDestroying) {
7632 if (DEBUG_VISIBILITY || DEBUG_ORIENTATION) {
7633 Log.v(TAG, "Eval win " + w + ": isDisplayed="
7634 + w.isDisplayedLw()
7635 + ", isAnimating=" + w.isAnimating());
7636 if (!w.isDisplayedLw()) {
7637 Log.v(TAG, "Not displayed: s=" + w.mSurface
7638 + " pv=" + w.mPolicyVisibility
7639 + " dp=" + w.mDrawPending
7640 + " cdp=" + w.mCommitDrawPending
7641 + " ah=" + w.mAttachedHidden
7642 + " th=" + atoken.hiddenRequested
7643 + " a=" + w.mAnimating);
7644 }
7645 }
7646 if (w != atoken.startingWindow) {
7647 if (!atoken.freezingScreen || !w.mAppFreezing) {
7648 atoken.numInterestingWindows++;
7649 if (w.isDisplayedLw()) {
7650 atoken.numDrawnWindows++;
7651 if (DEBUG_VISIBILITY || DEBUG_ORIENTATION) Log.v(TAG,
7652 "tokenMayBeDrawn: " + atoken
7653 + " freezingScreen=" + atoken.freezingScreen
7654 + " mAppFreezing=" + w.mAppFreezing);
7655 tokenMayBeDrawn = true;
7656 }
7657 }
7658 } else if (w.isDisplayedLw()) {
7659 atoken.startingDisplayed = true;
7660 }
7661 }
7662 } else if (w.mReadyToShow) {
7663 w.performShowLocked();
7664 }
7665 }
7666
7667 if (mPolicy.finishAnimationLw()) {
7668 restart = true;
7669 }
7670
7671 if (tokenMayBeDrawn) {
7672 // See if any windows have been drawn, so they (and others
7673 // associated with them) can now be shown.
7674 final int NT = mTokenList.size();
7675 for (i=0; i<NT; i++) {
7676 AppWindowToken wtoken = mTokenList.get(i).appWindowToken;
7677 if (wtoken == null) {
7678 continue;
7679 }
7680 if (wtoken.freezingScreen) {
7681 int numInteresting = wtoken.numInterestingWindows;
7682 if (numInteresting > 0 && wtoken.numDrawnWindows >= numInteresting) {
7683 if (DEBUG_VISIBILITY) Log.v(TAG,
7684 "allDrawn: " + wtoken
7685 + " interesting=" + numInteresting
7686 + " drawn=" + wtoken.numDrawnWindows);
7687 wtoken.showAllWindowsLocked();
7688 unsetAppFreezingScreenLocked(wtoken, false, true);
7689 orientationChangeComplete = true;
7690 }
7691 } else if (!wtoken.allDrawn) {
7692 int numInteresting = wtoken.numInterestingWindows;
7693 if (numInteresting > 0 && wtoken.numDrawnWindows >= numInteresting) {
7694 if (DEBUG_VISIBILITY) Log.v(TAG,
7695 "allDrawn: " + wtoken
7696 + " interesting=" + numInteresting
7697 + " drawn=" + wtoken.numDrawnWindows);
7698 wtoken.allDrawn = true;
7699 restart = true;
7700
7701 // We can now show all of the drawn windows!
7702 if (!mOpeningApps.contains(wtoken)) {
7703 wtoken.showAllWindowsLocked();
7704 }
7705 }
7706 }
7707 }
7708 }
7709
7710 // If we are ready to perform an app transition, check through
7711 // all of the app tokens to be shown and see if they are ready
7712 // to go.
7713 if (mAppTransitionReady) {
7714 int NN = mOpeningApps.size();
7715 boolean goodToGo = true;
7716 if (DEBUG_APP_TRANSITIONS) Log.v(TAG,
7717 "Checking " + NN + " opening apps (frozen="
7718 + mDisplayFrozen + " timeout="
7719 + mAppTransitionTimeout + ")...");
7720 if (!mDisplayFrozen && !mAppTransitionTimeout) {
7721 // If the display isn't frozen, wait to do anything until
7722 // all of the apps are ready. Otherwise just go because
7723 // we'll unfreeze the display when everyone is ready.
7724 for (i=0; i<NN && goodToGo; i++) {
7725 AppWindowToken wtoken = mOpeningApps.get(i);
7726 if (DEBUG_APP_TRANSITIONS) Log.v(TAG,
7727 "Check opening app" + wtoken + ": allDrawn="
7728 + wtoken.allDrawn + " startingDisplayed="
7729 + wtoken.startingDisplayed);
7730 if (!wtoken.allDrawn && !wtoken.startingDisplayed
7731 && !wtoken.startingMoved) {
7732 goodToGo = false;
7733 }
7734 }
7735 }
7736 if (goodToGo) {
7737 if (DEBUG_APP_TRANSITIONS) Log.v(TAG, "**** GOOD TO GO");
7738 int transit = mNextAppTransition;
7739 if (mSkipAppTransitionAnimation) {
7740 transit = WindowManagerPolicy.TRANSIT_NONE;
7741 }
7742 mNextAppTransition = WindowManagerPolicy.TRANSIT_NONE;
7743 mAppTransitionReady = false;
7744 mAppTransitionTimeout = false;
7745 mStartingIconInTransition = false;
7746 mSkipAppTransitionAnimation = false;
7747
7748 mH.removeMessages(H.APP_TRANSITION_TIMEOUT);
7749
7750 // We need to figure out which animation to use...
7751 WindowManager.LayoutParams lp = findAnimations(mAppTokens,
7752 mOpeningApps, mClosingApps);
7753
7754 NN = mOpeningApps.size();
7755 for (i=0; i<NN; i++) {
7756 AppWindowToken wtoken = mOpeningApps.get(i);
7757 if (DEBUG_APP_TRANSITIONS) Log.v(TAG,
7758 "Now opening app" + wtoken);
7759 wtoken.reportedVisible = false;
7760 wtoken.inPendingTransaction = false;
7761 setTokenVisibilityLocked(wtoken, lp, true, transit, false);
7762 wtoken.updateReportedVisibilityLocked();
7763 wtoken.showAllWindowsLocked();
7764 }
7765 NN = mClosingApps.size();
7766 for (i=0; i<NN; i++) {
7767 AppWindowToken wtoken = mClosingApps.get(i);
7768 if (DEBUG_APP_TRANSITIONS) Log.v(TAG,
7769 "Now closing app" + wtoken);
7770 wtoken.inPendingTransaction = false;
7771 setTokenVisibilityLocked(wtoken, lp, false, transit, false);
7772 wtoken.updateReportedVisibilityLocked();
7773 // Force the allDrawn flag, because we want to start
7774 // this guy's animations regardless of whether it's
7775 // gotten drawn.
7776 wtoken.allDrawn = true;
7777 }
7778
7779 mOpeningApps.clear();
7780 mClosingApps.clear();
7781
7782 // This has changed the visibility of windows, so perform
7783 // a new layout to get them all up-to-date.
7784 mLayoutNeeded = true;
7785 moveInputMethodWindowsIfNeededLocked(true);
7786 performLayoutLockedInner();
7787 updateFocusedWindowLocked(UPDATE_FOCUS_PLACING_SURFACES);
7788
7789 restart = true;
7790 }
7791 }
7792 } while (restart);
7793
7794 // THIRD LOOP: Update the surfaces of all windows.
7795
7796 final boolean someoneLosingFocus = mLosingFocus.size() != 0;
7797
7798 boolean obscured = false;
7799 boolean blurring = false;
7800 boolean dimming = false;
7801 boolean covered = false;
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07007802 boolean syswin = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007803
7804 for (i=N-1; i>=0; i--) {
7805 WindowState w = (WindowState)mWindows.get(i);
7806
7807 boolean displayed = false;
7808 final WindowManager.LayoutParams attrs = w.mAttrs;
7809 final int attrFlags = attrs.flags;
7810
7811 if (w.mSurface != null) {
7812 w.computeShownFrameLocked();
7813 if (localLOGV) Log.v(
7814 TAG, "Placing surface #" + i + " " + w.mSurface
7815 + ": new=" + w.mShownFrame + ", old="
7816 + w.mLastShownFrame);
7817
7818 boolean resize;
7819 int width, height;
7820 if ((w.mAttrs.flags & w.mAttrs.FLAG_SCALED) != 0) {
7821 resize = w.mLastRequestedWidth != w.mRequestedWidth ||
7822 w.mLastRequestedHeight != w.mRequestedHeight;
7823 // for a scaled surface, we just want to use
7824 // the requested size.
7825 width = w.mRequestedWidth;
7826 height = w.mRequestedHeight;
7827 w.mLastRequestedWidth = width;
7828 w.mLastRequestedHeight = height;
7829 w.mLastShownFrame.set(w.mShownFrame);
7830 try {
7831 w.mSurface.setPosition(w.mShownFrame.left, w.mShownFrame.top);
7832 } catch (RuntimeException e) {
7833 Log.w(TAG, "Error positioning surface in " + w, e);
7834 if (!recoveringMemory) {
7835 reclaimSomeSurfaceMemoryLocked(w, "position");
7836 }
7837 }
7838 } else {
7839 resize = !w.mLastShownFrame.equals(w.mShownFrame);
7840 width = w.mShownFrame.width();
7841 height = w.mShownFrame.height();
7842 w.mLastShownFrame.set(w.mShownFrame);
7843 if (resize) {
7844 if (SHOW_TRANSACTIONS) Log.i(
7845 TAG, " SURFACE " + w.mSurface + ": ("
7846 + w.mShownFrame.left + ","
7847 + w.mShownFrame.top + ") ("
7848 + w.mShownFrame.width() + "x"
7849 + w.mShownFrame.height() + ")");
7850 }
7851 }
7852
7853 if (resize) {
7854 if (width < 1) width = 1;
7855 if (height < 1) height = 1;
7856 if (w.mSurface != null) {
7857 try {
7858 w.mSurface.setSize(width, height);
7859 w.mSurface.setPosition(w.mShownFrame.left,
7860 w.mShownFrame.top);
7861 } catch (RuntimeException e) {
7862 // If something goes wrong with the surface (such
7863 // as running out of memory), don't take down the
7864 // entire system.
7865 Log.e(TAG, "Failure updating surface of " + w
7866 + "size=(" + width + "x" + height
7867 + "), pos=(" + w.mShownFrame.left
7868 + "," + w.mShownFrame.top + ")", e);
7869 if (!recoveringMemory) {
7870 reclaimSomeSurfaceMemoryLocked(w, "size");
7871 }
7872 }
7873 }
7874 }
7875 if (!w.mAppFreezing) {
7876 w.mContentInsetsChanged =
7877 !w.mLastContentInsets.equals(w.mContentInsets);
7878 w.mVisibleInsetsChanged =
7879 !w.mLastVisibleInsets.equals(w.mVisibleInsets);
7880 if (!w.mLastFrame.equals(w.mFrame)
7881 || w.mContentInsetsChanged
7882 || w.mVisibleInsetsChanged) {
7883 w.mLastFrame.set(w.mFrame);
7884 w.mLastContentInsets.set(w.mContentInsets);
7885 w.mLastVisibleInsets.set(w.mVisibleInsets);
7886 // If the orientation is changing, then we need to
7887 // hold off on unfreezing the display until this
7888 // window has been redrawn; to do that, we need
7889 // to go through the process of getting informed
7890 // by the application when it has finished drawing.
7891 if (w.mOrientationChanging) {
7892 if (DEBUG_ORIENTATION) Log.v(TAG,
7893 "Orientation start waiting for draw in "
7894 + w + ", surface " + w.mSurface);
7895 w.mDrawPending = true;
7896 w.mCommitDrawPending = false;
7897 w.mReadyToShow = false;
7898 if (w.mAppToken != null) {
7899 w.mAppToken.allDrawn = false;
7900 }
7901 }
7902 if (DEBUG_ORIENTATION) Log.v(TAG,
7903 "Resizing window " + w + " to " + w.mFrame);
7904 mResizingWindows.add(w);
7905 } else if (w.mOrientationChanging) {
7906 if (!w.mDrawPending && !w.mCommitDrawPending) {
7907 if (DEBUG_ORIENTATION) Log.v(TAG,
7908 "Orientation not waiting for draw in "
7909 + w + ", surface " + w.mSurface);
7910 w.mOrientationChanging = false;
7911 }
7912 }
7913 }
7914
7915 if (w.mAttachedHidden) {
7916 if (!w.mLastHidden) {
7917 //dump();
7918 w.mLastHidden = true;
7919 if (SHOW_TRANSACTIONS) Log.i(
7920 TAG, " SURFACE " + w.mSurface + ": HIDE (performLayout-attached)");
7921 if (w.mSurface != null) {
7922 try {
7923 w.mSurface.hide();
7924 } catch (RuntimeException e) {
7925 Log.w(TAG, "Exception hiding surface in " + w);
7926 }
7927 }
7928 mKeyWaiter.releasePendingPointerLocked(w.mSession);
7929 }
7930 // If we are waiting for this window to handle an
7931 // orientation change, well, it is hidden, so
7932 // doesn't really matter. Note that this does
7933 // introduce a potential glitch if the window
7934 // becomes unhidden before it has drawn for the
7935 // new orientation.
7936 if (w.mOrientationChanging) {
7937 w.mOrientationChanging = false;
7938 if (DEBUG_ORIENTATION) Log.v(TAG,
7939 "Orientation change skips hidden " + w);
7940 }
7941 } else if (!w.isReadyForDisplay()) {
7942 if (!w.mLastHidden) {
7943 //dump();
7944 w.mLastHidden = true;
7945 if (SHOW_TRANSACTIONS) Log.i(
7946 TAG, " SURFACE " + w.mSurface + ": HIDE (performLayout-ready)");
7947 if (w.mSurface != null) {
7948 try {
7949 w.mSurface.hide();
7950 } catch (RuntimeException e) {
7951 Log.w(TAG, "Exception exception hiding surface in " + w);
7952 }
7953 }
7954 mKeyWaiter.releasePendingPointerLocked(w.mSession);
7955 }
7956 // If we are waiting for this window to handle an
7957 // orientation change, well, it is hidden, so
7958 // doesn't really matter. Note that this does
7959 // introduce a potential glitch if the window
7960 // becomes unhidden before it has drawn for the
7961 // new orientation.
7962 if (w.mOrientationChanging) {
7963 w.mOrientationChanging = false;
7964 if (DEBUG_ORIENTATION) Log.v(TAG,
7965 "Orientation change skips hidden " + w);
7966 }
7967 } else if (w.mLastLayer != w.mAnimLayer
7968 || w.mLastAlpha != w.mShownAlpha
7969 || w.mLastDsDx != w.mDsDx
7970 || w.mLastDtDx != w.mDtDx
7971 || w.mLastDsDy != w.mDsDy
7972 || w.mLastDtDy != w.mDtDy
7973 || w.mLastHScale != w.mHScale
7974 || w.mLastVScale != w.mVScale
7975 || w.mLastHidden) {
7976 displayed = true;
7977 w.mLastAlpha = w.mShownAlpha;
7978 w.mLastLayer = w.mAnimLayer;
7979 w.mLastDsDx = w.mDsDx;
7980 w.mLastDtDx = w.mDtDx;
7981 w.mLastDsDy = w.mDsDy;
7982 w.mLastDtDy = w.mDtDy;
7983 w.mLastHScale = w.mHScale;
7984 w.mLastVScale = w.mVScale;
7985 if (SHOW_TRANSACTIONS) Log.i(
7986 TAG, " SURFACE " + w.mSurface + ": alpha="
7987 + w.mShownAlpha + " layer=" + w.mAnimLayer);
7988 if (w.mSurface != null) {
7989 try {
7990 w.mSurface.setAlpha(w.mShownAlpha);
7991 w.mSurface.setLayer(w.mAnimLayer);
7992 w.mSurface.setMatrix(
7993 w.mDsDx*w.mHScale, w.mDtDx*w.mVScale,
7994 w.mDsDy*w.mHScale, w.mDtDy*w.mVScale);
7995 } catch (RuntimeException e) {
7996 Log.w(TAG, "Error updating surface in " + w, e);
7997 if (!recoveringMemory) {
7998 reclaimSomeSurfaceMemoryLocked(w, "update");
7999 }
8000 }
8001 }
8002
8003 if (w.mLastHidden && !w.mDrawPending
8004 && !w.mCommitDrawPending
8005 && !w.mReadyToShow) {
8006 if (SHOW_TRANSACTIONS) Log.i(
8007 TAG, " SURFACE " + w.mSurface + ": SHOW (performLayout)");
8008 if (DEBUG_VISIBILITY) Log.v(TAG, "Showing " + w
8009 + " during relayout");
8010 if (showSurfaceRobustlyLocked(w)) {
8011 w.mHasDrawn = true;
8012 w.mLastHidden = false;
8013 } else {
8014 w.mOrientationChanging = false;
8015 }
8016 }
8017 if (w.mSurface != null) {
8018 w.mToken.hasVisible = true;
8019 }
8020 } else {
8021 displayed = true;
8022 }
8023
8024 if (displayed) {
8025 if (!covered) {
8026 if (attrs.width == LayoutParams.FILL_PARENT
8027 && attrs.height == LayoutParams.FILL_PARENT) {
8028 covered = true;
8029 }
8030 }
8031 if (w.mOrientationChanging) {
8032 if (w.mDrawPending || w.mCommitDrawPending) {
8033 orientationChangeComplete = false;
8034 if (DEBUG_ORIENTATION) Log.v(TAG,
8035 "Orientation continue waiting for draw in " + w);
8036 } else {
8037 w.mOrientationChanging = false;
8038 if (DEBUG_ORIENTATION) Log.v(TAG,
8039 "Orientation change complete in " + w);
8040 }
8041 }
8042 w.mToken.hasVisible = true;
8043 }
8044 } else if (w.mOrientationChanging) {
8045 if (DEBUG_ORIENTATION) Log.v(TAG,
8046 "Orientation change skips hidden " + w);
8047 w.mOrientationChanging = false;
8048 }
8049
8050 final boolean canBeSeen = w.isDisplayedLw();
8051
8052 if (someoneLosingFocus && w == mCurrentFocus && canBeSeen) {
8053 focusDisplayed = true;
8054 }
8055
8056 // Update effect.
8057 if (!obscured) {
8058 if (w.mSurface != null) {
8059 if ((attrFlags&FLAG_KEEP_SCREEN_ON) != 0) {
8060 holdScreen = w.mSession;
8061 }
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07008062 if (!syswin && w.mAttrs.screenBrightness >= 0
8063 && screenBrightness < 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008064 screenBrightness = w.mAttrs.screenBrightness;
8065 }
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07008066 if (attrs.type == WindowManager.LayoutParams.TYPE_SYSTEM_DIALOG
8067 || attrs.type == WindowManager.LayoutParams.TYPE_KEYGUARD
8068 || attrs.type == WindowManager.LayoutParams.TYPE_SYSTEM_ERROR) {
8069 syswin = true;
8070 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008071 }
8072 if (w.isFullscreenOpaque(dw, dh)) {
8073 // This window completely covers everything behind it,
8074 // so we want to leave all of them as unblurred (for
8075 // performance reasons).
8076 obscured = true;
8077 } else if (canBeSeen && !obscured &&
8078 (attrFlags&FLAG_BLUR_BEHIND|FLAG_DIM_BEHIND) != 0) {
8079 if (localLOGV) Log.v(TAG, "Win " + w
8080 + ": blurring=" + blurring
8081 + " obscured=" + obscured
8082 + " displayed=" + displayed);
8083 if ((attrFlags&FLAG_DIM_BEHIND) != 0) {
8084 if (!dimming) {
8085 //Log.i(TAG, "DIM BEHIND: " + w);
8086 dimming = true;
8087 mDimShown = true;
8088 if (mDimSurface == null) {
8089 if (SHOW_TRANSACTIONS) Log.i(TAG, " DIM "
8090 + mDimSurface + ": CREATE");
8091 try {
8092 mDimSurface = new Surface(mFxSession, 0,
8093 -1, 16, 16,
8094 PixelFormat.OPAQUE,
8095 Surface.FX_SURFACE_DIM);
8096 } catch (Exception e) {
8097 Log.e(TAG, "Exception creating Dim surface", e);
8098 }
8099 }
8100 if (SHOW_TRANSACTIONS) Log.i(TAG, " DIM "
8101 + mDimSurface + ": SHOW pos=(0,0) (" +
8102 dw + "x" + dh + "), layer=" + (w.mAnimLayer-1));
8103 if (mDimSurface != null) {
8104 try {
8105 mDimSurface.setPosition(0, 0);
8106 mDimSurface.setSize(dw, dh);
8107 mDimSurface.show();
8108 } catch (RuntimeException e) {
8109 Log.w(TAG, "Failure showing dim surface", e);
8110 }
8111 }
8112 }
8113 mDimSurface.setLayer(w.mAnimLayer-1);
8114 final float target = w.mExiting ? 0 : attrs.dimAmount;
8115 if (mDimTargetAlpha != target) {
8116 // If the desired dim level has changed, then
8117 // start an animation to it.
8118 mLastDimAnimTime = currentTime;
8119 long duration = (w.mAnimating && w.mAnimation != null)
8120 ? w.mAnimation.computeDurationHint()
8121 : DEFAULT_DIM_DURATION;
8122 if (target > mDimTargetAlpha) {
8123 // This is happening behind the activity UI,
8124 // so we can make it run a little longer to
8125 // give a stronger impression without disrupting
8126 // the user.
8127 duration *= DIM_DURATION_MULTIPLIER;
8128 }
8129 if (duration < 1) {
8130 // Don't divide by zero
8131 duration = 1;
8132 }
8133 mDimTargetAlpha = target;
8134 mDimDeltaPerMs = (mDimTargetAlpha-mDimCurrentAlpha)
8135 / duration;
8136 }
8137 }
8138 if ((attrFlags&FLAG_BLUR_BEHIND) != 0) {
8139 if (!blurring) {
8140 //Log.i(TAG, "BLUR BEHIND: " + w);
8141 blurring = true;
8142 mBlurShown = true;
8143 if (mBlurSurface == null) {
8144 if (SHOW_TRANSACTIONS) Log.i(TAG, " BLUR "
8145 + mBlurSurface + ": CREATE");
8146 try {
8147 mBlurSurface = new Surface(mFxSession, 0,
8148 -1, 16, 16,
8149 PixelFormat.OPAQUE,
8150 Surface.FX_SURFACE_BLUR);
8151 } catch (Exception e) {
8152 Log.e(TAG, "Exception creating Blur surface", e);
8153 }
8154 }
8155 if (SHOW_TRANSACTIONS) Log.i(TAG, " BLUR "
8156 + mBlurSurface + ": SHOW pos=(0,0) (" +
8157 dw + "x" + dh + "), layer=" + (w.mAnimLayer-1));
8158 if (mBlurSurface != null) {
8159 mBlurSurface.setPosition(0, 0);
8160 mBlurSurface.setSize(dw, dh);
8161 try {
8162 mBlurSurface.show();
8163 } catch (RuntimeException e) {
8164 Log.w(TAG, "Failure showing blur surface", e);
8165 }
8166 }
8167 }
8168 mBlurSurface.setLayer(w.mAnimLayer-2);
8169 }
8170 }
8171 }
8172 }
8173
8174 if (!dimming && mDimShown) {
8175 // Time to hide the dim surface... start fading.
8176 if (mDimTargetAlpha != 0) {
8177 mLastDimAnimTime = currentTime;
8178 mDimTargetAlpha = 0;
8179 mDimDeltaPerMs = (-mDimCurrentAlpha) / DEFAULT_DIM_DURATION;
8180 }
8181 }
8182
8183 if (mDimShown && mLastDimAnimTime != 0) {
8184 mDimCurrentAlpha += mDimDeltaPerMs
8185 * (currentTime-mLastDimAnimTime);
8186 boolean more = true;
8187 if (mDisplayFrozen) {
8188 // If the display is frozen, there is no reason to animate.
8189 more = false;
8190 } else if (mDimDeltaPerMs > 0) {
8191 if (mDimCurrentAlpha > mDimTargetAlpha) {
8192 more = false;
8193 }
8194 } else if (mDimDeltaPerMs < 0) {
8195 if (mDimCurrentAlpha < mDimTargetAlpha) {
8196 more = false;
8197 }
8198 } else {
8199 more = false;
8200 }
8201
8202 // Do we need to continue animating?
8203 if (more) {
8204 if (SHOW_TRANSACTIONS) Log.i(TAG, " DIM "
8205 + mDimSurface + ": alpha=" + mDimCurrentAlpha);
8206 mLastDimAnimTime = currentTime;
8207 mDimSurface.setAlpha(mDimCurrentAlpha);
8208 animating = true;
8209 } else {
8210 mDimCurrentAlpha = mDimTargetAlpha;
8211 mLastDimAnimTime = 0;
8212 if (SHOW_TRANSACTIONS) Log.i(TAG, " DIM "
8213 + mDimSurface + ": final alpha=" + mDimCurrentAlpha);
8214 mDimSurface.setAlpha(mDimCurrentAlpha);
8215 if (!dimming) {
8216 if (SHOW_TRANSACTIONS) Log.i(TAG, " DIM " + mDimSurface
8217 + ": HIDE");
8218 try {
8219 mDimSurface.hide();
8220 } catch (RuntimeException e) {
8221 Log.w(TAG, "Illegal argument exception hiding dim surface");
8222 }
8223 mDimShown = false;
8224 }
8225 }
8226 }
8227
8228 if (!blurring && mBlurShown) {
8229 if (SHOW_TRANSACTIONS) Log.i(TAG, " BLUR " + mBlurSurface
8230 + ": HIDE");
8231 try {
8232 mBlurSurface.hide();
8233 } catch (IllegalArgumentException e) {
8234 Log.w(TAG, "Illegal argument exception hiding blur surface");
8235 }
8236 mBlurShown = false;
8237 }
8238
8239 if (SHOW_TRANSACTIONS) Log.i(TAG, "<<< CLOSE TRANSACTION");
8240 } catch (RuntimeException e) {
8241 Log.e(TAG, "Unhandled exception in Window Manager", e);
8242 }
8243
8244 Surface.closeTransaction();
8245
8246 if (DEBUG_ORIENTATION && mDisplayFrozen) Log.v(TAG,
8247 "With display frozen, orientationChangeComplete="
8248 + orientationChangeComplete);
8249 if (orientationChangeComplete) {
8250 if (mWindowsFreezingScreen) {
8251 mWindowsFreezingScreen = false;
8252 mH.removeMessages(H.WINDOW_FREEZE_TIMEOUT);
8253 }
8254 if (mAppsFreezingScreen == 0) {
8255 stopFreezingDisplayLocked();
8256 }
8257 }
8258
8259 i = mResizingWindows.size();
8260 if (i > 0) {
8261 do {
8262 i--;
8263 WindowState win = mResizingWindows.get(i);
8264 try {
8265 win.mClient.resized(win.mFrame.width(),
8266 win.mFrame.height(), win.mLastContentInsets,
8267 win.mLastVisibleInsets, win.mDrawPending);
8268 win.mContentInsetsChanged = false;
8269 win.mVisibleInsetsChanged = false;
8270 } catch (RemoteException e) {
8271 win.mOrientationChanging = false;
8272 }
8273 } while (i > 0);
8274 mResizingWindows.clear();
8275 }
8276
8277 // Destroy the surface of any windows that are no longer visible.
8278 i = mDestroySurface.size();
8279 if (i > 0) {
8280 do {
8281 i--;
8282 WindowState win = mDestroySurface.get(i);
8283 win.mDestroying = false;
8284 if (mInputMethodWindow == win) {
8285 mInputMethodWindow = null;
8286 }
8287 win.destroySurfaceLocked();
8288 } while (i > 0);
8289 mDestroySurface.clear();
8290 }
8291
8292 // Time to remove any exiting tokens?
8293 for (i=mExitingTokens.size()-1; i>=0; i--) {
8294 WindowToken token = mExitingTokens.get(i);
8295 if (!token.hasVisible) {
8296 mExitingTokens.remove(i);
8297 }
8298 }
8299
8300 // Time to remove any exiting applications?
8301 for (i=mExitingAppTokens.size()-1; i>=0; i--) {
8302 AppWindowToken token = mExitingAppTokens.get(i);
8303 if (!token.hasVisible && !mClosingApps.contains(token)) {
8304 mAppTokens.remove(token);
8305 mExitingAppTokens.remove(i);
8306 }
8307 }
8308
8309 if (focusDisplayed) {
8310 mH.sendEmptyMessage(H.REPORT_LOSING_FOCUS);
8311 }
8312 if (animating) {
8313 requestAnimationLocked(currentTime+(1000/60)-SystemClock.uptimeMillis());
8314 }
8315 mQueue.setHoldScreenLocked(holdScreen != null);
8316 if (screenBrightness < 0 || screenBrightness > 1.0f) {
8317 mPowerManager.setScreenBrightnessOverride(-1);
8318 } else {
8319 mPowerManager.setScreenBrightnessOverride((int)
8320 (screenBrightness * Power.BRIGHTNESS_ON));
8321 }
8322 if (holdScreen != mHoldingScreenOn) {
8323 mHoldingScreenOn = holdScreen;
8324 Message m = mH.obtainMessage(H.HOLD_SCREEN_CHANGED, holdScreen);
8325 mH.sendMessage(m);
8326 }
8327 }
8328
8329 void requestAnimationLocked(long delay) {
8330 if (!mAnimationPending) {
8331 mAnimationPending = true;
8332 mH.sendMessageDelayed(mH.obtainMessage(H.ANIMATE), delay);
8333 }
8334 }
8335
8336 /**
8337 * Have the surface flinger show a surface, robustly dealing with
8338 * error conditions. In particular, if there is not enough memory
8339 * to show the surface, then we will try to get rid of other surfaces
8340 * in order to succeed.
8341 *
8342 * @return Returns true if the surface was successfully shown.
8343 */
8344 boolean showSurfaceRobustlyLocked(WindowState win) {
8345 try {
8346 if (win.mSurface != null) {
8347 win.mSurface.show();
8348 }
8349 return true;
8350 } catch (RuntimeException e) {
8351 Log.w(TAG, "Failure showing surface " + win.mSurface + " in " + win);
8352 }
8353
8354 reclaimSomeSurfaceMemoryLocked(win, "show");
8355
8356 return false;
8357 }
8358
8359 void reclaimSomeSurfaceMemoryLocked(WindowState win, String operation) {
8360 final Surface surface = win.mSurface;
8361
8362 EventLog.writeEvent(LOG_WM_NO_SURFACE_MEMORY, win.toString(),
8363 win.mSession.mPid, operation);
8364
8365 if (mForceRemoves == null) {
8366 mForceRemoves = new ArrayList<WindowState>();
8367 }
8368
8369 long callingIdentity = Binder.clearCallingIdentity();
8370 try {
8371 // There was some problem... first, do a sanity check of the
8372 // window list to make sure we haven't left any dangling surfaces
8373 // around.
8374 int N = mWindows.size();
8375 boolean leakedSurface = false;
8376 Log.i(TAG, "Out of memory for surface! Looking for leaks...");
8377 for (int i=0; i<N; i++) {
8378 WindowState ws = (WindowState)mWindows.get(i);
8379 if (ws.mSurface != null) {
8380 if (!mSessions.contains(ws.mSession)) {
8381 Log.w(TAG, "LEAKED SURFACE (session doesn't exist): "
8382 + ws + " surface=" + ws.mSurface
8383 + " token=" + win.mToken
8384 + " pid=" + ws.mSession.mPid
8385 + " uid=" + ws.mSession.mUid);
8386 ws.mSurface.clear();
8387 ws.mSurface = null;
8388 mForceRemoves.add(ws);
8389 i--;
8390 N--;
8391 leakedSurface = true;
8392 } else if (win.mAppToken != null && win.mAppToken.clientHidden) {
8393 Log.w(TAG, "LEAKED SURFACE (app token hidden): "
8394 + ws + " surface=" + ws.mSurface
8395 + " token=" + win.mAppToken);
8396 ws.mSurface.clear();
8397 ws.mSurface = null;
8398 leakedSurface = true;
8399 }
8400 }
8401 }
8402
8403 boolean killedApps = false;
8404 if (!leakedSurface) {
8405 Log.w(TAG, "No leaked surfaces; killing applicatons!");
8406 SparseIntArray pidCandidates = new SparseIntArray();
8407 for (int i=0; i<N; i++) {
8408 WindowState ws = (WindowState)mWindows.get(i);
8409 if (ws.mSurface != null) {
8410 pidCandidates.append(ws.mSession.mPid, ws.mSession.mPid);
8411 }
8412 }
8413 if (pidCandidates.size() > 0) {
8414 int[] pids = new int[pidCandidates.size()];
8415 for (int i=0; i<pids.length; i++) {
8416 pids[i] = pidCandidates.keyAt(i);
8417 }
8418 try {
8419 if (mActivityManager.killPidsForMemory(pids)) {
8420 killedApps = true;
8421 }
8422 } catch (RemoteException e) {
8423 }
8424 }
8425 }
8426
8427 if (leakedSurface || killedApps) {
8428 // We managed to reclaim some memory, so get rid of the trouble
8429 // surface and ask the app to request another one.
8430 Log.w(TAG, "Looks like we have reclaimed some memory, clearing surface for retry.");
8431 if (surface != null) {
8432 surface.clear();
8433 win.mSurface = null;
8434 }
8435
8436 try {
8437 win.mClient.dispatchGetNewSurface();
8438 } catch (RemoteException e) {
8439 }
8440 }
8441 } finally {
8442 Binder.restoreCallingIdentity(callingIdentity);
8443 }
8444 }
8445
8446 private boolean updateFocusedWindowLocked(int mode) {
8447 WindowState newFocus = computeFocusedWindowLocked();
8448 if (mCurrentFocus != newFocus) {
8449 // This check makes sure that we don't already have the focus
8450 // change message pending.
8451 mH.removeMessages(H.REPORT_FOCUS_CHANGE);
8452 mH.sendEmptyMessage(H.REPORT_FOCUS_CHANGE);
8453 if (localLOGV) Log.v(
8454 TAG, "Changing focus from " + mCurrentFocus + " to " + newFocus);
8455 final WindowState oldFocus = mCurrentFocus;
8456 mCurrentFocus = newFocus;
8457 mLosingFocus.remove(newFocus);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008458
8459 final WindowState imWindow = mInputMethodWindow;
8460 if (newFocus != imWindow && oldFocus != imWindow) {
The Android Open Source Projectc474dec2009-03-04 09:49:09 -08008461 if (moveInputMethodWindowsIfNeededLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008462 mode != UPDATE_FOCUS_WILL_ASSIGN_LAYERS &&
The Android Open Source Projectc474dec2009-03-04 09:49:09 -08008463 mode != UPDATE_FOCUS_WILL_PLACE_SURFACES)) {
8464 mLayoutNeeded = true;
8465 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008466 if (mode == UPDATE_FOCUS_PLACING_SURFACES) {
8467 performLayoutLockedInner();
The Android Open Source Projectc474dec2009-03-04 09:49:09 -08008468 } else if (mode == UPDATE_FOCUS_WILL_PLACE_SURFACES) {
8469 // Client will do the layout, but we need to assign layers
8470 // for handleNewWindowLocked() below.
8471 assignLayersLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008472 }
8473 }
The Android Open Source Projectc474dec2009-03-04 09:49:09 -08008474
8475 if (newFocus != null && mode != UPDATE_FOCUS_WILL_ASSIGN_LAYERS) {
8476 mKeyWaiter.handleNewWindowLocked(newFocus);
8477 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008478 return true;
8479 }
8480 return false;
8481 }
8482
8483 private WindowState computeFocusedWindowLocked() {
8484 WindowState result = null;
8485 WindowState win;
8486
8487 int i = mWindows.size() - 1;
8488 int nextAppIndex = mAppTokens.size()-1;
8489 WindowToken nextApp = nextAppIndex >= 0
8490 ? mAppTokens.get(nextAppIndex) : null;
8491
8492 while (i >= 0) {
8493 win = (WindowState)mWindows.get(i);
8494
8495 if (localLOGV || DEBUG_FOCUS) Log.v(
8496 TAG, "Looking for focus: " + i
8497 + " = " + win
8498 + ", flags=" + win.mAttrs.flags
8499 + ", canReceive=" + win.canReceiveKeys());
8500
8501 AppWindowToken thisApp = win.mAppToken;
8502
8503 // If this window's application has been removed, just skip it.
8504 if (thisApp != null && thisApp.removed) {
8505 i--;
8506 continue;
8507 }
8508
8509 // If there is a focused app, don't allow focus to go to any
8510 // windows below it. If this is an application window, step
8511 // through the app tokens until we find its app.
8512 if (thisApp != null && nextApp != null && thisApp != nextApp
8513 && win.mAttrs.type != TYPE_APPLICATION_STARTING) {
8514 int origAppIndex = nextAppIndex;
8515 while (nextAppIndex > 0) {
8516 if (nextApp == mFocusedApp) {
8517 // Whoops, we are below the focused app... no focus
8518 // for you!
8519 if (localLOGV || DEBUG_FOCUS) Log.v(
8520 TAG, "Reached focused app: " + mFocusedApp);
8521 return null;
8522 }
8523 nextAppIndex--;
8524 nextApp = mAppTokens.get(nextAppIndex);
8525 if (nextApp == thisApp) {
8526 break;
8527 }
8528 }
8529 if (thisApp != nextApp) {
8530 // Uh oh, the app token doesn't exist! This shouldn't
8531 // happen, but if it does we can get totally hosed...
8532 // so restart at the original app.
8533 nextAppIndex = origAppIndex;
8534 nextApp = mAppTokens.get(nextAppIndex);
8535 }
8536 }
8537
8538 // Dispatch to this window if it is wants key events.
8539 if (win.canReceiveKeys()) {
8540 if (DEBUG_FOCUS) Log.v(
8541 TAG, "Found focus @ " + i + " = " + win);
8542 result = win;
8543 break;
8544 }
8545
8546 i--;
8547 }
8548
8549 return result;
8550 }
8551
8552 private void startFreezingDisplayLocked() {
8553 if (mDisplayFrozen) {
8554 return;
8555 }
8556
8557 mScreenFrozenLock.acquire();
8558
8559 long now = SystemClock.uptimeMillis();
8560 //Log.i(TAG, "Freezing, gc pending: " + mFreezeGcPending + ", now " + now);
8561 if (mFreezeGcPending != 0) {
8562 if (now > (mFreezeGcPending+1000)) {
8563 //Log.i(TAG, "Gc! " + now + " > " + (mFreezeGcPending+1000));
8564 mH.removeMessages(H.FORCE_GC);
8565 Runtime.getRuntime().gc();
8566 mFreezeGcPending = now;
8567 }
8568 } else {
8569 mFreezeGcPending = now;
8570 }
8571
8572 mDisplayFrozen = true;
8573 if (mNextAppTransition != WindowManagerPolicy.TRANSIT_NONE) {
8574 mNextAppTransition = WindowManagerPolicy.TRANSIT_NONE;
8575 mAppTransitionReady = true;
8576 }
8577
8578 if (PROFILE_ORIENTATION) {
8579 File file = new File("/data/system/frozen");
8580 Debug.startMethodTracing(file.toString(), 8 * 1024 * 1024);
8581 }
8582 Surface.freezeDisplay(0);
8583 }
8584
8585 private void stopFreezingDisplayLocked() {
8586 if (!mDisplayFrozen) {
8587 return;
8588 }
8589
8590 mDisplayFrozen = false;
8591 mH.removeMessages(H.APP_FREEZE_TIMEOUT);
8592 if (PROFILE_ORIENTATION) {
8593 Debug.stopMethodTracing();
8594 }
8595 Surface.unfreezeDisplay(0);
8596
8597 // Freezing the display also suspends key event delivery, to
8598 // keep events from going astray while the display is reconfigured.
8599 // Now that we're back, notify the key waiter that we're alive
8600 // again and it should restart its timeouts.
8601 synchronized (mKeyWaiter) {
8602 mKeyWaiter.mWasFrozen = true;
8603 mKeyWaiter.notifyAll();
8604 }
8605
8606 // A little kludge: a lot could have happened while the
8607 // display was frozen, so now that we are coming back we
8608 // do a gc so that any remote references the system
8609 // processes holds on others can be released if they are
8610 // no longer needed.
8611 mH.removeMessages(H.FORCE_GC);
8612 mH.sendMessageDelayed(mH.obtainMessage(H.FORCE_GC),
8613 2000);
8614
8615 mScreenFrozenLock.release();
8616 }
8617
8618 @Override
8619 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
8620 if (mContext.checkCallingOrSelfPermission("android.permission.DUMP")
8621 != PackageManager.PERMISSION_GRANTED) {
8622 pw.println("Permission Denial: can't dump WindowManager from from pid="
8623 + Binder.getCallingPid()
8624 + ", uid=" + Binder.getCallingUid());
8625 return;
8626 }
8627
8628 synchronized(mWindowMap) {
8629 pw.println("Current Window Manager state:");
8630 for (int i=mWindows.size()-1; i>=0; i--) {
8631 WindowState w = (WindowState)mWindows.get(i);
8632 pw.println(" Window #" + i + ":");
8633 w.dump(pw, " ");
8634 }
8635 if (mInputMethodDialogs.size() > 0) {
8636 pw.println(" ");
8637 pw.println(" Input method dialogs:");
8638 for (int i=mInputMethodDialogs.size()-1; i>=0; i--) {
8639 WindowState w = mInputMethodDialogs.get(i);
8640 pw.println(" IM Dialog #" + i + ": " + w);
8641 }
8642 }
8643 if (mPendingRemove.size() > 0) {
8644 pw.println(" ");
8645 pw.println(" Remove pending for:");
8646 for (int i=mPendingRemove.size()-1; i>=0; i--) {
8647 WindowState w = mPendingRemove.get(i);
8648 pw.println(" Remove #" + i + ":");
8649 w.dump(pw, " ");
8650 }
8651 }
8652 if (mForceRemoves != null && mForceRemoves.size() > 0) {
8653 pw.println(" ");
8654 pw.println(" Windows force removing:");
8655 for (int i=mForceRemoves.size()-1; i>=0; i--) {
8656 WindowState w = mForceRemoves.get(i);
8657 pw.println(" Removing #" + i + ":");
8658 w.dump(pw, " ");
8659 }
8660 }
8661 if (mDestroySurface.size() > 0) {
8662 pw.println(" ");
8663 pw.println(" Windows waiting to destroy their surface:");
8664 for (int i=mDestroySurface.size()-1; i>=0; i--) {
8665 WindowState w = mDestroySurface.get(i);
8666 pw.println(" Destroy #" + i + ":");
8667 w.dump(pw, " ");
8668 }
8669 }
8670 if (mLosingFocus.size() > 0) {
8671 pw.println(" ");
8672 pw.println(" Windows losing focus:");
8673 for (int i=mLosingFocus.size()-1; i>=0; i--) {
8674 WindowState w = mLosingFocus.get(i);
8675 pw.println(" Losing #" + i + ":");
8676 w.dump(pw, " ");
8677 }
8678 }
8679 if (mSessions.size() > 0) {
8680 pw.println(" ");
8681 pw.println(" All active sessions:");
8682 Iterator<Session> it = mSessions.iterator();
8683 while (it.hasNext()) {
8684 Session s = it.next();
8685 pw.println(" Session " + s);
8686 s.dump(pw, " ");
8687 }
8688 }
8689 if (mTokenMap.size() > 0) {
8690 pw.println(" ");
8691 pw.println(" All tokens:");
8692 Iterator<WindowToken> it = mTokenMap.values().iterator();
8693 while (it.hasNext()) {
8694 WindowToken token = it.next();
8695 pw.println(" Token " + token.token);
8696 token.dump(pw, " ");
8697 }
8698 }
8699 if (mTokenList.size() > 0) {
8700 pw.println(" ");
8701 pw.println(" Window token list:");
8702 for (int i=0; i<mTokenList.size(); i++) {
8703 pw.println(" WindowToken #" + i + ": " + mTokenList.get(i));
8704 }
8705 }
8706 if (mAppTokens.size() > 0) {
8707 pw.println(" ");
8708 pw.println(" Application tokens in Z order:");
8709 for (int i=mAppTokens.size()-1; i>=0; i--) {
8710 pw.println(" AppWindowToken #" + i + ": " + mAppTokens.get(i));
8711 }
8712 }
8713 if (mFinishedStarting.size() > 0) {
8714 pw.println(" ");
8715 pw.println(" Finishing start of application tokens:");
8716 for (int i=mFinishedStarting.size()-1; i>=0; i--) {
8717 WindowToken token = mFinishedStarting.get(i);
8718 pw.println(" Finish Starting App Token #" + i + ":");
8719 token.dump(pw, " ");
8720 }
8721 }
8722 if (mExitingTokens.size() > 0) {
8723 pw.println(" ");
8724 pw.println(" Exiting tokens:");
8725 for (int i=mExitingTokens.size()-1; i>=0; i--) {
8726 WindowToken token = mExitingTokens.get(i);
8727 pw.println(" Exiting Token #" + i + ":");
8728 token.dump(pw, " ");
8729 }
8730 }
8731 if (mExitingAppTokens.size() > 0) {
8732 pw.println(" ");
8733 pw.println(" Exiting application tokens:");
8734 for (int i=mExitingAppTokens.size()-1; i>=0; i--) {
8735 WindowToken token = mExitingAppTokens.get(i);
8736 pw.println(" Exiting App Token #" + i + ":");
8737 token.dump(pw, " ");
8738 }
8739 }
8740 pw.println(" ");
8741 pw.println(" mCurrentFocus=" + mCurrentFocus);
8742 pw.println(" mLastFocus=" + mLastFocus);
8743 pw.println(" mFocusedApp=" + mFocusedApp);
8744 pw.println(" mInputMethodTarget=" + mInputMethodTarget);
8745 pw.println(" mInputMethodWindow=" + mInputMethodWindow);
8746 pw.println(" mInTouchMode=" + mInTouchMode);
8747 pw.println(" mSystemBooted=" + mSystemBooted
8748 + " mDisplayEnabled=" + mDisplayEnabled);
8749 pw.println(" mLayoutNeeded=" + mLayoutNeeded
8750 + " mBlurShown=" + mBlurShown);
8751 pw.println(" mDimShown=" + mDimShown
8752 + " current=" + mDimCurrentAlpha
8753 + " target=" + mDimTargetAlpha
8754 + " delta=" + mDimDeltaPerMs
8755 + " lastAnimTime=" + mLastDimAnimTime);
8756 pw.println(" mInputMethodAnimLayerAdjustment="
8757 + mInputMethodAnimLayerAdjustment);
8758 pw.println(" mDisplayFrozen=" + mDisplayFrozen
8759 + " mWindowsFreezingScreen=" + mWindowsFreezingScreen
8760 + " mAppsFreezingScreen=" + mAppsFreezingScreen);
8761 pw.println(" mRotation=" + mRotation
8762 + ", mForcedAppOrientation=" + mForcedAppOrientation
8763 + ", mRequestedRotation=" + mRequestedRotation);
8764 pw.println(" mAnimationPending=" + mAnimationPending
8765 + " mWindowAnimationScale=" + mWindowAnimationScale
8766 + " mTransitionWindowAnimationScale=" + mTransitionAnimationScale);
8767 pw.println(" mNextAppTransition=0x"
8768 + Integer.toHexString(mNextAppTransition)
8769 + ", mAppTransitionReady=" + mAppTransitionReady
8770 + ", mAppTransitionTimeout=" + mAppTransitionTimeout);
8771 pw.println(" mStartingIconInTransition=" + mStartingIconInTransition
8772 + ", mSkipAppTransitionAnimation=" + mSkipAppTransitionAnimation);
8773 pw.println(" mOpeningApps=" + mOpeningApps);
8774 pw.println(" mClosingApps=" + mClosingApps);
8775 pw.println(" DisplayWidth=" + mDisplay.getWidth()
8776 + " DisplayHeight=" + mDisplay.getHeight());
8777 pw.println(" KeyWaiter state:");
8778 pw.println(" mLastWin=" + mKeyWaiter.mLastWin
8779 + " mLastBinder=" + mKeyWaiter.mLastBinder);
8780 pw.println(" mFinished=" + mKeyWaiter.mFinished
8781 + " mGotFirstWindow=" + mKeyWaiter.mGotFirstWindow
8782 + " mEventDispatching=" + mKeyWaiter.mEventDispatching
8783 + " mTimeToSwitch=" + mKeyWaiter.mTimeToSwitch);
8784 }
8785 }
8786
8787 public void monitor() {
8788 synchronized (mWindowMap) { }
8789 synchronized (mKeyguardDisabled) { }
8790 synchronized (mKeyWaiter) { }
8791 }
8792}