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