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