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