blob: 3b47ae7f218245bdc275061b1cb51dae83f38e5c [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
19import static android.os.LocalPowerManager.CHEEK_EVENT;
20import static android.os.LocalPowerManager.OTHER_EVENT;
21import static android.os.LocalPowerManager.TOUCH_EVENT;
Joe Onoratoe68ffcb2009-03-24 19:11:13 -070022import static android.os.LocalPowerManager.LONG_TOUCH_EVENT;
23import static android.os.LocalPowerManager.TOUCH_UP_EVENT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080024import static android.view.WindowManager.LayoutParams.FIRST_APPLICATION_WINDOW;
25import static android.view.WindowManager.LayoutParams.FIRST_SUB_WINDOW;
26import static android.view.WindowManager.LayoutParams.FLAG_BLUR_BEHIND;
27import static android.view.WindowManager.LayoutParams.FLAG_DIM_BEHIND;
28import static android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
29import static android.view.WindowManager.LayoutParams.FLAG_SYSTEM_ERROR;
30import static android.view.WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
31import static android.view.WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM;
32import static android.view.WindowManager.LayoutParams.LAST_APPLICATION_WINDOW;
33import static android.view.WindowManager.LayoutParams.LAST_SUB_WINDOW;
34import static android.view.WindowManager.LayoutParams.MEMORY_TYPE_GPU;
35import static android.view.WindowManager.LayoutParams.MEMORY_TYPE_HARDWARE;
36import static android.view.WindowManager.LayoutParams.MEMORY_TYPE_PUSH_BUFFERS;
37import static android.view.WindowManager.LayoutParams.TYPE_APPLICATION_STARTING;
38import static android.view.WindowManager.LayoutParams.TYPE_BASE_APPLICATION;
39import static android.view.WindowManager.LayoutParams.TYPE_INPUT_METHOD;
40import static android.view.WindowManager.LayoutParams.TYPE_INPUT_METHOD_DIALOG;
41
42import com.android.internal.app.IBatteryStats;
43import com.android.internal.policy.PolicyManager;
44import com.android.internal.view.IInputContext;
45import com.android.internal.view.IInputMethodClient;
46import com.android.internal.view.IInputMethodManager;
47import com.android.server.KeyInputQueue.QueuedEvent;
48import com.android.server.am.BatteryStatsService;
49
50import android.Manifest;
51import android.app.ActivityManagerNative;
52import android.app.IActivityManager;
53import android.content.Context;
54import android.content.pm.ActivityInfo;
55import android.content.pm.PackageManager;
56import android.content.res.Configuration;
57import android.graphics.Matrix;
58import android.graphics.PixelFormat;
59import android.graphics.Rect;
60import android.graphics.Region;
61import android.os.BatteryStats;
62import android.os.Binder;
63import android.os.Debug;
64import android.os.Handler;
65import android.os.IBinder;
66import android.os.LocalPowerManager;
67import android.os.Looper;
68import android.os.Message;
69import android.os.Parcel;
70import android.os.ParcelFileDescriptor;
71import android.os.Power;
72import android.os.PowerManager;
73import android.os.Process;
74import android.os.RemoteException;
75import android.os.ServiceManager;
76import android.os.SystemClock;
77import android.os.SystemProperties;
78import android.os.TokenWatcher;
79import android.provider.Settings;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080080import android.util.EventLog;
81import android.util.Log;
82import android.util.SparseIntArray;
83import android.view.Display;
84import android.view.Gravity;
85import android.view.IApplicationToken;
86import android.view.IOnKeyguardExitResult;
87import android.view.IRotationWatcher;
88import android.view.IWindow;
89import android.view.IWindowManager;
90import android.view.IWindowSession;
91import android.view.KeyEvent;
92import android.view.MotionEvent;
93import android.view.RawInputEvent;
94import android.view.Surface;
95import android.view.SurfaceSession;
96import android.view.View;
97import android.view.ViewTreeObserver;
98import android.view.WindowManager;
99import android.view.WindowManagerImpl;
100import android.view.WindowManagerPolicy;
101import android.view.WindowManager.LayoutParams;
102import android.view.animation.Animation;
103import android.view.animation.AnimationUtils;
104import android.view.animation.Transformation;
105
106import java.io.BufferedWriter;
107import java.io.File;
108import java.io.FileDescriptor;
109import java.io.IOException;
110import java.io.OutputStream;
111import java.io.OutputStreamWriter;
112import java.io.PrintWriter;
113import java.io.StringWriter;
114import java.net.Socket;
115import java.util.ArrayList;
116import java.util.HashMap;
117import java.util.HashSet;
118import java.util.Iterator;
119import java.util.List;
120
121/** {@hide} */
122public class WindowManagerService extends IWindowManager.Stub implements Watchdog.Monitor {
123 static final String TAG = "WindowManager";
124 static final boolean DEBUG = false;
125 static final boolean DEBUG_FOCUS = false;
126 static final boolean DEBUG_ANIM = false;
127 static final boolean DEBUG_LAYERS = false;
128 static final boolean DEBUG_INPUT = false;
129 static final boolean DEBUG_INPUT_METHOD = false;
130 static final boolean DEBUG_VISIBILITY = false;
131 static final boolean DEBUG_ORIENTATION = false;
132 static final boolean DEBUG_APP_TRANSITIONS = false;
133 static final boolean DEBUG_STARTING_WINDOW = false;
134 static final boolean DEBUG_REORDER = false;
135 static final boolean SHOW_TRANSACTIONS = false;
Romain Guy06882f82009-06-10 13:36:04 -0700136
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800137 static final boolean PROFILE_ORIENTATION = false;
138 static final boolean BLUR = true;
Dave Bortcfe65242009-04-09 14:51:04 -0700139 static final boolean localLOGV = DEBUG;
Romain Guy06882f82009-06-10 13:36:04 -0700140
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800141 static final int LOG_WM_NO_SURFACE_MEMORY = 31000;
Romain Guy06882f82009-06-10 13:36:04 -0700142
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800143 /** How long to wait for first key repeat, in milliseconds */
144 static final int KEY_REPEAT_FIRST_DELAY = 750;
Romain Guy06882f82009-06-10 13:36:04 -0700145
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800146 /** How long to wait for subsequent key repeats, in milliseconds */
147 static final int KEY_REPEAT_DELAY = 50;
148
149 /** How much to multiply the policy's type layer, to reserve room
150 * for multiple windows of the same type and Z-ordering adjustment
151 * with TYPE_LAYER_OFFSET. */
152 static final int TYPE_LAYER_MULTIPLIER = 10000;
Romain Guy06882f82009-06-10 13:36:04 -0700153
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800154 /** Offset from TYPE_LAYER_MULTIPLIER for moving a group of windows above
155 * or below others in the same layer. */
156 static final int TYPE_LAYER_OFFSET = 1000;
Romain Guy06882f82009-06-10 13:36:04 -0700157
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800158 /** How much to increment the layer for each window, to reserve room
159 * for effect surfaces between them.
160 */
161 static final int WINDOW_LAYER_MULTIPLIER = 5;
Romain Guy06882f82009-06-10 13:36:04 -0700162
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800163 /** The maximum length we will accept for a loaded animation duration:
164 * this is 10 seconds.
165 */
166 static final int MAX_ANIMATION_DURATION = 10*1000;
167
168 /** Amount of time (in milliseconds) to animate the dim surface from one
169 * value to another, when no window animation is driving it.
170 */
171 static final int DEFAULT_DIM_DURATION = 200;
172
173 /** Adjustment to time to perform a dim, to make it more dramatic.
174 */
175 static final int DIM_DURATION_MULTIPLIER = 6;
Romain Guy06882f82009-06-10 13:36:04 -0700176
Dianne Hackborncfaef692009-06-15 14:24:44 -0700177 static final int INJECT_FAILED = 0;
178 static final int INJECT_SUCCEEDED = 1;
179 static final int INJECT_NO_PERMISSION = -1;
180
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800181 static final int UPDATE_FOCUS_NORMAL = 0;
182 static final int UPDATE_FOCUS_WILL_ASSIGN_LAYERS = 1;
183 static final int UPDATE_FOCUS_PLACING_SURFACES = 2;
184 static final int UPDATE_FOCUS_WILL_PLACE_SURFACES = 3;
Romain Guy06882f82009-06-10 13:36:04 -0700185
Michael Chane96440f2009-05-06 10:27:36 -0700186 /** The minimum time between dispatching touch events. */
187 int mMinWaitTimeBetweenTouchEvents = 1000 / 35;
188
189 // Last touch event time
190 long mLastTouchEventTime = 0;
Romain Guy06882f82009-06-10 13:36:04 -0700191
Michael Chane96440f2009-05-06 10:27:36 -0700192 // Last touch event type
193 int mLastTouchEventType = OTHER_EVENT;
Romain Guy06882f82009-06-10 13:36:04 -0700194
Michael Chane96440f2009-05-06 10:27:36 -0700195 // Time to wait before calling useractivity again. This saves CPU usage
196 // when we get a flood of touch events.
197 static final int MIN_TIME_BETWEEN_USERACTIVITIES = 1000;
198
199 // Last time we call user activity
200 long mLastUserActivityCallTime = 0;
201
Romain Guy06882f82009-06-10 13:36:04 -0700202 // Last time we updated battery stats
Michael Chane96440f2009-05-06 10:27:36 -0700203 long mLastBatteryStatsCallTime = 0;
Romain Guy06882f82009-06-10 13:36:04 -0700204
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800205 private static final String SYSTEM_SECURE = "ro.secure";
Romain Guy06882f82009-06-10 13:36:04 -0700206 private static final String SYSTEM_DEBUGGABLE = "ro.debuggable";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800207
208 /**
209 * Condition waited on by {@link #reenableKeyguard} to know the call to
210 * the window policy has finished.
211 */
212 private boolean mWaitingUntilKeyguardReenabled = false;
213
214
215 final TokenWatcher mKeyguardDisabled = new TokenWatcher(
216 new Handler(), "WindowManagerService.mKeyguardDisabled") {
217 public void acquired() {
218 mPolicy.enableKeyguard(false);
219 }
220 public void released() {
221 synchronized (mKeyguardDisabled) {
222 mPolicy.enableKeyguard(true);
223 mWaitingUntilKeyguardReenabled = false;
224 mKeyguardDisabled.notifyAll();
225 }
226 }
227 };
228
229 final Context mContext;
230
231 final boolean mHaveInputMethods;
Romain Guy06882f82009-06-10 13:36:04 -0700232
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800233 final boolean mLimitedAlphaCompositing;
Romain Guy06882f82009-06-10 13:36:04 -0700234
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800235 final WindowManagerPolicy mPolicy = PolicyManager.makeNewWindowManager();
236
237 final IActivityManager mActivityManager;
Romain Guy06882f82009-06-10 13:36:04 -0700238
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800239 final IBatteryStats mBatteryStats;
Romain Guy06882f82009-06-10 13:36:04 -0700240
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800241 /**
242 * All currently active sessions with clients.
243 */
244 final HashSet<Session> mSessions = new HashSet<Session>();
Romain Guy06882f82009-06-10 13:36:04 -0700245
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800246 /**
247 * Mapping from an IWindow IBinder to the server's Window object.
248 * This is also used as the lock for all of our state.
249 */
250 final HashMap<IBinder, WindowState> mWindowMap = new HashMap<IBinder, WindowState>();
251
252 /**
253 * Mapping from a token IBinder to a WindowToken object.
254 */
255 final HashMap<IBinder, WindowToken> mTokenMap =
256 new HashMap<IBinder, WindowToken>();
257
258 /**
259 * The same tokens as mTokenMap, stored in a list for efficient iteration
260 * over them.
261 */
262 final ArrayList<WindowToken> mTokenList = new ArrayList<WindowToken>();
Romain Guy06882f82009-06-10 13:36:04 -0700263
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800264 /**
265 * Window tokens that are in the process of exiting, but still
266 * on screen for animations.
267 */
268 final ArrayList<WindowToken> mExitingTokens = new ArrayList<WindowToken>();
269
270 /**
271 * Z-ordered (bottom-most first) list of all application tokens, for
272 * controlling the ordering of windows in different applications. This
273 * contains WindowToken objects.
274 */
275 final ArrayList<AppWindowToken> mAppTokens = new ArrayList<AppWindowToken>();
276
277 /**
278 * Application tokens that are in the process of exiting, but still
279 * on screen for animations.
280 */
281 final ArrayList<AppWindowToken> mExitingAppTokens = new ArrayList<AppWindowToken>();
282
283 /**
284 * List of window tokens that have finished starting their application,
285 * and now need to have the policy remove their windows.
286 */
287 final ArrayList<AppWindowToken> mFinishedStarting = new ArrayList<AppWindowToken>();
288
289 /**
290 * Z-ordered (bottom-most first) list of all Window objects.
291 */
292 final ArrayList mWindows = new ArrayList();
293
294 /**
295 * Windows that are being resized. Used so we can tell the client about
296 * the resize after closing the transaction in which we resized the
297 * underlying surface.
298 */
299 final ArrayList<WindowState> mResizingWindows = new ArrayList<WindowState>();
300
301 /**
302 * Windows whose animations have ended and now must be removed.
303 */
304 final ArrayList<WindowState> mPendingRemove = new ArrayList<WindowState>();
305
306 /**
307 * Windows whose surface should be destroyed.
308 */
309 final ArrayList<WindowState> mDestroySurface = new ArrayList<WindowState>();
310
311 /**
312 * Windows that have lost input focus and are waiting for the new
313 * focus window to be displayed before they are told about this.
314 */
315 ArrayList<WindowState> mLosingFocus = new ArrayList<WindowState>();
316
317 /**
318 * This is set when we have run out of memory, and will either be an empty
319 * list or contain windows that need to be force removed.
320 */
321 ArrayList<WindowState> mForceRemoves;
Romain Guy06882f82009-06-10 13:36:04 -0700322
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800323 IInputMethodManager mInputMethodManager;
Romain Guy06882f82009-06-10 13:36:04 -0700324
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800325 SurfaceSession mFxSession;
326 Surface mDimSurface;
327 boolean mDimShown;
328 float mDimCurrentAlpha;
329 float mDimTargetAlpha;
330 float mDimDeltaPerMs;
331 long mLastDimAnimTime;
332 Surface mBlurSurface;
333 boolean mBlurShown;
Romain Guy06882f82009-06-10 13:36:04 -0700334
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800335 int mTransactionSequence = 0;
Romain Guy06882f82009-06-10 13:36:04 -0700336
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800337 final float[] mTmpFloats = new float[9];
338
339 boolean mSafeMode;
340 boolean mDisplayEnabled = false;
341 boolean mSystemBooted = false;
342 int mRotation = 0;
343 int mRequestedRotation = 0;
344 int mForcedAppOrientation = ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
Dianne Hackborn321ae682009-03-27 16:16:03 -0700345 int mLastRotationFlags;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800346 ArrayList<IRotationWatcher> mRotationWatchers
347 = new ArrayList<IRotationWatcher>();
Romain Guy06882f82009-06-10 13:36:04 -0700348
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800349 boolean mLayoutNeeded = true;
350 boolean mAnimationPending = false;
351 boolean mDisplayFrozen = false;
352 boolean mWindowsFreezingScreen = false;
353 long mFreezeGcPending = 0;
354 int mAppsFreezingScreen = 0;
355
356 // This is held as long as we have the screen frozen, to give us time to
357 // perform a rotation animation when turning off shows the lock screen which
358 // changes the orientation.
359 PowerManager.WakeLock mScreenFrozenLock;
Romain Guy06882f82009-06-10 13:36:04 -0700360
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800361 // State management of app transitions. When we are preparing for a
362 // transition, mNextAppTransition will be the kind of transition to
363 // perform or TRANSIT_NONE if we are not waiting. If we are waiting,
364 // mOpeningApps and mClosingApps are the lists of tokens that will be
365 // made visible or hidden at the next transition.
366 int mNextAppTransition = WindowManagerPolicy.TRANSIT_NONE;
367 boolean mAppTransitionReady = false;
368 boolean mAppTransitionTimeout = false;
369 boolean mStartingIconInTransition = false;
370 boolean mSkipAppTransitionAnimation = false;
371 final ArrayList<AppWindowToken> mOpeningApps = new ArrayList<AppWindowToken>();
372 final ArrayList<AppWindowToken> mClosingApps = new ArrayList<AppWindowToken>();
Romain Guy06882f82009-06-10 13:36:04 -0700373
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800374 //flag to detect fat touch events
375 boolean mFatTouch = false;
376 Display mDisplay;
Romain Guy06882f82009-06-10 13:36:04 -0700377
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800378 H mH = new H();
379
380 WindowState mCurrentFocus = null;
381 WindowState mLastFocus = null;
Romain Guy06882f82009-06-10 13:36:04 -0700382
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800383 // This just indicates the window the input method is on top of, not
384 // necessarily the window its input is going to.
385 WindowState mInputMethodTarget = null;
386 WindowState mUpcomingInputMethodTarget = null;
387 boolean mInputMethodTargetWaitingAnim;
388 int mInputMethodAnimLayerAdjustment;
Romain Guy06882f82009-06-10 13:36:04 -0700389
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800390 WindowState mInputMethodWindow = null;
391 final ArrayList<WindowState> mInputMethodDialogs = new ArrayList<WindowState>();
392
393 AppWindowToken mFocusedApp = null;
394
395 PowerManagerService mPowerManager;
Romain Guy06882f82009-06-10 13:36:04 -0700396
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800397 float mWindowAnimationScale = 1.0f;
398 float mTransitionAnimationScale = 1.0f;
Romain Guy06882f82009-06-10 13:36:04 -0700399
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800400 final KeyWaiter mKeyWaiter = new KeyWaiter();
401 final KeyQ mQueue;
402 final InputDispatcherThread mInputThread;
403
404 // Who is holding the screen on.
405 Session mHoldingScreenOn;
Romain Guy06882f82009-06-10 13:36:04 -0700406
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800407 /**
408 * Whether the UI is currently running in touch mode (not showing
409 * navigational focus because the user is directly pressing the screen).
410 */
411 boolean mInTouchMode = false;
412
413 private ViewServer mViewServer;
414
415 final Rect mTempRect = new Rect();
Romain Guy06882f82009-06-10 13:36:04 -0700416
Dianne Hackbornc485a602009-03-24 22:39:49 -0700417 final Configuration mTempConfiguration = new Configuration();
Romain Guy06882f82009-06-10 13:36:04 -0700418
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800419 public static WindowManagerService main(Context context,
420 PowerManagerService pm, boolean haveInputMethods) {
421 WMThread thr = new WMThread(context, pm, haveInputMethods);
422 thr.start();
Romain Guy06882f82009-06-10 13:36:04 -0700423
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800424 synchronized (thr) {
425 while (thr.mService == null) {
426 try {
427 thr.wait();
428 } catch (InterruptedException e) {
429 }
430 }
431 }
Romain Guy06882f82009-06-10 13:36:04 -0700432
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800433 return thr.mService;
434 }
Romain Guy06882f82009-06-10 13:36:04 -0700435
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800436 static class WMThread extends Thread {
437 WindowManagerService mService;
Romain Guy06882f82009-06-10 13:36:04 -0700438
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800439 private final Context mContext;
440 private final PowerManagerService mPM;
441 private final boolean mHaveInputMethods;
Romain Guy06882f82009-06-10 13:36:04 -0700442
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800443 public WMThread(Context context, PowerManagerService pm,
444 boolean haveInputMethods) {
445 super("WindowManager");
446 mContext = context;
447 mPM = pm;
448 mHaveInputMethods = haveInputMethods;
449 }
Romain Guy06882f82009-06-10 13:36:04 -0700450
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800451 public void run() {
452 Looper.prepare();
453 WindowManagerService s = new WindowManagerService(mContext, mPM,
454 mHaveInputMethods);
455 android.os.Process.setThreadPriority(
456 android.os.Process.THREAD_PRIORITY_DISPLAY);
Romain Guy06882f82009-06-10 13:36:04 -0700457
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800458 synchronized (this) {
459 mService = s;
460 notifyAll();
461 }
Romain Guy06882f82009-06-10 13:36:04 -0700462
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800463 Looper.loop();
464 }
465 }
466
467 static class PolicyThread extends Thread {
468 private final WindowManagerPolicy mPolicy;
469 private final WindowManagerService mService;
470 private final Context mContext;
471 private final PowerManagerService mPM;
472 boolean mRunning = false;
Romain Guy06882f82009-06-10 13:36:04 -0700473
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800474 public PolicyThread(WindowManagerPolicy policy,
475 WindowManagerService service, Context context,
476 PowerManagerService pm) {
477 super("WindowManagerPolicy");
478 mPolicy = policy;
479 mService = service;
480 mContext = context;
481 mPM = pm;
482 }
Romain Guy06882f82009-06-10 13:36:04 -0700483
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800484 public void run() {
485 Looper.prepare();
486 //Looper.myLooper().setMessageLogging(new LogPrinter(
487 // Log.VERBOSE, "WindowManagerPolicy"));
488 android.os.Process.setThreadPriority(
489 android.os.Process.THREAD_PRIORITY_FOREGROUND);
490 mPolicy.init(mContext, mService, mPM);
Romain Guy06882f82009-06-10 13:36:04 -0700491
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800492 synchronized (this) {
493 mRunning = true;
494 notifyAll();
495 }
Romain Guy06882f82009-06-10 13:36:04 -0700496
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800497 Looper.loop();
498 }
499 }
500
501 private WindowManagerService(Context context, PowerManagerService pm,
502 boolean haveInputMethods) {
503 mContext = context;
504 mHaveInputMethods = haveInputMethods;
505 mLimitedAlphaCompositing = context.getResources().getBoolean(
506 com.android.internal.R.bool.config_sf_limitedAlpha);
Romain Guy06882f82009-06-10 13:36:04 -0700507
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800508 mPowerManager = pm;
509 mPowerManager.setPolicy(mPolicy);
510 PowerManager pmc = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
511 mScreenFrozenLock = pmc.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
512 "SCREEN_FROZEN");
513 mScreenFrozenLock.setReferenceCounted(false);
514
515 mActivityManager = ActivityManagerNative.getDefault();
516 mBatteryStats = BatteryStatsService.getService();
517
518 // Get persisted window scale setting
519 mWindowAnimationScale = Settings.System.getFloat(context.getContentResolver(),
520 Settings.System.WINDOW_ANIMATION_SCALE, mWindowAnimationScale);
521 mTransitionAnimationScale = Settings.System.getFloat(context.getContentResolver(),
522 Settings.System.TRANSITION_ANIMATION_SCALE, mTransitionAnimationScale);
Romain Guy06882f82009-06-10 13:36:04 -0700523
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800524 mQueue = new KeyQ();
525
526 mInputThread = new InputDispatcherThread();
Romain Guy06882f82009-06-10 13:36:04 -0700527
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800528 PolicyThread thr = new PolicyThread(mPolicy, this, context, pm);
529 thr.start();
Romain Guy06882f82009-06-10 13:36:04 -0700530
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800531 synchronized (thr) {
532 while (!thr.mRunning) {
533 try {
534 thr.wait();
535 } catch (InterruptedException e) {
536 }
537 }
538 }
Romain Guy06882f82009-06-10 13:36:04 -0700539
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800540 mInputThread.start();
Romain Guy06882f82009-06-10 13:36:04 -0700541
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800542 // Add ourself to the Watchdog monitors.
543 Watchdog.getInstance().addMonitor(this);
544 }
545
546 @Override
547 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
548 throws RemoteException {
549 try {
550 return super.onTransact(code, data, reply, flags);
551 } catch (RuntimeException e) {
552 // The window manager only throws security exceptions, so let's
553 // log all others.
554 if (!(e instanceof SecurityException)) {
555 Log.e(TAG, "Window Manager Crash", e);
556 }
557 throw e;
558 }
559 }
560
561 private void placeWindowAfter(Object pos, WindowState window) {
562 final int i = mWindows.indexOf(pos);
563 if (localLOGV || DEBUG_FOCUS) Log.v(
564 TAG, "Adding window " + window + " at "
565 + (i+1) + " of " + mWindows.size() + " (after " + pos + ")");
566 mWindows.add(i+1, window);
567 }
568
569 private void placeWindowBefore(Object pos, WindowState window) {
570 final int i = mWindows.indexOf(pos);
571 if (localLOGV || DEBUG_FOCUS) Log.v(
572 TAG, "Adding window " + window + " at "
573 + i + " of " + mWindows.size() + " (before " + pos + ")");
574 mWindows.add(i, window);
575 }
576
577 //This method finds out the index of a window that has the same app token as
578 //win. used for z ordering the windows in mWindows
579 private int findIdxBasedOnAppTokens(WindowState win) {
580 //use a local variable to cache mWindows
581 ArrayList localmWindows = mWindows;
582 int jmax = localmWindows.size();
583 if(jmax == 0) {
584 return -1;
585 }
586 for(int j = (jmax-1); j >= 0; j--) {
587 WindowState wentry = (WindowState)localmWindows.get(j);
588 if(wentry.mAppToken == win.mAppToken) {
589 return j;
590 }
591 }
592 return -1;
593 }
Romain Guy06882f82009-06-10 13:36:04 -0700594
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800595 private void addWindowToListInOrderLocked(WindowState win, boolean addToToken) {
596 final IWindow client = win.mClient;
597 final WindowToken token = win.mToken;
598 final ArrayList localmWindows = mWindows;
Romain Guy06882f82009-06-10 13:36:04 -0700599
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800600 final int N = localmWindows.size();
601 final WindowState attached = win.mAttachedWindow;
602 int i;
603 if (attached == null) {
604 int tokenWindowsPos = token.windows.size();
605 if (token.appWindowToken != null) {
606 int index = tokenWindowsPos-1;
607 if (index >= 0) {
608 // If this application has existing windows, we
609 // simply place the new window on top of them... but
610 // keep the starting window on top.
611 if (win.mAttrs.type == TYPE_BASE_APPLICATION) {
612 // Base windows go behind everything else.
613 placeWindowBefore(token.windows.get(0), win);
614 tokenWindowsPos = 0;
615 } else {
616 AppWindowToken atoken = win.mAppToken;
617 if (atoken != null &&
618 token.windows.get(index) == atoken.startingWindow) {
619 placeWindowBefore(token.windows.get(index), win);
620 tokenWindowsPos--;
621 } else {
622 int newIdx = findIdxBasedOnAppTokens(win);
623 if(newIdx != -1) {
Romain Guy06882f82009-06-10 13:36:04 -0700624 //there is a window above this one associated with the same
625 //apptoken note that the window could be a floating window
626 //that was created later or a window at the top of the list of
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800627 //windows associated with this token.
628 localmWindows.add(newIdx+1, win);
Romain Guy06882f82009-06-10 13:36:04 -0700629 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800630 }
631 }
632 } else {
633 if (localLOGV) Log.v(
634 TAG, "Figuring out where to add app window "
635 + client.asBinder() + " (token=" + token + ")");
636 // Figure out where the window should go, based on the
637 // order of applications.
638 final int NA = mAppTokens.size();
639 Object pos = null;
640 for (i=NA-1; i>=0; i--) {
641 AppWindowToken t = mAppTokens.get(i);
642 if (t == token) {
643 i--;
644 break;
645 }
646 if (t.windows.size() > 0) {
647 pos = t.windows.get(0);
648 }
649 }
650 // We now know the index into the apps. If we found
651 // an app window above, that gives us the position; else
652 // we need to look some more.
653 if (pos != null) {
654 // Move behind any windows attached to this one.
Romain Guy06882f82009-06-10 13:36:04 -0700655 WindowToken atoken =
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800656 mTokenMap.get(((WindowState)pos).mClient.asBinder());
657 if (atoken != null) {
658 final int NC = atoken.windows.size();
659 if (NC > 0) {
660 WindowState bottom = atoken.windows.get(0);
661 if (bottom.mSubLayer < 0) {
662 pos = bottom;
663 }
664 }
665 }
666 placeWindowBefore(pos, win);
667 } else {
668 while (i >= 0) {
669 AppWindowToken t = mAppTokens.get(i);
670 final int NW = t.windows.size();
671 if (NW > 0) {
672 pos = t.windows.get(NW-1);
673 break;
674 }
675 i--;
676 }
677 if (pos != null) {
678 // Move in front of any windows attached to this
679 // one.
680 WindowToken atoken =
681 mTokenMap.get(((WindowState)pos).mClient.asBinder());
682 if (atoken != null) {
683 final int NC = atoken.windows.size();
684 if (NC > 0) {
685 WindowState top = atoken.windows.get(NC-1);
686 if (top.mSubLayer >= 0) {
687 pos = top;
688 }
689 }
690 }
691 placeWindowAfter(pos, win);
692 } else {
693 // Just search for the start of this layer.
694 final int myLayer = win.mBaseLayer;
695 for (i=0; i<N; i++) {
696 WindowState w = (WindowState)localmWindows.get(i);
697 if (w.mBaseLayer > myLayer) {
698 break;
699 }
700 }
701 if (localLOGV || DEBUG_FOCUS) Log.v(
702 TAG, "Adding window " + win + " at "
703 + i + " of " + N);
704 localmWindows.add(i, win);
705 }
706 }
707 }
708 } else {
709 // Figure out where window should go, based on layer.
710 final int myLayer = win.mBaseLayer;
711 for (i=N-1; i>=0; i--) {
712 if (((WindowState)localmWindows.get(i)).mBaseLayer <= myLayer) {
713 i++;
714 break;
715 }
716 }
717 if (i < 0) i = 0;
718 if (localLOGV || DEBUG_FOCUS) Log.v(
719 TAG, "Adding window " + win + " at "
720 + i + " of " + N);
721 localmWindows.add(i, win);
722 }
723 if (addToToken) {
724 token.windows.add(tokenWindowsPos, win);
725 }
726
727 } else {
728 // Figure out this window's ordering relative to the window
729 // it is attached to.
730 final int NA = token.windows.size();
731 final int sublayer = win.mSubLayer;
732 int largestSublayer = Integer.MIN_VALUE;
733 WindowState windowWithLargestSublayer = null;
734 for (i=0; i<NA; i++) {
735 WindowState w = token.windows.get(i);
736 final int wSublayer = w.mSubLayer;
737 if (wSublayer >= largestSublayer) {
738 largestSublayer = wSublayer;
739 windowWithLargestSublayer = w;
740 }
741 if (sublayer < 0) {
742 // For negative sublayers, we go below all windows
743 // in the same sublayer.
744 if (wSublayer >= sublayer) {
745 if (addToToken) {
746 token.windows.add(i, win);
747 }
748 placeWindowBefore(
749 wSublayer >= 0 ? attached : w, win);
750 break;
751 }
752 } else {
753 // For positive sublayers, we go above all windows
754 // in the same sublayer.
755 if (wSublayer > sublayer) {
756 if (addToToken) {
757 token.windows.add(i, win);
758 }
759 placeWindowBefore(w, win);
760 break;
761 }
762 }
763 }
764 if (i >= NA) {
765 if (addToToken) {
766 token.windows.add(win);
767 }
768 if (sublayer < 0) {
769 placeWindowBefore(attached, win);
770 } else {
771 placeWindowAfter(largestSublayer >= 0
772 ? windowWithLargestSublayer
773 : attached,
774 win);
775 }
776 }
777 }
Romain Guy06882f82009-06-10 13:36:04 -0700778
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800779 if (win.mAppToken != null && addToToken) {
780 win.mAppToken.allAppWindows.add(win);
781 }
782 }
Romain Guy06882f82009-06-10 13:36:04 -0700783
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800784 static boolean canBeImeTarget(WindowState w) {
785 final int fl = w.mAttrs.flags
786 & (FLAG_NOT_FOCUSABLE|FLAG_ALT_FOCUSABLE_IM);
787 if (fl == 0 || fl == (FLAG_NOT_FOCUSABLE|FLAG_ALT_FOCUSABLE_IM)) {
788 return w.isVisibleOrAdding();
789 }
790 return false;
791 }
Romain Guy06882f82009-06-10 13:36:04 -0700792
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800793 int findDesiredInputMethodWindowIndexLocked(boolean willMove) {
794 final ArrayList localmWindows = mWindows;
795 final int N = localmWindows.size();
796 WindowState w = null;
797 int i = N;
798 while (i > 0) {
799 i--;
800 w = (WindowState)localmWindows.get(i);
Romain Guy06882f82009-06-10 13:36:04 -0700801
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800802 //Log.i(TAG, "Checking window @" + i + " " + w + " fl=0x"
803 // + Integer.toHexString(w.mAttrs.flags));
804 if (canBeImeTarget(w)) {
805 //Log.i(TAG, "Putting input method here!");
Romain Guy06882f82009-06-10 13:36:04 -0700806
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800807 // Yet more tricksyness! If this window is a "starting"
808 // window, we do actually want to be on top of it, but
809 // it is not -really- where input will go. So if the caller
810 // is not actually looking to move the IME, look down below
811 // for a real window to target...
812 if (!willMove
813 && w.mAttrs.type == WindowManager.LayoutParams.TYPE_APPLICATION_STARTING
814 && i > 0) {
815 WindowState wb = (WindowState)localmWindows.get(i-1);
816 if (wb.mAppToken == w.mAppToken && canBeImeTarget(wb)) {
817 i--;
818 w = wb;
819 }
820 }
821 break;
822 }
823 }
Romain Guy06882f82009-06-10 13:36:04 -0700824
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800825 mUpcomingInputMethodTarget = w;
Romain Guy06882f82009-06-10 13:36:04 -0700826
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800827 if (DEBUG_INPUT_METHOD) Log.v(TAG, "Desired input method target="
828 + w + " willMove=" + willMove);
Romain Guy06882f82009-06-10 13:36:04 -0700829
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800830 if (willMove && w != null) {
831 final WindowState curTarget = mInputMethodTarget;
832 if (curTarget != null && curTarget.mAppToken != null) {
Romain Guy06882f82009-06-10 13:36:04 -0700833
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800834 // Now some fun for dealing with window animations that
835 // modify the Z order. We need to look at all windows below
836 // the current target that are in this app, finding the highest
837 // visible one in layering.
838 AppWindowToken token = curTarget.mAppToken;
839 WindowState highestTarget = null;
840 int highestPos = 0;
841 if (token.animating || token.animation != null) {
842 int pos = 0;
843 pos = localmWindows.indexOf(curTarget);
844 while (pos >= 0) {
845 WindowState win = (WindowState)localmWindows.get(pos);
846 if (win.mAppToken != token) {
847 break;
848 }
849 if (!win.mRemoved) {
850 if (highestTarget == null || win.mAnimLayer >
851 highestTarget.mAnimLayer) {
852 highestTarget = win;
853 highestPos = pos;
854 }
855 }
856 pos--;
857 }
858 }
Romain Guy06882f82009-06-10 13:36:04 -0700859
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800860 if (highestTarget != null) {
Romain Guy06882f82009-06-10 13:36:04 -0700861 if (DEBUG_INPUT_METHOD) Log.v(TAG, "mNextAppTransition="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800862 + mNextAppTransition + " " + highestTarget
863 + " animating=" + highestTarget.isAnimating()
864 + " layer=" + highestTarget.mAnimLayer
865 + " new layer=" + w.mAnimLayer);
Romain Guy06882f82009-06-10 13:36:04 -0700866
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800867 if (mNextAppTransition != WindowManagerPolicy.TRANSIT_NONE) {
868 // If we are currently setting up for an animation,
869 // hold everything until we can find out what will happen.
870 mInputMethodTargetWaitingAnim = true;
871 mInputMethodTarget = highestTarget;
872 return highestPos + 1;
873 } else if (highestTarget.isAnimating() &&
874 highestTarget.mAnimLayer > w.mAnimLayer) {
875 // If the window we are currently targeting is involved
876 // with an animation, and it is on top of the next target
877 // we will be over, then hold off on moving until
878 // that is done.
879 mInputMethodTarget = highestTarget;
880 return highestPos + 1;
881 }
882 }
883 }
884 }
Romain Guy06882f82009-06-10 13:36:04 -0700885
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800886 //Log.i(TAG, "Placing input method @" + (i+1));
887 if (w != null) {
888 if (willMove) {
889 RuntimeException e = new RuntimeException();
890 e.fillInStackTrace();
891 if (DEBUG_INPUT_METHOD) Log.w(TAG, "Moving IM target from "
892 + mInputMethodTarget + " to " + w, e);
893 mInputMethodTarget = w;
894 if (w.mAppToken != null) {
895 setInputMethodAnimLayerAdjustment(w.mAppToken.animLayerAdjustment);
896 } else {
897 setInputMethodAnimLayerAdjustment(0);
898 }
899 }
900 return i+1;
901 }
902 if (willMove) {
903 RuntimeException e = new RuntimeException();
904 e.fillInStackTrace();
905 if (DEBUG_INPUT_METHOD) Log.w(TAG, "Moving IM target from "
906 + mInputMethodTarget + " to null", e);
907 mInputMethodTarget = null;
908 setInputMethodAnimLayerAdjustment(0);
909 }
910 return -1;
911 }
Romain Guy06882f82009-06-10 13:36:04 -0700912
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800913 void addInputMethodWindowToListLocked(WindowState win) {
914 int pos = findDesiredInputMethodWindowIndexLocked(true);
915 if (pos >= 0) {
916 win.mTargetAppToken = mInputMethodTarget.mAppToken;
917 mWindows.add(pos, win);
918 moveInputMethodDialogsLocked(pos+1);
919 return;
920 }
921 win.mTargetAppToken = null;
922 addWindowToListInOrderLocked(win, true);
923 moveInputMethodDialogsLocked(pos);
924 }
Romain Guy06882f82009-06-10 13:36:04 -0700925
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800926 void setInputMethodAnimLayerAdjustment(int adj) {
927 if (DEBUG_LAYERS) Log.v(TAG, "Setting im layer adj to " + adj);
928 mInputMethodAnimLayerAdjustment = adj;
929 WindowState imw = mInputMethodWindow;
930 if (imw != null) {
931 imw.mAnimLayer = imw.mLayer + adj;
932 if (DEBUG_LAYERS) Log.v(TAG, "IM win " + imw
933 + " anim layer: " + imw.mAnimLayer);
934 int wi = imw.mChildWindows.size();
935 while (wi > 0) {
936 wi--;
937 WindowState cw = (WindowState)imw.mChildWindows.get(wi);
938 cw.mAnimLayer = cw.mLayer + adj;
939 if (DEBUG_LAYERS) Log.v(TAG, "IM win " + cw
940 + " anim layer: " + cw.mAnimLayer);
941 }
942 }
943 int di = mInputMethodDialogs.size();
944 while (di > 0) {
945 di --;
946 imw = mInputMethodDialogs.get(di);
947 imw.mAnimLayer = imw.mLayer + adj;
948 if (DEBUG_LAYERS) Log.v(TAG, "IM win " + imw
949 + " anim layer: " + imw.mAnimLayer);
950 }
951 }
Romain Guy06882f82009-06-10 13:36:04 -0700952
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800953 private int tmpRemoveWindowLocked(int interestingPos, WindowState win) {
954 int wpos = mWindows.indexOf(win);
955 if (wpos >= 0) {
956 if (wpos < interestingPos) interestingPos--;
957 mWindows.remove(wpos);
958 int NC = win.mChildWindows.size();
959 while (NC > 0) {
960 NC--;
961 WindowState cw = (WindowState)win.mChildWindows.get(NC);
962 int cpos = mWindows.indexOf(cw);
963 if (cpos >= 0) {
964 if (cpos < interestingPos) interestingPos--;
965 mWindows.remove(cpos);
966 }
967 }
968 }
969 return interestingPos;
970 }
Romain Guy06882f82009-06-10 13:36:04 -0700971
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800972 private void reAddWindowToListInOrderLocked(WindowState win) {
973 addWindowToListInOrderLocked(win, false);
974 // This is a hack to get all of the child windows added as well
975 // at the right position. Child windows should be rare and
976 // this case should be rare, so it shouldn't be that big a deal.
977 int wpos = mWindows.indexOf(win);
978 if (wpos >= 0) {
979 mWindows.remove(wpos);
980 reAddWindowLocked(wpos, win);
981 }
982 }
Romain Guy06882f82009-06-10 13:36:04 -0700983
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800984 void logWindowList(String prefix) {
985 int N = mWindows.size();
986 while (N > 0) {
987 N--;
988 Log.v(TAG, prefix + "#" + N + ": " + mWindows.get(N));
989 }
990 }
Romain Guy06882f82009-06-10 13:36:04 -0700991
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800992 void moveInputMethodDialogsLocked(int pos) {
993 ArrayList<WindowState> dialogs = mInputMethodDialogs;
Romain Guy06882f82009-06-10 13:36:04 -0700994
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800995 final int N = dialogs.size();
996 if (DEBUG_INPUT_METHOD) Log.v(TAG, "Removing " + N + " dialogs w/pos=" + pos);
997 for (int i=0; i<N; i++) {
998 pos = tmpRemoveWindowLocked(pos, dialogs.get(i));
999 }
1000 if (DEBUG_INPUT_METHOD) {
1001 Log.v(TAG, "Window list w/pos=" + pos);
1002 logWindowList(" ");
1003 }
Romain Guy06882f82009-06-10 13:36:04 -07001004
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001005 if (pos >= 0) {
1006 final AppWindowToken targetAppToken = mInputMethodTarget.mAppToken;
1007 if (pos < mWindows.size()) {
1008 WindowState wp = (WindowState)mWindows.get(pos);
1009 if (wp == mInputMethodWindow) {
1010 pos++;
1011 }
1012 }
1013 if (DEBUG_INPUT_METHOD) Log.v(TAG, "Adding " + N + " dialogs at pos=" + pos);
1014 for (int i=0; i<N; i++) {
1015 WindowState win = dialogs.get(i);
1016 win.mTargetAppToken = targetAppToken;
1017 pos = reAddWindowLocked(pos, win);
1018 }
1019 if (DEBUG_INPUT_METHOD) {
1020 Log.v(TAG, "Final window list:");
1021 logWindowList(" ");
1022 }
1023 return;
1024 }
1025 for (int i=0; i<N; i++) {
1026 WindowState win = dialogs.get(i);
1027 win.mTargetAppToken = null;
1028 reAddWindowToListInOrderLocked(win);
1029 if (DEBUG_INPUT_METHOD) {
1030 Log.v(TAG, "No IM target, final list:");
1031 logWindowList(" ");
1032 }
1033 }
1034 }
Romain Guy06882f82009-06-10 13:36:04 -07001035
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001036 boolean moveInputMethodWindowsIfNeededLocked(boolean needAssignLayers) {
1037 final WindowState imWin = mInputMethodWindow;
1038 final int DN = mInputMethodDialogs.size();
1039 if (imWin == null && DN == 0) {
1040 return false;
1041 }
Romain Guy06882f82009-06-10 13:36:04 -07001042
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001043 int imPos = findDesiredInputMethodWindowIndexLocked(true);
1044 if (imPos >= 0) {
1045 // In this case, the input method windows are to be placed
1046 // immediately above the window they are targeting.
Romain Guy06882f82009-06-10 13:36:04 -07001047
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001048 // First check to see if the input method windows are already
1049 // located here, and contiguous.
1050 final int N = mWindows.size();
1051 WindowState firstImWin = imPos < N
1052 ? (WindowState)mWindows.get(imPos) : null;
Romain Guy06882f82009-06-10 13:36:04 -07001053
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001054 // Figure out the actual input method window that should be
1055 // at the bottom of their stack.
1056 WindowState baseImWin = imWin != null
1057 ? imWin : mInputMethodDialogs.get(0);
1058 if (baseImWin.mChildWindows.size() > 0) {
1059 WindowState cw = (WindowState)baseImWin.mChildWindows.get(0);
1060 if (cw.mSubLayer < 0) baseImWin = cw;
1061 }
Romain Guy06882f82009-06-10 13:36:04 -07001062
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001063 if (firstImWin == baseImWin) {
1064 // The windows haven't moved... but are they still contiguous?
1065 // First find the top IM window.
1066 int pos = imPos+1;
1067 while (pos < N) {
1068 if (!((WindowState)mWindows.get(pos)).mIsImWindow) {
1069 break;
1070 }
1071 pos++;
1072 }
1073 pos++;
1074 // Now there should be no more input method windows above.
1075 while (pos < N) {
1076 if (((WindowState)mWindows.get(pos)).mIsImWindow) {
1077 break;
1078 }
1079 pos++;
1080 }
1081 if (pos >= N) {
1082 // All is good!
1083 return false;
1084 }
1085 }
Romain Guy06882f82009-06-10 13:36:04 -07001086
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001087 if (imWin != null) {
1088 if (DEBUG_INPUT_METHOD) {
1089 Log.v(TAG, "Moving IM from " + imPos);
1090 logWindowList(" ");
1091 }
1092 imPos = tmpRemoveWindowLocked(imPos, imWin);
1093 if (DEBUG_INPUT_METHOD) {
1094 Log.v(TAG, "List after moving with new pos " + imPos + ":");
1095 logWindowList(" ");
1096 }
1097 imWin.mTargetAppToken = mInputMethodTarget.mAppToken;
1098 reAddWindowLocked(imPos, imWin);
1099 if (DEBUG_INPUT_METHOD) {
1100 Log.v(TAG, "List after moving IM to " + imPos + ":");
1101 logWindowList(" ");
1102 }
1103 if (DN > 0) moveInputMethodDialogsLocked(imPos+1);
1104 } else {
1105 moveInputMethodDialogsLocked(imPos);
1106 }
Romain Guy06882f82009-06-10 13:36:04 -07001107
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001108 } else {
1109 // In this case, the input method windows go in a fixed layer,
1110 // because they aren't currently associated with a focus window.
Romain Guy06882f82009-06-10 13:36:04 -07001111
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001112 if (imWin != null) {
1113 if (DEBUG_INPUT_METHOD) Log.v(TAG, "Moving IM from " + imPos);
1114 tmpRemoveWindowLocked(0, imWin);
1115 imWin.mTargetAppToken = null;
1116 reAddWindowToListInOrderLocked(imWin);
1117 if (DEBUG_INPUT_METHOD) {
1118 Log.v(TAG, "List with no IM target:");
1119 logWindowList(" ");
1120 }
1121 if (DN > 0) moveInputMethodDialogsLocked(-1);;
1122 } else {
1123 moveInputMethodDialogsLocked(-1);;
1124 }
Romain Guy06882f82009-06-10 13:36:04 -07001125
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001126 }
Romain Guy06882f82009-06-10 13:36:04 -07001127
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001128 if (needAssignLayers) {
1129 assignLayersLocked();
1130 }
Romain Guy06882f82009-06-10 13:36:04 -07001131
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001132 return true;
1133 }
Romain Guy06882f82009-06-10 13:36:04 -07001134
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001135 void adjustInputMethodDialogsLocked() {
1136 moveInputMethodDialogsLocked(findDesiredInputMethodWindowIndexLocked(true));
1137 }
Romain Guy06882f82009-06-10 13:36:04 -07001138
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001139 public int addWindow(Session session, IWindow client,
1140 WindowManager.LayoutParams attrs, int viewVisibility,
1141 Rect outContentInsets) {
1142 int res = mPolicy.checkAddPermission(attrs);
1143 if (res != WindowManagerImpl.ADD_OKAY) {
1144 return res;
1145 }
Romain Guy06882f82009-06-10 13:36:04 -07001146
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001147 boolean reportNewConfig = false;
1148 WindowState attachedWindow = null;
1149 WindowState win = null;
Romain Guy06882f82009-06-10 13:36:04 -07001150
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001151 synchronized(mWindowMap) {
1152 // Instantiating a Display requires talking with the simulator,
1153 // so don't do it until we know the system is mostly up and
1154 // running.
1155 if (mDisplay == null) {
1156 WindowManager wm = (WindowManager)mContext.getSystemService(Context.WINDOW_SERVICE);
1157 mDisplay = wm.getDefaultDisplay();
1158 mQueue.setDisplay(mDisplay);
1159 reportNewConfig = true;
1160 }
Romain Guy06882f82009-06-10 13:36:04 -07001161
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001162 if (mWindowMap.containsKey(client.asBinder())) {
1163 Log.w(TAG, "Window " + client + " is already added");
1164 return WindowManagerImpl.ADD_DUPLICATE_ADD;
1165 }
1166
1167 if (attrs.type >= FIRST_SUB_WINDOW && attrs.type <= LAST_SUB_WINDOW) {
Romain Guy06882f82009-06-10 13:36:04 -07001168 attachedWindow = windowForClientLocked(null, attrs.token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001169 if (attachedWindow == null) {
1170 Log.w(TAG, "Attempted to add window with token that is not a window: "
1171 + attrs.token + ". Aborting.");
1172 return WindowManagerImpl.ADD_BAD_SUBWINDOW_TOKEN;
1173 }
1174 if (attachedWindow.mAttrs.type >= FIRST_SUB_WINDOW
1175 && attachedWindow.mAttrs.type <= LAST_SUB_WINDOW) {
1176 Log.w(TAG, "Attempted to add window with token that is a sub-window: "
1177 + attrs.token + ". Aborting.");
1178 return WindowManagerImpl.ADD_BAD_SUBWINDOW_TOKEN;
1179 }
1180 }
1181
1182 boolean addToken = false;
1183 WindowToken token = mTokenMap.get(attrs.token);
1184 if (token == null) {
1185 if (attrs.type >= FIRST_APPLICATION_WINDOW
1186 && attrs.type <= LAST_APPLICATION_WINDOW) {
1187 Log.w(TAG, "Attempted to add application window with unknown token "
1188 + attrs.token + ". Aborting.");
1189 return WindowManagerImpl.ADD_BAD_APP_TOKEN;
1190 }
1191 if (attrs.type == TYPE_INPUT_METHOD) {
1192 Log.w(TAG, "Attempted to add input method window with unknown token "
1193 + attrs.token + ". Aborting.");
1194 return WindowManagerImpl.ADD_BAD_APP_TOKEN;
1195 }
1196 token = new WindowToken(attrs.token, -1, false);
1197 addToken = true;
1198 } else if (attrs.type >= FIRST_APPLICATION_WINDOW
1199 && attrs.type <= LAST_APPLICATION_WINDOW) {
1200 AppWindowToken atoken = token.appWindowToken;
1201 if (atoken == null) {
1202 Log.w(TAG, "Attempted to add window with non-application token "
1203 + token + ". Aborting.");
1204 return WindowManagerImpl.ADD_NOT_APP_TOKEN;
1205 } else if (atoken.removed) {
1206 Log.w(TAG, "Attempted to add window with exiting application token "
1207 + token + ". Aborting.");
1208 return WindowManagerImpl.ADD_APP_EXITING;
1209 }
1210 if (attrs.type == TYPE_APPLICATION_STARTING && atoken.firstWindowDrawn) {
1211 // No need for this guy!
1212 if (localLOGV) Log.v(
1213 TAG, "**** NO NEED TO START: " + attrs.getTitle());
1214 return WindowManagerImpl.ADD_STARTING_NOT_NEEDED;
1215 }
1216 } else if (attrs.type == TYPE_INPUT_METHOD) {
1217 if (token.windowType != TYPE_INPUT_METHOD) {
1218 Log.w(TAG, "Attempted to add input method window with bad token "
1219 + attrs.token + ". Aborting.");
1220 return WindowManagerImpl.ADD_BAD_APP_TOKEN;
1221 }
1222 }
1223
1224 win = new WindowState(session, client, token,
1225 attachedWindow, attrs, viewVisibility);
1226 if (win.mDeathRecipient == null) {
1227 // Client has apparently died, so there is no reason to
1228 // continue.
1229 Log.w(TAG, "Adding window client " + client.asBinder()
1230 + " that is dead, aborting.");
1231 return WindowManagerImpl.ADD_APP_EXITING;
1232 }
1233
1234 mPolicy.adjustWindowParamsLw(win.mAttrs);
Romain Guy06882f82009-06-10 13:36:04 -07001235
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001236 res = mPolicy.prepareAddWindowLw(win, attrs);
1237 if (res != WindowManagerImpl.ADD_OKAY) {
1238 return res;
1239 }
1240
1241 // From now on, no exceptions or errors allowed!
1242
1243 res = WindowManagerImpl.ADD_OKAY;
Romain Guy06882f82009-06-10 13:36:04 -07001244
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001245 final long origId = Binder.clearCallingIdentity();
Romain Guy06882f82009-06-10 13:36:04 -07001246
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001247 if (addToken) {
1248 mTokenMap.put(attrs.token, token);
1249 mTokenList.add(token);
1250 }
1251 win.attach();
1252 mWindowMap.put(client.asBinder(), win);
1253
1254 if (attrs.type == TYPE_APPLICATION_STARTING &&
1255 token.appWindowToken != null) {
1256 token.appWindowToken.startingWindow = win;
1257 }
1258
1259 boolean imMayMove = true;
Romain Guy06882f82009-06-10 13:36:04 -07001260
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001261 if (attrs.type == TYPE_INPUT_METHOD) {
1262 mInputMethodWindow = win;
1263 addInputMethodWindowToListLocked(win);
1264 imMayMove = false;
1265 } else if (attrs.type == TYPE_INPUT_METHOD_DIALOG) {
1266 mInputMethodDialogs.add(win);
1267 addWindowToListInOrderLocked(win, true);
1268 adjustInputMethodDialogsLocked();
1269 imMayMove = false;
1270 } else {
1271 addWindowToListInOrderLocked(win, true);
1272 }
Romain Guy06882f82009-06-10 13:36:04 -07001273
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001274 win.mEnterAnimationPending = true;
Romain Guy06882f82009-06-10 13:36:04 -07001275
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001276 mPolicy.getContentInsetHintLw(attrs, outContentInsets);
Romain Guy06882f82009-06-10 13:36:04 -07001277
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001278 if (mInTouchMode) {
1279 res |= WindowManagerImpl.ADD_FLAG_IN_TOUCH_MODE;
1280 }
1281 if (win == null || win.mAppToken == null || !win.mAppToken.clientHidden) {
1282 res |= WindowManagerImpl.ADD_FLAG_APP_VISIBLE;
1283 }
Romain Guy06882f82009-06-10 13:36:04 -07001284
The Android Open Source Projectc474dec2009-03-04 09:49:09 -08001285 boolean focusChanged = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001286 if (win.canReceiveKeys()) {
The Android Open Source Projectc474dec2009-03-04 09:49:09 -08001287 if ((focusChanged=updateFocusedWindowLocked(UPDATE_FOCUS_WILL_ASSIGN_LAYERS))
1288 == true) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001289 imMayMove = false;
1290 }
1291 }
Romain Guy06882f82009-06-10 13:36:04 -07001292
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001293 if (imMayMove) {
Romain Guy06882f82009-06-10 13:36:04 -07001294 moveInputMethodWindowsIfNeededLocked(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001295 }
Romain Guy06882f82009-06-10 13:36:04 -07001296
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001297 assignLayersLocked();
1298 // Don't do layout here, the window must call
1299 // relayout to be displayed, so we'll do it there.
Romain Guy06882f82009-06-10 13:36:04 -07001300
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001301 //dump();
1302
The Android Open Source Projectc474dec2009-03-04 09:49:09 -08001303 if (focusChanged) {
1304 if (mCurrentFocus != null) {
1305 mKeyWaiter.handleNewWindowLocked(mCurrentFocus);
1306 }
1307 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001308 if (localLOGV) Log.v(
1309 TAG, "New client " + client.asBinder()
1310 + ": window=" + win);
1311 }
1312
1313 // sendNewConfiguration() checks caller permissions so we must call it with
1314 // privilege. updateOrientationFromAppTokens() clears and resets the caller
1315 // identity anyway, so it's safe to just clear & restore around this whole
1316 // block.
1317 final long origId = Binder.clearCallingIdentity();
1318 if (reportNewConfig) {
1319 sendNewConfiguration();
1320 } else {
1321 // Update Orientation after adding a window, only if the window needs to be
1322 // displayed right away
1323 if (win.isVisibleOrAdding()) {
Dianne Hackborncfaef692009-06-15 14:24:44 -07001324 if (updateOrientationFromAppTokensUnchecked(null, null) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001325 sendNewConfiguration();
1326 }
1327 }
1328 }
1329 Binder.restoreCallingIdentity(origId);
Romain Guy06882f82009-06-10 13:36:04 -07001330
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001331 return res;
1332 }
Romain Guy06882f82009-06-10 13:36:04 -07001333
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001334 public void removeWindow(Session session, IWindow client) {
1335 synchronized(mWindowMap) {
1336 WindowState win = windowForClientLocked(session, client);
1337 if (win == null) {
1338 return;
1339 }
1340 removeWindowLocked(session, win);
1341 }
1342 }
Romain Guy06882f82009-06-10 13:36:04 -07001343
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001344 public void removeWindowLocked(Session session, WindowState win) {
1345
1346 if (localLOGV || DEBUG_FOCUS) Log.v(
1347 TAG, "Remove " + win + " client="
1348 + Integer.toHexString(System.identityHashCode(
1349 win.mClient.asBinder()))
1350 + ", surface=" + win.mSurface);
1351
1352 final long origId = Binder.clearCallingIdentity();
Romain Guy06882f82009-06-10 13:36:04 -07001353
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001354 if (DEBUG_APP_TRANSITIONS) Log.v(
1355 TAG, "Remove " + win + ": mSurface=" + win.mSurface
1356 + " mExiting=" + win.mExiting
1357 + " isAnimating=" + win.isAnimating()
1358 + " app-animation="
1359 + (win.mAppToken != null ? win.mAppToken.animation : null)
1360 + " inPendingTransaction="
1361 + (win.mAppToken != null ? win.mAppToken.inPendingTransaction : false)
1362 + " mDisplayFrozen=" + mDisplayFrozen);
1363 // Visibility of the removed window. Will be used later to update orientation later on.
1364 boolean wasVisible = false;
1365 // First, see if we need to run an animation. If we do, we have
1366 // to hold off on removing the window until the animation is done.
1367 // If the display is frozen, just remove immediately, since the
1368 // animation wouldn't be seen.
1369 if (win.mSurface != null && !mDisplayFrozen) {
1370 // If we are not currently running the exit animation, we
1371 // need to see about starting one.
1372 if (wasVisible=win.isWinVisibleLw()) {
Romain Guy06882f82009-06-10 13:36:04 -07001373
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001374 int transit = WindowManagerPolicy.TRANSIT_EXIT;
1375 if (win.getAttrs().type == TYPE_APPLICATION_STARTING) {
1376 transit = WindowManagerPolicy.TRANSIT_PREVIEW_DONE;
1377 }
1378 // Try starting an animation.
1379 if (applyAnimationLocked(win, transit, false)) {
1380 win.mExiting = true;
1381 }
1382 }
1383 if (win.mExiting || win.isAnimating()) {
1384 // The exit animation is running... wait for it!
1385 //Log.i(TAG, "*** Running exit animation...");
1386 win.mExiting = true;
1387 win.mRemoveOnExit = true;
1388 mLayoutNeeded = true;
1389 updateFocusedWindowLocked(UPDATE_FOCUS_WILL_PLACE_SURFACES);
1390 performLayoutAndPlaceSurfacesLocked();
1391 if (win.mAppToken != null) {
1392 win.mAppToken.updateReportedVisibilityLocked();
1393 }
1394 //dump();
1395 Binder.restoreCallingIdentity(origId);
1396 return;
1397 }
1398 }
1399
1400 removeWindowInnerLocked(session, win);
1401 // Removing a visible window will effect the computed orientation
1402 // So just update orientation if needed.
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07001403 if (wasVisible && computeForcedAppOrientationLocked()
1404 != mForcedAppOrientation) {
1405 mH.sendMessage(mH.obtainMessage(H.COMPUTE_AND_SEND_NEW_CONFIGURATION));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001406 }
1407 updateFocusedWindowLocked(UPDATE_FOCUS_NORMAL);
1408 Binder.restoreCallingIdentity(origId);
1409 }
Romain Guy06882f82009-06-10 13:36:04 -07001410
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001411 private void removeWindowInnerLocked(Session session, WindowState win) {
1412 mKeyWaiter.releasePendingPointerLocked(win.mSession);
1413 mKeyWaiter.releasePendingTrackballLocked(win.mSession);
Romain Guy06882f82009-06-10 13:36:04 -07001414
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001415 win.mRemoved = true;
Romain Guy06882f82009-06-10 13:36:04 -07001416
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001417 if (mInputMethodTarget == win) {
1418 moveInputMethodWindowsIfNeededLocked(false);
1419 }
Romain Guy06882f82009-06-10 13:36:04 -07001420
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001421 mPolicy.removeWindowLw(win);
1422 win.removeLocked();
1423
1424 mWindowMap.remove(win.mClient.asBinder());
1425 mWindows.remove(win);
1426
1427 if (mInputMethodWindow == win) {
1428 mInputMethodWindow = null;
1429 } else if (win.mAttrs.type == TYPE_INPUT_METHOD_DIALOG) {
1430 mInputMethodDialogs.remove(win);
1431 }
Romain Guy06882f82009-06-10 13:36:04 -07001432
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001433 final WindowToken token = win.mToken;
1434 final AppWindowToken atoken = win.mAppToken;
1435 token.windows.remove(win);
1436 if (atoken != null) {
1437 atoken.allAppWindows.remove(win);
1438 }
1439 if (localLOGV) Log.v(
1440 TAG, "**** Removing window " + win + ": count="
1441 + token.windows.size());
1442 if (token.windows.size() == 0) {
1443 if (!token.explicit) {
1444 mTokenMap.remove(token.token);
1445 mTokenList.remove(token);
1446 } else if (atoken != null) {
1447 atoken.firstWindowDrawn = false;
1448 }
1449 }
1450
1451 if (atoken != null) {
1452 if (atoken.startingWindow == win) {
1453 atoken.startingWindow = null;
1454 } else if (atoken.allAppWindows.size() == 0 && atoken.startingData != null) {
1455 // If this is the last window and we had requested a starting
1456 // transition window, well there is no point now.
1457 atoken.startingData = null;
1458 } else if (atoken.allAppWindows.size() == 1 && atoken.startingView != null) {
1459 // If this is the last window except for a starting transition
1460 // window, we need to get rid of the starting transition.
1461 if (DEBUG_STARTING_WINDOW) {
1462 Log.v(TAG, "Schedule remove starting " + token
1463 + ": no more real windows");
1464 }
1465 Message m = mH.obtainMessage(H.REMOVE_STARTING, atoken);
1466 mH.sendMessage(m);
1467 }
1468 }
Romain Guy06882f82009-06-10 13:36:04 -07001469
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001470 if (!mInLayout) {
1471 assignLayersLocked();
1472 mLayoutNeeded = true;
1473 performLayoutAndPlaceSurfacesLocked();
1474 if (win.mAppToken != null) {
1475 win.mAppToken.updateReportedVisibilityLocked();
1476 }
1477 }
1478 }
1479
1480 private void setTransparentRegionWindow(Session session, IWindow client, Region region) {
1481 long origId = Binder.clearCallingIdentity();
1482 try {
1483 synchronized (mWindowMap) {
1484 WindowState w = windowForClientLocked(session, client);
1485 if ((w != null) && (w.mSurface != null)) {
1486 Surface.openTransaction();
1487 try {
1488 w.mSurface.setTransparentRegionHint(region);
1489 } finally {
1490 Surface.closeTransaction();
1491 }
1492 }
1493 }
1494 } finally {
1495 Binder.restoreCallingIdentity(origId);
1496 }
1497 }
1498
1499 void setInsetsWindow(Session session, IWindow client,
Romain Guy06882f82009-06-10 13:36:04 -07001500 int touchableInsets, Rect contentInsets,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001501 Rect visibleInsets) {
1502 long origId = Binder.clearCallingIdentity();
1503 try {
1504 synchronized (mWindowMap) {
1505 WindowState w = windowForClientLocked(session, client);
1506 if (w != null) {
1507 w.mGivenInsetsPending = false;
1508 w.mGivenContentInsets.set(contentInsets);
1509 w.mGivenVisibleInsets.set(visibleInsets);
1510 w.mTouchableInsets = touchableInsets;
1511 mLayoutNeeded = true;
1512 performLayoutAndPlaceSurfacesLocked();
1513 }
1514 }
1515 } finally {
1516 Binder.restoreCallingIdentity(origId);
1517 }
1518 }
Romain Guy06882f82009-06-10 13:36:04 -07001519
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001520 public void getWindowDisplayFrame(Session session, IWindow client,
1521 Rect outDisplayFrame) {
1522 synchronized(mWindowMap) {
1523 WindowState win = windowForClientLocked(session, client);
1524 if (win == null) {
1525 outDisplayFrame.setEmpty();
1526 return;
1527 }
1528 outDisplayFrame.set(win.mDisplayFrame);
1529 }
1530 }
1531
1532 public int relayoutWindow(Session session, IWindow client,
1533 WindowManager.LayoutParams attrs, int requestedWidth,
1534 int requestedHeight, int viewVisibility, boolean insetsPending,
1535 Rect outFrame, Rect outContentInsets, Rect outVisibleInsets,
1536 Surface outSurface) {
1537 boolean displayed = false;
1538 boolean inTouchMode;
1539 Configuration newConfig = null;
1540 long origId = Binder.clearCallingIdentity();
Romain Guy06882f82009-06-10 13:36:04 -07001541
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001542 synchronized(mWindowMap) {
1543 WindowState win = windowForClientLocked(session, client);
1544 if (win == null) {
1545 return 0;
1546 }
1547 win.mRequestedWidth = requestedWidth;
1548 win.mRequestedHeight = requestedHeight;
1549
1550 if (attrs != null) {
1551 mPolicy.adjustWindowParamsLw(attrs);
1552 }
Romain Guy06882f82009-06-10 13:36:04 -07001553
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001554 int attrChanges = 0;
1555 int flagChanges = 0;
1556 if (attrs != null) {
1557 flagChanges = win.mAttrs.flags ^= attrs.flags;
1558 attrChanges = win.mAttrs.copyFrom(attrs);
1559 }
1560
1561 if (localLOGV) Log.v(
1562 TAG, "Relayout given client " + client.asBinder()
1563 + " (" + win.mAttrs.getTitle() + ")");
1564
1565
1566 if ((attrChanges & WindowManager.LayoutParams.ALPHA_CHANGED) != 0) {
1567 win.mAlpha = attrs.alpha;
1568 }
1569
1570 final boolean scaledWindow =
1571 ((win.mAttrs.flags & WindowManager.LayoutParams.FLAG_SCALED) != 0);
1572
1573 if (scaledWindow) {
1574 // requested{Width|Height} Surface's physical size
1575 // attrs.{width|height} Size on screen
1576 win.mHScale = (attrs.width != requestedWidth) ?
1577 (attrs.width / (float)requestedWidth) : 1.0f;
1578 win.mVScale = (attrs.height != requestedHeight) ?
1579 (attrs.height / (float)requestedHeight) : 1.0f;
1580 }
1581
1582 boolean imMayMove = (flagChanges&(
1583 WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM |
1584 WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE)) != 0;
Romain Guy06882f82009-06-10 13:36:04 -07001585
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001586 boolean focusMayChange = win.mViewVisibility != viewVisibility
1587 || ((flagChanges&WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE) != 0)
1588 || (!win.mRelayoutCalled);
Romain Guy06882f82009-06-10 13:36:04 -07001589
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001590 win.mRelayoutCalled = true;
1591 final int oldVisibility = win.mViewVisibility;
1592 win.mViewVisibility = viewVisibility;
1593 if (viewVisibility == View.VISIBLE &&
1594 (win.mAppToken == null || !win.mAppToken.clientHidden)) {
1595 displayed = !win.isVisibleLw();
1596 if (win.mExiting) {
1597 win.mExiting = false;
1598 win.mAnimation = null;
1599 }
1600 if (win.mDestroying) {
1601 win.mDestroying = false;
1602 mDestroySurface.remove(win);
1603 }
1604 if (oldVisibility == View.GONE) {
1605 win.mEnterAnimationPending = true;
1606 }
1607 if (displayed && win.mSurface != null && !win.mDrawPending
1608 && !win.mCommitDrawPending && !mDisplayFrozen) {
1609 applyEnterAnimationLocked(win);
1610 }
1611 if ((attrChanges&WindowManager.LayoutParams.FORMAT_CHANGED) != 0) {
1612 // To change the format, we need to re-build the surface.
1613 win.destroySurfaceLocked();
1614 displayed = true;
1615 }
1616 try {
1617 Surface surface = win.createSurfaceLocked();
1618 if (surface != null) {
1619 outSurface.copyFrom(surface);
1620 } else {
1621 outSurface.clear();
1622 }
1623 } catch (Exception e) {
1624 Log.w(TAG, "Exception thrown when creating surface for client "
1625 + client + " (" + win.mAttrs.getTitle() + ")",
1626 e);
1627 Binder.restoreCallingIdentity(origId);
1628 return 0;
1629 }
1630 if (displayed) {
1631 focusMayChange = true;
1632 }
1633 if (win.mAttrs.type == TYPE_INPUT_METHOD
1634 && mInputMethodWindow == null) {
1635 mInputMethodWindow = win;
1636 imMayMove = true;
1637 }
1638 } else {
1639 win.mEnterAnimationPending = false;
1640 if (win.mSurface != null) {
1641 // If we are not currently running the exit animation, we
1642 // need to see about starting one.
1643 if (!win.mExiting) {
1644 // Try starting an animation; if there isn't one, we
1645 // can destroy the surface right away.
1646 int transit = WindowManagerPolicy.TRANSIT_EXIT;
1647 if (win.getAttrs().type == TYPE_APPLICATION_STARTING) {
1648 transit = WindowManagerPolicy.TRANSIT_PREVIEW_DONE;
1649 }
1650 if (win.isWinVisibleLw() &&
1651 applyAnimationLocked(win, transit, false)) {
1652 win.mExiting = true;
1653 mKeyWaiter.finishedKey(session, client, true,
1654 KeyWaiter.RETURN_NOTHING);
1655 } else if (win.isAnimating()) {
1656 // Currently in a hide animation... turn this into
1657 // an exit.
1658 win.mExiting = true;
1659 } else {
1660 if (mInputMethodWindow == win) {
1661 mInputMethodWindow = null;
1662 }
1663 win.destroySurfaceLocked();
1664 }
1665 }
1666 }
1667 outSurface.clear();
1668 }
1669
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001670 if (focusMayChange) {
1671 //System.out.println("Focus may change: " + win.mAttrs.getTitle());
1672 if (updateFocusedWindowLocked(UPDATE_FOCUS_WILL_PLACE_SURFACES)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001673 imMayMove = false;
1674 }
1675 //System.out.println("Relayout " + win + ": focus=" + mCurrentFocus);
1676 }
Romain Guy06882f82009-06-10 13:36:04 -07001677
The Android Open Source Projectc474dec2009-03-04 09:49:09 -08001678 // updateFocusedWindowLocked() already assigned layers so we only need to
1679 // reassign them at this point if the IM window state gets shuffled
1680 boolean assignLayers = false;
Romain Guy06882f82009-06-10 13:36:04 -07001681
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001682 if (imMayMove) {
1683 if (moveInputMethodWindowsIfNeededLocked(false)) {
1684 assignLayers = true;
1685 }
1686 }
Romain Guy06882f82009-06-10 13:36:04 -07001687
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001688 mLayoutNeeded = true;
1689 win.mGivenInsetsPending = insetsPending;
1690 if (assignLayers) {
1691 assignLayersLocked();
1692 }
The Android Open Source Project10592532009-03-18 17:39:46 -07001693 newConfig = updateOrientationFromAppTokensLocked(null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001694 performLayoutAndPlaceSurfacesLocked();
1695 if (win.mAppToken != null) {
1696 win.mAppToken.updateReportedVisibilityLocked();
1697 }
1698 outFrame.set(win.mFrame);
1699 outContentInsets.set(win.mContentInsets);
1700 outVisibleInsets.set(win.mVisibleInsets);
1701 if (localLOGV) Log.v(
1702 TAG, "Relayout given client " + client.asBinder()
Romain Guy06882f82009-06-10 13:36:04 -07001703 + ", requestedWidth=" + requestedWidth
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001704 + ", requestedHeight=" + requestedHeight
1705 + ", viewVisibility=" + viewVisibility
1706 + "\nRelayout returning frame=" + outFrame
1707 + ", surface=" + outSurface);
1708
1709 if (localLOGV || DEBUG_FOCUS) Log.v(
1710 TAG, "Relayout of " + win + ": focusMayChange=" + focusMayChange);
1711
1712 inTouchMode = mInTouchMode;
1713 }
1714
1715 if (newConfig != null) {
1716 sendNewConfiguration();
1717 }
Romain Guy06882f82009-06-10 13:36:04 -07001718
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001719 Binder.restoreCallingIdentity(origId);
Romain Guy06882f82009-06-10 13:36:04 -07001720
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001721 return (inTouchMode ? WindowManagerImpl.RELAYOUT_IN_TOUCH_MODE : 0)
1722 | (displayed ? WindowManagerImpl.RELAYOUT_FIRST_TIME : 0);
1723 }
1724
1725 public void finishDrawingWindow(Session session, IWindow client) {
1726 final long origId = Binder.clearCallingIdentity();
1727 synchronized(mWindowMap) {
1728 WindowState win = windowForClientLocked(session, client);
1729 if (win != null && win.finishDrawingLocked()) {
1730 mLayoutNeeded = true;
1731 performLayoutAndPlaceSurfacesLocked();
1732 }
1733 }
1734 Binder.restoreCallingIdentity(origId);
1735 }
1736
1737 private AttributeCache.Entry getCachedAnimations(WindowManager.LayoutParams lp) {
1738 if (DEBUG_ANIM) Log.v(TAG, "Loading animations: params package="
1739 + (lp != null ? lp.packageName : null)
1740 + " resId=0x" + (lp != null ? Integer.toHexString(lp.windowAnimations) : null));
1741 if (lp != null && lp.windowAnimations != 0) {
1742 // If this is a system resource, don't try to load it from the
1743 // application resources. It is nice to avoid loading application
1744 // resources if we can.
1745 String packageName = lp.packageName != null ? lp.packageName : "android";
1746 int resId = lp.windowAnimations;
1747 if ((resId&0xFF000000) == 0x01000000) {
1748 packageName = "android";
1749 }
1750 if (DEBUG_ANIM) Log.v(TAG, "Loading animations: picked package="
1751 + packageName);
1752 return AttributeCache.instance().get(packageName, resId,
1753 com.android.internal.R.styleable.WindowAnimation);
1754 }
1755 return null;
1756 }
Romain Guy06882f82009-06-10 13:36:04 -07001757
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001758 private void applyEnterAnimationLocked(WindowState win) {
1759 int transit = WindowManagerPolicy.TRANSIT_SHOW;
1760 if (win.mEnterAnimationPending) {
1761 win.mEnterAnimationPending = false;
1762 transit = WindowManagerPolicy.TRANSIT_ENTER;
1763 }
1764
1765 applyAnimationLocked(win, transit, true);
1766 }
1767
1768 private boolean applyAnimationLocked(WindowState win,
1769 int transit, boolean isEntrance) {
1770 if (win.mLocalAnimating && win.mAnimationIsEntrance == isEntrance) {
1771 // If we are trying to apply an animation, but already running
1772 // an animation of the same type, then just leave that one alone.
1773 return true;
1774 }
Romain Guy06882f82009-06-10 13:36:04 -07001775
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001776 // Only apply an animation if the display isn't frozen. If it is
1777 // frozen, there is no reason to animate and it can cause strange
1778 // artifacts when we unfreeze the display if some different animation
1779 // is running.
1780 if (!mDisplayFrozen) {
1781 int anim = mPolicy.selectAnimationLw(win, transit);
1782 int attr = -1;
1783 Animation a = null;
1784 if (anim != 0) {
1785 a = AnimationUtils.loadAnimation(mContext, anim);
1786 } else {
1787 switch (transit) {
1788 case WindowManagerPolicy.TRANSIT_ENTER:
1789 attr = com.android.internal.R.styleable.WindowAnimation_windowEnterAnimation;
1790 break;
1791 case WindowManagerPolicy.TRANSIT_EXIT:
1792 attr = com.android.internal.R.styleable.WindowAnimation_windowExitAnimation;
1793 break;
1794 case WindowManagerPolicy.TRANSIT_SHOW:
1795 attr = com.android.internal.R.styleable.WindowAnimation_windowShowAnimation;
1796 break;
1797 case WindowManagerPolicy.TRANSIT_HIDE:
1798 attr = com.android.internal.R.styleable.WindowAnimation_windowHideAnimation;
1799 break;
1800 }
1801 if (attr >= 0) {
1802 a = loadAnimation(win.mAttrs, attr);
1803 }
1804 }
1805 if (DEBUG_ANIM) Log.v(TAG, "applyAnimation: win=" + win
1806 + " anim=" + anim + " attr=0x" + Integer.toHexString(attr)
1807 + " mAnimation=" + win.mAnimation
1808 + " isEntrance=" + isEntrance);
1809 if (a != null) {
1810 if (DEBUG_ANIM) {
1811 RuntimeException e = new RuntimeException();
1812 e.fillInStackTrace();
1813 Log.v(TAG, "Loaded animation " + a + " for " + win, e);
1814 }
1815 win.setAnimation(a);
1816 win.mAnimationIsEntrance = isEntrance;
1817 }
1818 } else {
1819 win.clearAnimation();
1820 }
1821
1822 return win.mAnimation != null;
1823 }
1824
1825 private Animation loadAnimation(WindowManager.LayoutParams lp, int animAttr) {
1826 int anim = 0;
1827 Context context = mContext;
1828 if (animAttr >= 0) {
1829 AttributeCache.Entry ent = getCachedAnimations(lp);
1830 if (ent != null) {
1831 context = ent.context;
1832 anim = ent.array.getResourceId(animAttr, 0);
1833 }
1834 }
1835 if (anim != 0) {
1836 return AnimationUtils.loadAnimation(context, anim);
1837 }
1838 return null;
1839 }
Romain Guy06882f82009-06-10 13:36:04 -07001840
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001841 private boolean applyAnimationLocked(AppWindowToken wtoken,
1842 WindowManager.LayoutParams lp, int transit, boolean enter) {
1843 // Only apply an animation if the display isn't frozen. If it is
1844 // frozen, there is no reason to animate and it can cause strange
1845 // artifacts when we unfreeze the display if some different animation
1846 // is running.
1847 if (!mDisplayFrozen) {
1848 int animAttr = 0;
1849 switch (transit) {
1850 case WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN:
1851 animAttr = enter
1852 ? com.android.internal.R.styleable.WindowAnimation_activityOpenEnterAnimation
1853 : com.android.internal.R.styleable.WindowAnimation_activityOpenExitAnimation;
1854 break;
1855 case WindowManagerPolicy.TRANSIT_ACTIVITY_CLOSE:
1856 animAttr = enter
1857 ? com.android.internal.R.styleable.WindowAnimation_activityCloseEnterAnimation
1858 : com.android.internal.R.styleable.WindowAnimation_activityCloseExitAnimation;
1859 break;
1860 case WindowManagerPolicy.TRANSIT_TASK_OPEN:
1861 animAttr = enter
1862 ? com.android.internal.R.styleable.WindowAnimation_taskOpenEnterAnimation
1863 : com.android.internal.R.styleable.WindowAnimation_taskOpenExitAnimation;
1864 break;
1865 case WindowManagerPolicy.TRANSIT_TASK_CLOSE:
1866 animAttr = enter
1867 ? com.android.internal.R.styleable.WindowAnimation_taskCloseEnterAnimation
1868 : com.android.internal.R.styleable.WindowAnimation_taskCloseExitAnimation;
1869 break;
1870 case WindowManagerPolicy.TRANSIT_TASK_TO_FRONT:
1871 animAttr = enter
1872 ? com.android.internal.R.styleable.WindowAnimation_taskToFrontEnterAnimation
1873 : com.android.internal.R.styleable.WindowAnimation_taskToFrontExitAnimation;
1874 break;
1875 case WindowManagerPolicy.TRANSIT_TASK_TO_BACK:
1876 animAttr = enter
1877 ? com.android.internal.R.styleable.WindowAnimation_taskToBackEnterAnimation
1878 : com.android.internal.R.styleable.WindowAnimation_taskToBackExitAnimation;
1879 break;
1880 }
1881 Animation a = loadAnimation(lp, animAttr);
1882 if (DEBUG_ANIM) Log.v(TAG, "applyAnimation: wtoken=" + wtoken
1883 + " anim=" + a
1884 + " animAttr=0x" + Integer.toHexString(animAttr)
1885 + " transit=" + transit);
1886 if (a != null) {
1887 if (DEBUG_ANIM) {
1888 RuntimeException e = new RuntimeException();
1889 e.fillInStackTrace();
1890 Log.v(TAG, "Loaded animation " + a + " for " + wtoken, e);
1891 }
1892 wtoken.setAnimation(a);
1893 }
1894 } else {
1895 wtoken.clearAnimation();
1896 }
1897
1898 return wtoken.animation != null;
1899 }
1900
1901 // -------------------------------------------------------------
1902 // Application Window Tokens
1903 // -------------------------------------------------------------
1904
1905 public void validateAppTokens(List tokens) {
1906 int v = tokens.size()-1;
1907 int m = mAppTokens.size()-1;
1908 while (v >= 0 && m >= 0) {
1909 AppWindowToken wtoken = mAppTokens.get(m);
1910 if (wtoken.removed) {
1911 m--;
1912 continue;
1913 }
1914 if (tokens.get(v) != wtoken.token) {
1915 Log.w(TAG, "Tokens out of sync: external is " + tokens.get(v)
1916 + " @ " + v + ", internal is " + wtoken.token + " @ " + m);
1917 }
1918 v--;
1919 m--;
1920 }
1921 while (v >= 0) {
1922 Log.w(TAG, "External token not found: " + tokens.get(v) + " @ " + v);
1923 v--;
1924 }
1925 while (m >= 0) {
1926 AppWindowToken wtoken = mAppTokens.get(m);
1927 if (!wtoken.removed) {
1928 Log.w(TAG, "Invalid internal token: " + wtoken.token + " @ " + m);
1929 }
1930 m--;
1931 }
1932 }
1933
1934 boolean checkCallingPermission(String permission, String func) {
1935 // Quick check: if the calling permission is me, it's all okay.
1936 if (Binder.getCallingPid() == Process.myPid()) {
1937 return true;
1938 }
Romain Guy06882f82009-06-10 13:36:04 -07001939
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001940 if (mContext.checkCallingPermission(permission)
1941 == PackageManager.PERMISSION_GRANTED) {
1942 return true;
1943 }
1944 String msg = "Permission Denial: " + func + " from pid="
1945 + Binder.getCallingPid()
1946 + ", uid=" + Binder.getCallingUid()
1947 + " requires " + permission;
1948 Log.w(TAG, msg);
1949 return false;
1950 }
Romain Guy06882f82009-06-10 13:36:04 -07001951
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001952 AppWindowToken findAppWindowToken(IBinder token) {
1953 WindowToken wtoken = mTokenMap.get(token);
1954 if (wtoken == null) {
1955 return null;
1956 }
1957 return wtoken.appWindowToken;
1958 }
Romain Guy06882f82009-06-10 13:36:04 -07001959
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001960 public void addWindowToken(IBinder token, int type) {
1961 if (!checkCallingPermission(android.Manifest.permission.MANAGE_APP_TOKENS,
1962 "addWindowToken()")) {
Dianne Hackborncfaef692009-06-15 14:24:44 -07001963 throw new SecurityException("Requires MANAGE_APP_TOKENS permission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001964 }
Romain Guy06882f82009-06-10 13:36:04 -07001965
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001966 synchronized(mWindowMap) {
1967 WindowToken wtoken = mTokenMap.get(token);
1968 if (wtoken != null) {
1969 Log.w(TAG, "Attempted to add existing input method token: " + token);
1970 return;
1971 }
1972 wtoken = new WindowToken(token, type, true);
1973 mTokenMap.put(token, wtoken);
1974 mTokenList.add(wtoken);
1975 }
1976 }
Romain Guy06882f82009-06-10 13:36:04 -07001977
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001978 public void removeWindowToken(IBinder token) {
1979 if (!checkCallingPermission(android.Manifest.permission.MANAGE_APP_TOKENS,
1980 "removeWindowToken()")) {
Dianne Hackborncfaef692009-06-15 14:24:44 -07001981 throw new SecurityException("Requires MANAGE_APP_TOKENS permission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001982 }
1983
1984 final long origId = Binder.clearCallingIdentity();
1985 synchronized(mWindowMap) {
1986 WindowToken wtoken = mTokenMap.remove(token);
1987 mTokenList.remove(wtoken);
1988 if (wtoken != null) {
1989 boolean delayed = false;
1990 if (!wtoken.hidden) {
1991 wtoken.hidden = true;
Romain Guy06882f82009-06-10 13:36:04 -07001992
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001993 final int N = wtoken.windows.size();
1994 boolean changed = false;
Romain Guy06882f82009-06-10 13:36:04 -07001995
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001996 for (int i=0; i<N; i++) {
1997 WindowState win = wtoken.windows.get(i);
1998
1999 if (win.isAnimating()) {
2000 delayed = true;
2001 }
Romain Guy06882f82009-06-10 13:36:04 -07002002
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002003 if (win.isVisibleNow()) {
2004 applyAnimationLocked(win,
2005 WindowManagerPolicy.TRANSIT_EXIT, false);
2006 mKeyWaiter.finishedKey(win.mSession, win.mClient, true,
2007 KeyWaiter.RETURN_NOTHING);
2008 changed = true;
2009 }
2010 }
2011
2012 if (changed) {
2013 mLayoutNeeded = true;
2014 performLayoutAndPlaceSurfacesLocked();
2015 updateFocusedWindowLocked(UPDATE_FOCUS_NORMAL);
2016 }
Romain Guy06882f82009-06-10 13:36:04 -07002017
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002018 if (delayed) {
2019 mExitingTokens.add(wtoken);
2020 }
2021 }
Romain Guy06882f82009-06-10 13:36:04 -07002022
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002023 } else {
2024 Log.w(TAG, "Attempted to remove non-existing token: " + token);
2025 }
2026 }
2027 Binder.restoreCallingIdentity(origId);
2028 }
2029
2030 public void addAppToken(int addPos, IApplicationToken token,
2031 int groupId, int requestedOrientation, boolean fullscreen) {
2032 if (!checkCallingPermission(android.Manifest.permission.MANAGE_APP_TOKENS,
2033 "addAppToken()")) {
Dianne Hackborncfaef692009-06-15 14:24:44 -07002034 throw new SecurityException("Requires MANAGE_APP_TOKENS permission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002035 }
Romain Guy06882f82009-06-10 13:36:04 -07002036
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002037 synchronized(mWindowMap) {
2038 AppWindowToken wtoken = findAppWindowToken(token.asBinder());
2039 if (wtoken != null) {
2040 Log.w(TAG, "Attempted to add existing app token: " + token);
2041 return;
2042 }
2043 wtoken = new AppWindowToken(token);
2044 wtoken.groupId = groupId;
2045 wtoken.appFullscreen = fullscreen;
2046 wtoken.requestedOrientation = requestedOrientation;
2047 mAppTokens.add(addPos, wtoken);
Dave Bortcfe65242009-04-09 14:51:04 -07002048 if (localLOGV) Log.v(TAG, "Adding new app token: " + wtoken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002049 mTokenMap.put(token.asBinder(), wtoken);
2050 mTokenList.add(wtoken);
Romain Guy06882f82009-06-10 13:36:04 -07002051
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002052 // Application tokens start out hidden.
2053 wtoken.hidden = true;
2054 wtoken.hiddenRequested = true;
Romain Guy06882f82009-06-10 13:36:04 -07002055
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002056 //dump();
2057 }
2058 }
Romain Guy06882f82009-06-10 13:36:04 -07002059
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002060 public void setAppGroupId(IBinder token, int groupId) {
2061 if (!checkCallingPermission(android.Manifest.permission.MANAGE_APP_TOKENS,
2062 "setAppStartingIcon()")) {
Dianne Hackborncfaef692009-06-15 14:24:44 -07002063 throw new SecurityException("Requires MANAGE_APP_TOKENS permission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002064 }
2065
2066 synchronized(mWindowMap) {
2067 AppWindowToken wtoken = findAppWindowToken(token);
2068 if (wtoken == null) {
2069 Log.w(TAG, "Attempted to set group id of non-existing app token: " + token);
2070 return;
2071 }
2072 wtoken.groupId = groupId;
2073 }
2074 }
Romain Guy06882f82009-06-10 13:36:04 -07002075
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002076 public int getOrientationFromWindowsLocked() {
2077 int pos = mWindows.size() - 1;
2078 while (pos >= 0) {
2079 WindowState wtoken = (WindowState) mWindows.get(pos);
2080 pos--;
2081 if (wtoken.mAppToken != null) {
2082 // We hit an application window. so the orientation will be determined by the
2083 // app window. No point in continuing further.
2084 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
2085 }
2086 if (!wtoken.isVisibleLw()) {
2087 continue;
2088 }
2089 int req = wtoken.mAttrs.screenOrientation;
2090 if((req == ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED) ||
2091 (req == ActivityInfo.SCREEN_ORIENTATION_BEHIND)){
2092 continue;
2093 } else {
2094 return req;
2095 }
2096 }
2097 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
2098 }
Romain Guy06882f82009-06-10 13:36:04 -07002099
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002100 public int getOrientationFromAppTokensLocked() {
2101 int pos = mAppTokens.size() - 1;
2102 int curGroup = 0;
2103 int lastOrientation = ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
Owen Lin3413b892009-05-01 17:12:32 -07002104 boolean findingBehind = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002105 boolean haveGroup = false;
The Android Open Source Project4df24232009-03-05 14:34:35 -08002106 boolean lastFullscreen = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002107 while (pos >= 0) {
2108 AppWindowToken wtoken = mAppTokens.get(pos);
2109 pos--;
Owen Lin3413b892009-05-01 17:12:32 -07002110 // if we're about to tear down this window and not seek for
2111 // the behind activity, don't use it for orientation
2112 if (!findingBehind
2113 && (!wtoken.hidden && wtoken.hiddenRequested)) {
The Android Open Source Project10592532009-03-18 17:39:46 -07002114 continue;
2115 }
2116
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002117 if (!haveGroup) {
2118 // We ignore any hidden applications on the top.
2119 if (wtoken.hiddenRequested || wtoken.willBeHidden) {
2120 continue;
2121 }
2122 haveGroup = true;
2123 curGroup = wtoken.groupId;
2124 lastOrientation = wtoken.requestedOrientation;
2125 } else if (curGroup != wtoken.groupId) {
2126 // If we have hit a new application group, and the bottom
2127 // of the previous group didn't explicitly say to use
The Android Open Source Project4df24232009-03-05 14:34:35 -08002128 // the orientation behind it, and the last app was
2129 // full screen, then we'll stick with the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002130 // user's orientation.
The Android Open Source Project4df24232009-03-05 14:34:35 -08002131 if (lastOrientation != ActivityInfo.SCREEN_ORIENTATION_BEHIND
2132 && lastFullscreen) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002133 return lastOrientation;
2134 }
2135 }
2136 int or = wtoken.requestedOrientation;
Owen Lin3413b892009-05-01 17:12:32 -07002137 // If this application is fullscreen, and didn't explicitly say
2138 // to use the orientation behind it, then just take whatever
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002139 // orientation it has and ignores whatever is under it.
The Android Open Source Project4df24232009-03-05 14:34:35 -08002140 lastFullscreen = wtoken.appFullscreen;
Romain Guy06882f82009-06-10 13:36:04 -07002141 if (lastFullscreen
Owen Lin3413b892009-05-01 17:12:32 -07002142 && or != ActivityInfo.SCREEN_ORIENTATION_BEHIND) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002143 return or;
2144 }
2145 // If this application has requested an explicit orientation,
2146 // then use it.
2147 if (or == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE ||
2148 or == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT ||
2149 or == ActivityInfo.SCREEN_ORIENTATION_SENSOR ||
2150 or == ActivityInfo.SCREEN_ORIENTATION_NOSENSOR ||
2151 or == ActivityInfo.SCREEN_ORIENTATION_USER) {
2152 return or;
2153 }
Owen Lin3413b892009-05-01 17:12:32 -07002154 findingBehind |= (or == ActivityInfo.SCREEN_ORIENTATION_BEHIND);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002155 }
2156 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
2157 }
Romain Guy06882f82009-06-10 13:36:04 -07002158
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002159 public Configuration updateOrientationFromAppTokens(
The Android Open Source Project10592532009-03-18 17:39:46 -07002160 Configuration currentConfig, IBinder freezeThisOneIfNeeded) {
Dianne Hackborncfaef692009-06-15 14:24:44 -07002161 if (!checkCallingPermission(android.Manifest.permission.MANAGE_APP_TOKENS,
2162 "updateOrientationFromAppTokens()")) {
2163 throw new SecurityException("Requires MANAGE_APP_TOKENS permission");
2164 }
2165
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002166 Configuration config;
2167 long ident = Binder.clearCallingIdentity();
Dianne Hackborncfaef692009-06-15 14:24:44 -07002168 config = updateOrientationFromAppTokensUnchecked(currentConfig,
2169 freezeThisOneIfNeeded);
2170 Binder.restoreCallingIdentity(ident);
2171 return config;
2172 }
2173
2174 Configuration updateOrientationFromAppTokensUnchecked(
2175 Configuration currentConfig, IBinder freezeThisOneIfNeeded) {
2176 Configuration config;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002177 synchronized(mWindowMap) {
The Android Open Source Project10592532009-03-18 17:39:46 -07002178 config = updateOrientationFromAppTokensLocked(currentConfig, freezeThisOneIfNeeded);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002179 }
2180 if (config != null) {
2181 mLayoutNeeded = true;
2182 performLayoutAndPlaceSurfacesLocked();
2183 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002184 return config;
2185 }
Romain Guy06882f82009-06-10 13:36:04 -07002186
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002187 /*
2188 * The orientation is computed from non-application windows first. If none of
2189 * the non-application windows specify orientation, the orientation is computed from
Romain Guy06882f82009-06-10 13:36:04 -07002190 * application tokens.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002191 * @see android.view.IWindowManager#updateOrientationFromAppTokens(
2192 * android.os.IBinder)
2193 */
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07002194 Configuration updateOrientationFromAppTokensLocked(
The Android Open Source Project10592532009-03-18 17:39:46 -07002195 Configuration appConfig, IBinder freezeThisOneIfNeeded) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002196 boolean changed = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002197 long ident = Binder.clearCallingIdentity();
2198 try {
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07002199 int req = computeForcedAppOrientationLocked();
Romain Guy06882f82009-06-10 13:36:04 -07002200
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002201 if (req != mForcedAppOrientation) {
2202 changed = true;
2203 mForcedAppOrientation = req;
2204 //send a message to Policy indicating orientation change to take
2205 //action like disabling/enabling sensors etc.,
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07002206 mPolicy.setCurrentOrientationLw(req);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002207 }
Romain Guy06882f82009-06-10 13:36:04 -07002208
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002209 if (changed) {
2210 changed = setRotationUncheckedLocked(
Dianne Hackborn321ae682009-03-27 16:16:03 -07002211 WindowManagerPolicy.USE_LAST_ROTATION,
2212 mLastRotationFlags & (~Surface.FLAGS_ORIENTATION_ANIMATION_DISABLE));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002213 if (changed) {
2214 if (freezeThisOneIfNeeded != null) {
2215 AppWindowToken wtoken = findAppWindowToken(
2216 freezeThisOneIfNeeded);
2217 if (wtoken != null) {
2218 startAppFreezingScreenLocked(wtoken,
2219 ActivityInfo.CONFIG_ORIENTATION);
2220 }
2221 }
Dianne Hackbornc485a602009-03-24 22:39:49 -07002222 return computeNewConfigurationLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002223 }
2224 }
The Android Open Source Project10592532009-03-18 17:39:46 -07002225
2226 // No obvious action we need to take, but if our current
2227 // state mismatches the activity maanager's, update it
2228 if (appConfig != null) {
Dianne Hackbornc485a602009-03-24 22:39:49 -07002229 mTempConfiguration.setToDefaults();
2230 if (computeNewConfigurationLocked(mTempConfiguration)) {
2231 if (appConfig.diff(mTempConfiguration) != 0) {
2232 Log.i(TAG, "Config changed: " + mTempConfiguration);
2233 return new Configuration(mTempConfiguration);
2234 }
The Android Open Source Project10592532009-03-18 17:39:46 -07002235 }
2236 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002237 } finally {
2238 Binder.restoreCallingIdentity(ident);
2239 }
Romain Guy06882f82009-06-10 13:36:04 -07002240
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002241 return null;
2242 }
Romain Guy06882f82009-06-10 13:36:04 -07002243
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07002244 int computeForcedAppOrientationLocked() {
2245 int req = getOrientationFromWindowsLocked();
2246 if (req == ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED) {
2247 req = getOrientationFromAppTokensLocked();
2248 }
2249 return req;
2250 }
Romain Guy06882f82009-06-10 13:36:04 -07002251
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002252 public void setAppOrientation(IApplicationToken token, int requestedOrientation) {
2253 if (!checkCallingPermission(android.Manifest.permission.MANAGE_APP_TOKENS,
2254 "setAppOrientation()")) {
Dianne Hackborncfaef692009-06-15 14:24:44 -07002255 throw new SecurityException("Requires MANAGE_APP_TOKENS permission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002256 }
Romain Guy06882f82009-06-10 13:36:04 -07002257
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002258 synchronized(mWindowMap) {
2259 AppWindowToken wtoken = findAppWindowToken(token.asBinder());
2260 if (wtoken == null) {
2261 Log.w(TAG, "Attempted to set orientation of non-existing app token: " + token);
2262 return;
2263 }
Romain Guy06882f82009-06-10 13:36:04 -07002264
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002265 wtoken.requestedOrientation = requestedOrientation;
2266 }
2267 }
Romain Guy06882f82009-06-10 13:36:04 -07002268
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002269 public int getAppOrientation(IApplicationToken token) {
2270 synchronized(mWindowMap) {
2271 AppWindowToken wtoken = findAppWindowToken(token.asBinder());
2272 if (wtoken == null) {
2273 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
2274 }
Romain Guy06882f82009-06-10 13:36:04 -07002275
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002276 return wtoken.requestedOrientation;
2277 }
2278 }
Romain Guy06882f82009-06-10 13:36:04 -07002279
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002280 public void setFocusedApp(IBinder token, boolean moveFocusNow) {
2281 if (!checkCallingPermission(android.Manifest.permission.MANAGE_APP_TOKENS,
2282 "setFocusedApp()")) {
Dianne Hackborncfaef692009-06-15 14:24:44 -07002283 throw new SecurityException("Requires MANAGE_APP_TOKENS permission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002284 }
2285
2286 synchronized(mWindowMap) {
2287 boolean changed = false;
2288 if (token == null) {
2289 if (DEBUG_FOCUS) Log.v(TAG, "Clearing focused app, was " + mFocusedApp);
2290 changed = mFocusedApp != null;
2291 mFocusedApp = null;
2292 mKeyWaiter.tickle();
2293 } else {
2294 AppWindowToken newFocus = findAppWindowToken(token);
2295 if (newFocus == null) {
2296 Log.w(TAG, "Attempted to set focus to non-existing app token: " + token);
2297 return;
2298 }
2299 changed = mFocusedApp != newFocus;
2300 mFocusedApp = newFocus;
2301 if (DEBUG_FOCUS) Log.v(TAG, "Set focused app to: " + mFocusedApp);
2302 mKeyWaiter.tickle();
2303 }
2304
2305 if (moveFocusNow && changed) {
2306 final long origId = Binder.clearCallingIdentity();
2307 updateFocusedWindowLocked(UPDATE_FOCUS_NORMAL);
2308 Binder.restoreCallingIdentity(origId);
2309 }
2310 }
2311 }
2312
2313 public void prepareAppTransition(int transit) {
2314 if (!checkCallingPermission(android.Manifest.permission.MANAGE_APP_TOKENS,
2315 "prepareAppTransition()")) {
Dianne Hackborncfaef692009-06-15 14:24:44 -07002316 throw new SecurityException("Requires MANAGE_APP_TOKENS permission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002317 }
Romain Guy06882f82009-06-10 13:36:04 -07002318
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002319 synchronized(mWindowMap) {
2320 if (DEBUG_APP_TRANSITIONS) Log.v(
2321 TAG, "Prepare app transition: transit=" + transit
2322 + " mNextAppTransition=" + mNextAppTransition);
2323 if (!mDisplayFrozen) {
2324 if (mNextAppTransition == WindowManagerPolicy.TRANSIT_NONE) {
2325 mNextAppTransition = transit;
2326 }
2327 mAppTransitionReady = false;
2328 mAppTransitionTimeout = false;
2329 mStartingIconInTransition = false;
2330 mSkipAppTransitionAnimation = false;
2331 mH.removeMessages(H.APP_TRANSITION_TIMEOUT);
2332 mH.sendMessageDelayed(mH.obtainMessage(H.APP_TRANSITION_TIMEOUT),
2333 5000);
2334 }
2335 }
2336 }
2337
2338 public int getPendingAppTransition() {
2339 return mNextAppTransition;
2340 }
Romain Guy06882f82009-06-10 13:36:04 -07002341
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002342 public void executeAppTransition() {
2343 if (!checkCallingPermission(android.Manifest.permission.MANAGE_APP_TOKENS,
2344 "executeAppTransition()")) {
Dianne Hackborncfaef692009-06-15 14:24:44 -07002345 throw new SecurityException("Requires MANAGE_APP_TOKENS permission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002346 }
Romain Guy06882f82009-06-10 13:36:04 -07002347
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002348 synchronized(mWindowMap) {
2349 if (DEBUG_APP_TRANSITIONS) Log.v(
2350 TAG, "Execute app transition: mNextAppTransition=" + mNextAppTransition);
2351 if (mNextAppTransition != WindowManagerPolicy.TRANSIT_NONE) {
2352 mAppTransitionReady = true;
2353 final long origId = Binder.clearCallingIdentity();
2354 performLayoutAndPlaceSurfacesLocked();
2355 Binder.restoreCallingIdentity(origId);
2356 }
2357 }
2358 }
2359
2360 public void setAppStartingWindow(IBinder token, String pkg,
2361 int theme, CharSequence nonLocalizedLabel, int labelRes, int icon,
2362 IBinder transferFrom, boolean createIfNeeded) {
2363 if (!checkCallingPermission(android.Manifest.permission.MANAGE_APP_TOKENS,
2364 "setAppStartingIcon()")) {
Dianne Hackborncfaef692009-06-15 14:24:44 -07002365 throw new SecurityException("Requires MANAGE_APP_TOKENS permission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002366 }
2367
2368 synchronized(mWindowMap) {
2369 if (DEBUG_STARTING_WINDOW) Log.v(
2370 TAG, "setAppStartingIcon: token=" + token + " pkg=" + pkg
2371 + " transferFrom=" + transferFrom);
Romain Guy06882f82009-06-10 13:36:04 -07002372
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002373 AppWindowToken wtoken = findAppWindowToken(token);
2374 if (wtoken == null) {
2375 Log.w(TAG, "Attempted to set icon of non-existing app token: " + token);
2376 return;
2377 }
2378
2379 // If the display is frozen, we won't do anything until the
2380 // actual window is displayed so there is no reason to put in
2381 // the starting window.
2382 if (mDisplayFrozen) {
2383 return;
2384 }
Romain Guy06882f82009-06-10 13:36:04 -07002385
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002386 if (wtoken.startingData != null) {
2387 return;
2388 }
Romain Guy06882f82009-06-10 13:36:04 -07002389
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002390 if (transferFrom != null) {
2391 AppWindowToken ttoken = findAppWindowToken(transferFrom);
2392 if (ttoken != null) {
2393 WindowState startingWindow = ttoken.startingWindow;
2394 if (startingWindow != null) {
2395 if (mStartingIconInTransition) {
2396 // In this case, the starting icon has already
2397 // been displayed, so start letting windows get
2398 // shown immediately without any more transitions.
2399 mSkipAppTransitionAnimation = true;
2400 }
2401 if (DEBUG_STARTING_WINDOW) Log.v(TAG,
2402 "Moving existing starting from " + ttoken
2403 + " to " + wtoken);
2404 final long origId = Binder.clearCallingIdentity();
Romain Guy06882f82009-06-10 13:36:04 -07002405
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002406 // Transfer the starting window over to the new
2407 // token.
2408 wtoken.startingData = ttoken.startingData;
2409 wtoken.startingView = ttoken.startingView;
2410 wtoken.startingWindow = startingWindow;
2411 ttoken.startingData = null;
2412 ttoken.startingView = null;
2413 ttoken.startingWindow = null;
2414 ttoken.startingMoved = true;
2415 startingWindow.mToken = wtoken;
Dianne Hackbornef49c572009-03-24 19:27:32 -07002416 startingWindow.mRootToken = wtoken;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002417 startingWindow.mAppToken = wtoken;
2418 mWindows.remove(startingWindow);
2419 ttoken.windows.remove(startingWindow);
2420 ttoken.allAppWindows.remove(startingWindow);
2421 addWindowToListInOrderLocked(startingWindow, true);
2422 wtoken.allAppWindows.add(startingWindow);
Romain Guy06882f82009-06-10 13:36:04 -07002423
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002424 // Propagate other interesting state between the
2425 // tokens. If the old token is displayed, we should
2426 // immediately force the new one to be displayed. If
2427 // it is animating, we need to move that animation to
2428 // the new one.
2429 if (ttoken.allDrawn) {
2430 wtoken.allDrawn = true;
2431 }
2432 if (ttoken.firstWindowDrawn) {
2433 wtoken.firstWindowDrawn = true;
2434 }
2435 if (!ttoken.hidden) {
2436 wtoken.hidden = false;
2437 wtoken.hiddenRequested = false;
2438 wtoken.willBeHidden = false;
2439 }
2440 if (wtoken.clientHidden != ttoken.clientHidden) {
2441 wtoken.clientHidden = ttoken.clientHidden;
2442 wtoken.sendAppVisibilityToClients();
2443 }
2444 if (ttoken.animation != null) {
2445 wtoken.animation = ttoken.animation;
2446 wtoken.animating = ttoken.animating;
2447 wtoken.animLayerAdjustment = ttoken.animLayerAdjustment;
2448 ttoken.animation = null;
2449 ttoken.animLayerAdjustment = 0;
2450 wtoken.updateLayers();
2451 ttoken.updateLayers();
2452 }
Romain Guy06882f82009-06-10 13:36:04 -07002453
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002454 updateFocusedWindowLocked(UPDATE_FOCUS_WILL_PLACE_SURFACES);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002455 mLayoutNeeded = true;
2456 performLayoutAndPlaceSurfacesLocked();
2457 Binder.restoreCallingIdentity(origId);
2458 return;
2459 } else if (ttoken.startingData != null) {
2460 // The previous app was getting ready to show a
2461 // starting window, but hasn't yet done so. Steal it!
2462 if (DEBUG_STARTING_WINDOW) Log.v(TAG,
2463 "Moving pending starting from " + ttoken
2464 + " to " + wtoken);
2465 wtoken.startingData = ttoken.startingData;
2466 ttoken.startingData = null;
2467 ttoken.startingMoved = true;
2468 Message m = mH.obtainMessage(H.ADD_STARTING, wtoken);
2469 // Note: we really want to do sendMessageAtFrontOfQueue() because we
2470 // want to process the message ASAP, before any other queued
2471 // messages.
2472 mH.sendMessageAtFrontOfQueue(m);
2473 return;
2474 }
2475 }
2476 }
2477
2478 // There is no existing starting window, and the caller doesn't
2479 // want us to create one, so that's it!
2480 if (!createIfNeeded) {
2481 return;
2482 }
Romain Guy06882f82009-06-10 13:36:04 -07002483
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002484 mStartingIconInTransition = true;
2485 wtoken.startingData = new StartingData(
2486 pkg, theme, nonLocalizedLabel,
2487 labelRes, icon);
2488 Message m = mH.obtainMessage(H.ADD_STARTING, wtoken);
2489 // Note: we really want to do sendMessageAtFrontOfQueue() because we
2490 // want to process the message ASAP, before any other queued
2491 // messages.
2492 mH.sendMessageAtFrontOfQueue(m);
2493 }
2494 }
2495
2496 public void setAppWillBeHidden(IBinder token) {
2497 if (!checkCallingPermission(android.Manifest.permission.MANAGE_APP_TOKENS,
2498 "setAppWillBeHidden()")) {
Dianne Hackborncfaef692009-06-15 14:24:44 -07002499 throw new SecurityException("Requires MANAGE_APP_TOKENS permission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002500 }
2501
2502 AppWindowToken wtoken;
2503
2504 synchronized(mWindowMap) {
2505 wtoken = findAppWindowToken(token);
2506 if (wtoken == null) {
2507 Log.w(TAG, "Attempted to set will be hidden of non-existing app token: " + token);
2508 return;
2509 }
2510 wtoken.willBeHidden = true;
2511 }
2512 }
Romain Guy06882f82009-06-10 13:36:04 -07002513
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002514 boolean setTokenVisibilityLocked(AppWindowToken wtoken, WindowManager.LayoutParams lp,
2515 boolean visible, int transit, boolean performLayout) {
2516 boolean delayed = false;
2517
2518 if (wtoken.clientHidden == visible) {
2519 wtoken.clientHidden = !visible;
2520 wtoken.sendAppVisibilityToClients();
2521 }
Romain Guy06882f82009-06-10 13:36:04 -07002522
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002523 wtoken.willBeHidden = false;
2524 if (wtoken.hidden == visible) {
2525 final int N = wtoken.allAppWindows.size();
2526 boolean changed = false;
2527 if (DEBUG_APP_TRANSITIONS) Log.v(
2528 TAG, "Changing app " + wtoken + " hidden=" + wtoken.hidden
2529 + " performLayout=" + performLayout);
Romain Guy06882f82009-06-10 13:36:04 -07002530
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002531 boolean runningAppAnimation = false;
Romain Guy06882f82009-06-10 13:36:04 -07002532
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002533 if (transit != WindowManagerPolicy.TRANSIT_NONE) {
2534 if (wtoken.animation == sDummyAnimation) {
2535 wtoken.animation = null;
2536 }
2537 applyAnimationLocked(wtoken, lp, transit, visible);
2538 changed = true;
2539 if (wtoken.animation != null) {
2540 delayed = runningAppAnimation = true;
2541 }
2542 }
Romain Guy06882f82009-06-10 13:36:04 -07002543
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002544 for (int i=0; i<N; i++) {
2545 WindowState win = wtoken.allAppWindows.get(i);
2546 if (win == wtoken.startingWindow) {
2547 continue;
2548 }
2549
2550 if (win.isAnimating()) {
2551 delayed = true;
2552 }
Romain Guy06882f82009-06-10 13:36:04 -07002553
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002554 //Log.i(TAG, "Window " + win + ": vis=" + win.isVisible());
2555 //win.dump(" ");
2556 if (visible) {
2557 if (!win.isVisibleNow()) {
2558 if (!runningAppAnimation) {
2559 applyAnimationLocked(win,
2560 WindowManagerPolicy.TRANSIT_ENTER, true);
2561 }
2562 changed = true;
2563 }
2564 } else if (win.isVisibleNow()) {
2565 if (!runningAppAnimation) {
2566 applyAnimationLocked(win,
2567 WindowManagerPolicy.TRANSIT_EXIT, false);
2568 }
2569 mKeyWaiter.finishedKey(win.mSession, win.mClient, true,
2570 KeyWaiter.RETURN_NOTHING);
2571 changed = true;
2572 }
2573 }
2574
2575 wtoken.hidden = wtoken.hiddenRequested = !visible;
2576 if (!visible) {
2577 unsetAppFreezingScreenLocked(wtoken, true, true);
2578 } else {
2579 // If we are being set visible, and the starting window is
2580 // not yet displayed, then make sure it doesn't get displayed.
2581 WindowState swin = wtoken.startingWindow;
2582 if (swin != null && (swin.mDrawPending
2583 || swin.mCommitDrawPending)) {
2584 swin.mPolicyVisibility = false;
2585 swin.mPolicyVisibilityAfterAnim = false;
2586 }
2587 }
Romain Guy06882f82009-06-10 13:36:04 -07002588
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002589 if (DEBUG_APP_TRANSITIONS) Log.v(TAG, "setTokenVisibilityLocked: " + wtoken
2590 + ": hidden=" + wtoken.hidden + " hiddenRequested="
2591 + wtoken.hiddenRequested);
Romain Guy06882f82009-06-10 13:36:04 -07002592
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002593 if (changed && performLayout) {
2594 mLayoutNeeded = true;
2595 updateFocusedWindowLocked(UPDATE_FOCUS_WILL_PLACE_SURFACES);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002596 performLayoutAndPlaceSurfacesLocked();
2597 }
2598 }
2599
2600 if (wtoken.animation != null) {
2601 delayed = true;
2602 }
Romain Guy06882f82009-06-10 13:36:04 -07002603
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002604 return delayed;
2605 }
2606
2607 public void setAppVisibility(IBinder token, boolean visible) {
2608 if (!checkCallingPermission(android.Manifest.permission.MANAGE_APP_TOKENS,
2609 "setAppVisibility()")) {
Dianne Hackborncfaef692009-06-15 14:24:44 -07002610 throw new SecurityException("Requires MANAGE_APP_TOKENS permission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002611 }
2612
2613 AppWindowToken wtoken;
2614
2615 synchronized(mWindowMap) {
2616 wtoken = findAppWindowToken(token);
2617 if (wtoken == null) {
2618 Log.w(TAG, "Attempted to set visibility of non-existing app token: " + token);
2619 return;
2620 }
2621
2622 if (DEBUG_APP_TRANSITIONS || DEBUG_ORIENTATION) {
2623 RuntimeException e = new RuntimeException();
2624 e.fillInStackTrace();
2625 Log.v(TAG, "setAppVisibility(" + token + ", " + visible
2626 + "): mNextAppTransition=" + mNextAppTransition
2627 + " hidden=" + wtoken.hidden
2628 + " hiddenRequested=" + wtoken.hiddenRequested, e);
2629 }
Romain Guy06882f82009-06-10 13:36:04 -07002630
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002631 // If we are preparing an app transition, then delay changing
2632 // the visibility of this token until we execute that transition.
2633 if (!mDisplayFrozen && mNextAppTransition != WindowManagerPolicy.TRANSIT_NONE) {
2634 // Already in requested state, don't do anything more.
2635 if (wtoken.hiddenRequested != visible) {
2636 return;
2637 }
2638 wtoken.hiddenRequested = !visible;
Romain Guy06882f82009-06-10 13:36:04 -07002639
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002640 if (DEBUG_APP_TRANSITIONS) Log.v(
2641 TAG, "Setting dummy animation on: " + wtoken);
2642 wtoken.setDummyAnimation();
2643 mOpeningApps.remove(wtoken);
2644 mClosingApps.remove(wtoken);
2645 wtoken.inPendingTransaction = true;
2646 if (visible) {
2647 mOpeningApps.add(wtoken);
2648 wtoken.allDrawn = false;
2649 wtoken.startingDisplayed = false;
2650 wtoken.startingMoved = false;
Romain Guy06882f82009-06-10 13:36:04 -07002651
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002652 if (wtoken.clientHidden) {
2653 // In the case where we are making an app visible
2654 // but holding off for a transition, we still need
2655 // to tell the client to make its windows visible so
2656 // they get drawn. Otherwise, we will wait on
2657 // performing the transition until all windows have
2658 // been drawn, they never will be, and we are sad.
2659 wtoken.clientHidden = false;
2660 wtoken.sendAppVisibilityToClients();
2661 }
2662 } else {
2663 mClosingApps.add(wtoken);
2664 }
2665 return;
2666 }
Romain Guy06882f82009-06-10 13:36:04 -07002667
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002668 final long origId = Binder.clearCallingIdentity();
2669 setTokenVisibilityLocked(wtoken, null, visible, WindowManagerPolicy.TRANSIT_NONE, true);
2670 wtoken.updateReportedVisibilityLocked();
2671 Binder.restoreCallingIdentity(origId);
2672 }
2673 }
2674
2675 void unsetAppFreezingScreenLocked(AppWindowToken wtoken,
2676 boolean unfreezeSurfaceNow, boolean force) {
2677 if (wtoken.freezingScreen) {
2678 if (DEBUG_ORIENTATION) Log.v(TAG, "Clear freezing of " + wtoken
2679 + " force=" + force);
2680 final int N = wtoken.allAppWindows.size();
2681 boolean unfrozeWindows = false;
2682 for (int i=0; i<N; i++) {
2683 WindowState w = wtoken.allAppWindows.get(i);
2684 if (w.mAppFreezing) {
2685 w.mAppFreezing = false;
2686 if (w.mSurface != null && !w.mOrientationChanging) {
2687 w.mOrientationChanging = true;
2688 }
2689 unfrozeWindows = true;
2690 }
2691 }
2692 if (force || unfrozeWindows) {
2693 if (DEBUG_ORIENTATION) Log.v(TAG, "No longer freezing: " + wtoken);
2694 wtoken.freezingScreen = false;
2695 mAppsFreezingScreen--;
2696 }
2697 if (unfreezeSurfaceNow) {
2698 if (unfrozeWindows) {
2699 mLayoutNeeded = true;
2700 performLayoutAndPlaceSurfacesLocked();
2701 }
2702 if (mAppsFreezingScreen == 0 && !mWindowsFreezingScreen) {
2703 stopFreezingDisplayLocked();
2704 }
2705 }
2706 }
2707 }
Romain Guy06882f82009-06-10 13:36:04 -07002708
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002709 public void startAppFreezingScreenLocked(AppWindowToken wtoken,
2710 int configChanges) {
2711 if (DEBUG_ORIENTATION) {
2712 RuntimeException e = new RuntimeException();
2713 e.fillInStackTrace();
2714 Log.i(TAG, "Set freezing of " + wtoken.appToken
2715 + ": hidden=" + wtoken.hidden + " freezing="
2716 + wtoken.freezingScreen, e);
2717 }
2718 if (!wtoken.hiddenRequested) {
2719 if (!wtoken.freezingScreen) {
2720 wtoken.freezingScreen = true;
2721 mAppsFreezingScreen++;
2722 if (mAppsFreezingScreen == 1) {
2723 startFreezingDisplayLocked();
2724 mH.removeMessages(H.APP_FREEZE_TIMEOUT);
2725 mH.sendMessageDelayed(mH.obtainMessage(H.APP_FREEZE_TIMEOUT),
2726 5000);
2727 }
2728 }
2729 final int N = wtoken.allAppWindows.size();
2730 for (int i=0; i<N; i++) {
2731 WindowState w = wtoken.allAppWindows.get(i);
2732 w.mAppFreezing = true;
2733 }
2734 }
2735 }
Romain Guy06882f82009-06-10 13:36:04 -07002736
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002737 public void startAppFreezingScreen(IBinder token, int configChanges) {
2738 if (!checkCallingPermission(android.Manifest.permission.MANAGE_APP_TOKENS,
2739 "setAppFreezingScreen()")) {
Dianne Hackborncfaef692009-06-15 14:24:44 -07002740 throw new SecurityException("Requires MANAGE_APP_TOKENS permission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002741 }
2742
2743 synchronized(mWindowMap) {
2744 if (configChanges == 0 && !mDisplayFrozen) {
2745 if (DEBUG_ORIENTATION) Log.v(TAG, "Skipping set freeze of " + token);
2746 return;
2747 }
Romain Guy06882f82009-06-10 13:36:04 -07002748
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002749 AppWindowToken wtoken = findAppWindowToken(token);
2750 if (wtoken == null || wtoken.appToken == null) {
2751 Log.w(TAG, "Attempted to freeze screen with non-existing app token: " + wtoken);
2752 return;
2753 }
2754 final long origId = Binder.clearCallingIdentity();
2755 startAppFreezingScreenLocked(wtoken, configChanges);
2756 Binder.restoreCallingIdentity(origId);
2757 }
2758 }
Romain Guy06882f82009-06-10 13:36:04 -07002759
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002760 public void stopAppFreezingScreen(IBinder token, boolean force) {
2761 if (!checkCallingPermission(android.Manifest.permission.MANAGE_APP_TOKENS,
2762 "setAppFreezingScreen()")) {
Dianne Hackborncfaef692009-06-15 14:24:44 -07002763 throw new SecurityException("Requires MANAGE_APP_TOKENS permission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002764 }
2765
2766 synchronized(mWindowMap) {
2767 AppWindowToken wtoken = findAppWindowToken(token);
2768 if (wtoken == null || wtoken.appToken == null) {
2769 return;
2770 }
2771 final long origId = Binder.clearCallingIdentity();
2772 if (DEBUG_ORIENTATION) Log.v(TAG, "Clear freezing of " + token
2773 + ": hidden=" + wtoken.hidden + " freezing=" + wtoken.freezingScreen);
2774 unsetAppFreezingScreenLocked(wtoken, true, force);
2775 Binder.restoreCallingIdentity(origId);
2776 }
2777 }
Romain Guy06882f82009-06-10 13:36:04 -07002778
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002779 public void removeAppToken(IBinder token) {
2780 if (!checkCallingPermission(android.Manifest.permission.MANAGE_APP_TOKENS,
2781 "removeAppToken()")) {
Dianne Hackborncfaef692009-06-15 14:24:44 -07002782 throw new SecurityException("Requires MANAGE_APP_TOKENS permission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002783 }
2784
2785 AppWindowToken wtoken = null;
2786 AppWindowToken startingToken = null;
2787 boolean delayed = false;
2788
2789 final long origId = Binder.clearCallingIdentity();
2790 synchronized(mWindowMap) {
2791 WindowToken basewtoken = mTokenMap.remove(token);
2792 mTokenList.remove(basewtoken);
2793 if (basewtoken != null && (wtoken=basewtoken.appWindowToken) != null) {
2794 if (DEBUG_APP_TRANSITIONS) Log.v(TAG, "Removing app token: " + wtoken);
2795 delayed = setTokenVisibilityLocked(wtoken, null, false, WindowManagerPolicy.TRANSIT_NONE, true);
2796 wtoken.inPendingTransaction = false;
2797 mOpeningApps.remove(wtoken);
2798 if (mClosingApps.contains(wtoken)) {
2799 delayed = true;
2800 } else if (mNextAppTransition != WindowManagerPolicy.TRANSIT_NONE) {
2801 mClosingApps.add(wtoken);
2802 delayed = true;
2803 }
2804 if (DEBUG_APP_TRANSITIONS) Log.v(
2805 TAG, "Removing app " + wtoken + " delayed=" + delayed
2806 + " animation=" + wtoken.animation
2807 + " animating=" + wtoken.animating);
2808 if (delayed) {
2809 // set the token aside because it has an active animation to be finished
2810 mExitingAppTokens.add(wtoken);
2811 }
2812 mAppTokens.remove(wtoken);
2813 wtoken.removed = true;
2814 if (wtoken.startingData != null) {
2815 startingToken = wtoken;
2816 }
2817 unsetAppFreezingScreenLocked(wtoken, true, true);
2818 if (mFocusedApp == wtoken) {
2819 if (DEBUG_FOCUS) Log.v(TAG, "Removing focused app token:" + wtoken);
2820 mFocusedApp = null;
2821 updateFocusedWindowLocked(UPDATE_FOCUS_NORMAL);
2822 mKeyWaiter.tickle();
2823 }
2824 } else {
2825 Log.w(TAG, "Attempted to remove non-existing app token: " + token);
2826 }
Romain Guy06882f82009-06-10 13:36:04 -07002827
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002828 if (!delayed && wtoken != null) {
2829 wtoken.updateReportedVisibilityLocked();
2830 }
2831 }
2832 Binder.restoreCallingIdentity(origId);
2833
2834 if (startingToken != null) {
2835 if (DEBUG_STARTING_WINDOW) Log.v(TAG, "Schedule remove starting "
2836 + startingToken + ": app token removed");
2837 Message m = mH.obtainMessage(H.REMOVE_STARTING, startingToken);
2838 mH.sendMessage(m);
2839 }
2840 }
2841
2842 private boolean tmpRemoveAppWindowsLocked(WindowToken token) {
2843 final int NW = token.windows.size();
2844 for (int i=0; i<NW; i++) {
2845 WindowState win = token.windows.get(i);
2846 mWindows.remove(win);
2847 int j = win.mChildWindows.size();
2848 while (j > 0) {
2849 j--;
2850 mWindows.remove(win.mChildWindows.get(j));
2851 }
2852 }
2853 return NW > 0;
2854 }
2855
2856 void dumpAppTokensLocked() {
2857 for (int i=mAppTokens.size()-1; i>=0; i--) {
2858 Log.v(TAG, " #" + i + ": " + mAppTokens.get(i).token);
2859 }
2860 }
Romain Guy06882f82009-06-10 13:36:04 -07002861
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002862 void dumpWindowsLocked() {
2863 for (int i=mWindows.size()-1; i>=0; i--) {
2864 Log.v(TAG, " #" + i + ": " + mWindows.get(i));
2865 }
2866 }
Romain Guy06882f82009-06-10 13:36:04 -07002867
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002868 private int findWindowOffsetLocked(int tokenPos) {
2869 final int NW = mWindows.size();
2870
2871 if (tokenPos >= mAppTokens.size()) {
2872 int i = NW;
2873 while (i > 0) {
2874 i--;
2875 WindowState win = (WindowState)mWindows.get(i);
2876 if (win.getAppToken() != null) {
2877 return i+1;
2878 }
2879 }
2880 }
2881
2882 while (tokenPos > 0) {
2883 // Find the first app token below the new position that has
2884 // a window displayed.
2885 final AppWindowToken wtoken = mAppTokens.get(tokenPos-1);
2886 if (DEBUG_REORDER) Log.v(TAG, "Looking for lower windows @ "
2887 + tokenPos + " -- " + wtoken.token);
2888 int i = wtoken.windows.size();
2889 while (i > 0) {
2890 i--;
2891 WindowState win = wtoken.windows.get(i);
2892 int j = win.mChildWindows.size();
2893 while (j > 0) {
2894 j--;
2895 WindowState cwin = (WindowState)win.mChildWindows.get(j);
2896 if (cwin.mSubLayer >= 0 ) {
2897 for (int pos=NW-1; pos>=0; pos--) {
2898 if (mWindows.get(pos) == cwin) {
2899 if (DEBUG_REORDER) Log.v(TAG,
2900 "Found child win @" + (pos+1));
2901 return pos+1;
2902 }
2903 }
2904 }
2905 }
2906 for (int pos=NW-1; pos>=0; pos--) {
2907 if (mWindows.get(pos) == win) {
2908 if (DEBUG_REORDER) Log.v(TAG, "Found win @" + (pos+1));
2909 return pos+1;
2910 }
2911 }
2912 }
2913 tokenPos--;
2914 }
2915
2916 return 0;
2917 }
2918
2919 private final int reAddWindowLocked(int index, WindowState win) {
2920 final int NCW = win.mChildWindows.size();
2921 boolean added = false;
2922 for (int j=0; j<NCW; j++) {
2923 WindowState cwin = (WindowState)win.mChildWindows.get(j);
2924 if (!added && cwin.mSubLayer >= 0) {
2925 mWindows.add(index, win);
2926 index++;
2927 added = true;
2928 }
2929 mWindows.add(index, cwin);
2930 index++;
2931 }
2932 if (!added) {
2933 mWindows.add(index, win);
2934 index++;
2935 }
2936 return index;
2937 }
Romain Guy06882f82009-06-10 13:36:04 -07002938
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002939 private final int reAddAppWindowsLocked(int index, WindowToken token) {
2940 final int NW = token.windows.size();
2941 for (int i=0; i<NW; i++) {
2942 index = reAddWindowLocked(index, token.windows.get(i));
2943 }
2944 return index;
2945 }
2946
2947 public void moveAppToken(int index, IBinder token) {
2948 if (!checkCallingPermission(android.Manifest.permission.MANAGE_APP_TOKENS,
2949 "moveAppToken()")) {
Dianne Hackborncfaef692009-06-15 14:24:44 -07002950 throw new SecurityException("Requires MANAGE_APP_TOKENS permission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002951 }
2952
2953 synchronized(mWindowMap) {
2954 if (DEBUG_REORDER) Log.v(TAG, "Initial app tokens:");
2955 if (DEBUG_REORDER) dumpAppTokensLocked();
2956 final AppWindowToken wtoken = findAppWindowToken(token);
2957 if (wtoken == null || !mAppTokens.remove(wtoken)) {
2958 Log.w(TAG, "Attempting to reorder token that doesn't exist: "
2959 + token + " (" + wtoken + ")");
2960 return;
2961 }
2962 mAppTokens.add(index, wtoken);
2963 if (DEBUG_REORDER) Log.v(TAG, "Moved " + token + " to " + index + ":");
2964 if (DEBUG_REORDER) dumpAppTokensLocked();
Romain Guy06882f82009-06-10 13:36:04 -07002965
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002966 final long origId = Binder.clearCallingIdentity();
2967 if (DEBUG_REORDER) Log.v(TAG, "Removing windows in " + token + ":");
2968 if (DEBUG_REORDER) dumpWindowsLocked();
2969 if (tmpRemoveAppWindowsLocked(wtoken)) {
2970 if (DEBUG_REORDER) Log.v(TAG, "Adding windows back in:");
2971 if (DEBUG_REORDER) dumpWindowsLocked();
2972 reAddAppWindowsLocked(findWindowOffsetLocked(index), wtoken);
2973 if (DEBUG_REORDER) Log.v(TAG, "Final window list:");
2974 if (DEBUG_REORDER) dumpWindowsLocked();
2975 updateFocusedWindowLocked(UPDATE_FOCUS_WILL_PLACE_SURFACES);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002976 mLayoutNeeded = true;
2977 performLayoutAndPlaceSurfacesLocked();
2978 }
2979 Binder.restoreCallingIdentity(origId);
2980 }
2981 }
2982
2983 private void removeAppTokensLocked(List<IBinder> tokens) {
2984 // XXX This should be done more efficiently!
2985 // (take advantage of the fact that both lists should be
2986 // ordered in the same way.)
2987 int N = tokens.size();
2988 for (int i=0; i<N; i++) {
2989 IBinder token = tokens.get(i);
2990 final AppWindowToken wtoken = findAppWindowToken(token);
2991 if (!mAppTokens.remove(wtoken)) {
2992 Log.w(TAG, "Attempting to reorder token that doesn't exist: "
2993 + token + " (" + wtoken + ")");
2994 i--;
2995 N--;
2996 }
2997 }
2998 }
2999
3000 private void moveAppWindowsLocked(List<IBinder> tokens, int tokenPos) {
3001 // First remove all of the windows from the list.
3002 final int N = tokens.size();
3003 int i;
3004 for (i=0; i<N; i++) {
3005 WindowToken token = mTokenMap.get(tokens.get(i));
3006 if (token != null) {
3007 tmpRemoveAppWindowsLocked(token);
3008 }
3009 }
3010
3011 // Where to start adding?
3012 int pos = findWindowOffsetLocked(tokenPos);
3013
3014 // And now add them back at the correct place.
3015 for (i=0; i<N; i++) {
3016 WindowToken token = mTokenMap.get(tokens.get(i));
3017 if (token != null) {
3018 pos = reAddAppWindowsLocked(pos, token);
3019 }
3020 }
3021
3022 updateFocusedWindowLocked(UPDATE_FOCUS_WILL_PLACE_SURFACES);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003023 mLayoutNeeded = true;
3024 performLayoutAndPlaceSurfacesLocked();
3025
3026 //dump();
3027 }
3028
3029 public void moveAppTokensToTop(List<IBinder> tokens) {
3030 if (!checkCallingPermission(android.Manifest.permission.MANAGE_APP_TOKENS,
3031 "moveAppTokensToTop()")) {
Dianne Hackborncfaef692009-06-15 14:24:44 -07003032 throw new SecurityException("Requires MANAGE_APP_TOKENS permission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003033 }
3034
3035 final long origId = Binder.clearCallingIdentity();
3036 synchronized(mWindowMap) {
3037 removeAppTokensLocked(tokens);
3038 final int N = tokens.size();
3039 for (int i=0; i<N; i++) {
3040 AppWindowToken wt = findAppWindowToken(tokens.get(i));
3041 if (wt != null) {
3042 mAppTokens.add(wt);
3043 }
3044 }
3045 moveAppWindowsLocked(tokens, mAppTokens.size());
3046 }
3047 Binder.restoreCallingIdentity(origId);
3048 }
3049
3050 public void moveAppTokensToBottom(List<IBinder> tokens) {
3051 if (!checkCallingPermission(android.Manifest.permission.MANAGE_APP_TOKENS,
3052 "moveAppTokensToBottom()")) {
Dianne Hackborncfaef692009-06-15 14:24:44 -07003053 throw new SecurityException("Requires MANAGE_APP_TOKENS permission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003054 }
3055
3056 final long origId = Binder.clearCallingIdentity();
3057 synchronized(mWindowMap) {
3058 removeAppTokensLocked(tokens);
3059 final int N = tokens.size();
3060 int pos = 0;
3061 for (int i=0; i<N; i++) {
3062 AppWindowToken wt = findAppWindowToken(tokens.get(i));
3063 if (wt != null) {
3064 mAppTokens.add(pos, wt);
3065 pos++;
3066 }
3067 }
3068 moveAppWindowsLocked(tokens, 0);
3069 }
3070 Binder.restoreCallingIdentity(origId);
3071 }
3072
3073 // -------------------------------------------------------------
3074 // Misc IWindowSession methods
3075 // -------------------------------------------------------------
Romain Guy06882f82009-06-10 13:36:04 -07003076
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003077 public void disableKeyguard(IBinder token, String tag) {
3078 if (mContext.checkCallingPermission(android.Manifest.permission.DISABLE_KEYGUARD)
3079 != PackageManager.PERMISSION_GRANTED) {
3080 throw new SecurityException("Requires DISABLE_KEYGUARD permission");
3081 }
3082 mKeyguardDisabled.acquire(token, tag);
3083 }
3084
3085 public void reenableKeyguard(IBinder token) {
3086 if (mContext.checkCallingPermission(android.Manifest.permission.DISABLE_KEYGUARD)
3087 != PackageManager.PERMISSION_GRANTED) {
3088 throw new SecurityException("Requires DISABLE_KEYGUARD permission");
3089 }
3090 synchronized (mKeyguardDisabled) {
3091 mKeyguardDisabled.release(token);
3092
3093 if (!mKeyguardDisabled.isAcquired()) {
3094 // if we are the last one to reenable the keyguard wait until
3095 // we have actaully finished reenabling until returning
3096 mWaitingUntilKeyguardReenabled = true;
3097 while (mWaitingUntilKeyguardReenabled) {
3098 try {
3099 mKeyguardDisabled.wait();
3100 } catch (InterruptedException e) {
3101 Thread.currentThread().interrupt();
3102 }
3103 }
3104 }
3105 }
3106 }
3107
3108 /**
3109 * @see android.app.KeyguardManager#exitKeyguardSecurely
3110 */
3111 public void exitKeyguardSecurely(final IOnKeyguardExitResult callback) {
3112 if (mContext.checkCallingPermission(android.Manifest.permission.DISABLE_KEYGUARD)
3113 != PackageManager.PERMISSION_GRANTED) {
3114 throw new SecurityException("Requires DISABLE_KEYGUARD permission");
3115 }
3116 mPolicy.exitKeyguardSecurely(new WindowManagerPolicy.OnKeyguardExitResult() {
3117 public void onKeyguardExitResult(boolean success) {
3118 try {
3119 callback.onKeyguardExitResult(success);
3120 } catch (RemoteException e) {
3121 // Client has died, we don't care.
3122 }
3123 }
3124 });
3125 }
3126
3127 public boolean inKeyguardRestrictedInputMode() {
3128 return mPolicy.inKeyguardRestrictedKeyInputMode();
3129 }
Romain Guy06882f82009-06-10 13:36:04 -07003130
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003131 static float fixScale(float scale) {
3132 if (scale < 0) scale = 0;
3133 else if (scale > 20) scale = 20;
3134 return Math.abs(scale);
3135 }
Romain Guy06882f82009-06-10 13:36:04 -07003136
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003137 public void setAnimationScale(int which, float scale) {
3138 if (!checkCallingPermission(android.Manifest.permission.SET_ANIMATION_SCALE,
3139 "setAnimationScale()")) {
Dianne Hackborncfaef692009-06-15 14:24:44 -07003140 throw new SecurityException("Requires SET_ANIMATION_SCALE permission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003141 }
3142
3143 if (scale < 0) scale = 0;
3144 else if (scale > 20) scale = 20;
3145 scale = Math.abs(scale);
3146 switch (which) {
3147 case 0: mWindowAnimationScale = fixScale(scale); break;
3148 case 1: mTransitionAnimationScale = fixScale(scale); break;
3149 }
Romain Guy06882f82009-06-10 13:36:04 -07003150
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003151 // Persist setting
3152 mH.obtainMessage(H.PERSIST_ANIMATION_SCALE).sendToTarget();
3153 }
Romain Guy06882f82009-06-10 13:36:04 -07003154
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003155 public void setAnimationScales(float[] scales) {
3156 if (!checkCallingPermission(android.Manifest.permission.SET_ANIMATION_SCALE,
3157 "setAnimationScale()")) {
Dianne Hackborncfaef692009-06-15 14:24:44 -07003158 throw new SecurityException("Requires SET_ANIMATION_SCALE permission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003159 }
3160
3161 if (scales != null) {
3162 if (scales.length >= 1) {
3163 mWindowAnimationScale = fixScale(scales[0]);
3164 }
3165 if (scales.length >= 2) {
3166 mTransitionAnimationScale = fixScale(scales[1]);
3167 }
3168 }
Romain Guy06882f82009-06-10 13:36:04 -07003169
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003170 // Persist setting
3171 mH.obtainMessage(H.PERSIST_ANIMATION_SCALE).sendToTarget();
3172 }
Romain Guy06882f82009-06-10 13:36:04 -07003173
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003174 public float getAnimationScale(int which) {
3175 switch (which) {
3176 case 0: return mWindowAnimationScale;
3177 case 1: return mTransitionAnimationScale;
3178 }
3179 return 0;
3180 }
Romain Guy06882f82009-06-10 13:36:04 -07003181
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003182 public float[] getAnimationScales() {
3183 return new float[] { mWindowAnimationScale, mTransitionAnimationScale };
3184 }
Romain Guy06882f82009-06-10 13:36:04 -07003185
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003186 public int getSwitchState(int sw) {
3187 if (!checkCallingPermission(android.Manifest.permission.READ_INPUT_STATE,
3188 "getSwitchState()")) {
Dianne Hackborncfaef692009-06-15 14:24:44 -07003189 throw new SecurityException("Requires READ_INPUT_STATE permission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003190 }
3191 return KeyInputQueue.getSwitchState(sw);
3192 }
Romain Guy06882f82009-06-10 13:36:04 -07003193
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003194 public int getSwitchStateForDevice(int devid, int sw) {
3195 if (!checkCallingPermission(android.Manifest.permission.READ_INPUT_STATE,
3196 "getSwitchStateForDevice()")) {
Dianne Hackborncfaef692009-06-15 14:24:44 -07003197 throw new SecurityException("Requires READ_INPUT_STATE permission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003198 }
3199 return KeyInputQueue.getSwitchState(devid, sw);
3200 }
Romain Guy06882f82009-06-10 13:36:04 -07003201
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003202 public int getScancodeState(int sw) {
3203 if (!checkCallingPermission(android.Manifest.permission.READ_INPUT_STATE,
3204 "getScancodeState()")) {
Dianne Hackborncfaef692009-06-15 14:24:44 -07003205 throw new SecurityException("Requires READ_INPUT_STATE permission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003206 }
3207 return KeyInputQueue.getScancodeState(sw);
3208 }
Romain Guy06882f82009-06-10 13:36:04 -07003209
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003210 public int getScancodeStateForDevice(int devid, int sw) {
3211 if (!checkCallingPermission(android.Manifest.permission.READ_INPUT_STATE,
3212 "getScancodeStateForDevice()")) {
Dianne Hackborncfaef692009-06-15 14:24:44 -07003213 throw new SecurityException("Requires READ_INPUT_STATE permission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003214 }
3215 return KeyInputQueue.getScancodeState(devid, sw);
3216 }
Romain Guy06882f82009-06-10 13:36:04 -07003217
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003218 public int getKeycodeState(int sw) {
3219 if (!checkCallingPermission(android.Manifest.permission.READ_INPUT_STATE,
3220 "getKeycodeState()")) {
Dianne Hackborncfaef692009-06-15 14:24:44 -07003221 throw new SecurityException("Requires READ_INPUT_STATE permission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003222 }
3223 return KeyInputQueue.getKeycodeState(sw);
3224 }
Romain Guy06882f82009-06-10 13:36:04 -07003225
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003226 public int getKeycodeStateForDevice(int devid, int sw) {
3227 if (!checkCallingPermission(android.Manifest.permission.READ_INPUT_STATE,
3228 "getKeycodeStateForDevice()")) {
Dianne Hackborncfaef692009-06-15 14:24:44 -07003229 throw new SecurityException("Requires READ_INPUT_STATE permission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003230 }
3231 return KeyInputQueue.getKeycodeState(devid, sw);
3232 }
Romain Guy06882f82009-06-10 13:36:04 -07003233
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003234 public boolean hasKeys(int[] keycodes, boolean[] keyExists) {
3235 return KeyInputQueue.hasKeys(keycodes, keyExists);
3236 }
Romain Guy06882f82009-06-10 13:36:04 -07003237
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003238 public void enableScreenAfterBoot() {
3239 synchronized(mWindowMap) {
3240 if (mSystemBooted) {
3241 return;
3242 }
3243 mSystemBooted = true;
3244 }
Romain Guy06882f82009-06-10 13:36:04 -07003245
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003246 performEnableScreen();
3247 }
Romain Guy06882f82009-06-10 13:36:04 -07003248
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003249 public void enableScreenIfNeededLocked() {
3250 if (mDisplayEnabled) {
3251 return;
3252 }
3253 if (!mSystemBooted) {
3254 return;
3255 }
3256 mH.sendMessage(mH.obtainMessage(H.ENABLE_SCREEN));
3257 }
Romain Guy06882f82009-06-10 13:36:04 -07003258
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003259 public void performEnableScreen() {
3260 synchronized(mWindowMap) {
3261 if (mDisplayEnabled) {
3262 return;
3263 }
3264 if (!mSystemBooted) {
3265 return;
3266 }
Romain Guy06882f82009-06-10 13:36:04 -07003267
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003268 // Don't enable the screen until all existing windows
3269 // have been drawn.
3270 final int N = mWindows.size();
3271 for (int i=0; i<N; i++) {
3272 WindowState w = (WindowState)mWindows.get(i);
3273 if (w.isVisibleLw() && !w.isDisplayedLw()) {
3274 return;
3275 }
3276 }
Romain Guy06882f82009-06-10 13:36:04 -07003277
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003278 mDisplayEnabled = true;
3279 if (false) {
3280 Log.i(TAG, "ENABLING SCREEN!");
3281 StringWriter sw = new StringWriter();
3282 PrintWriter pw = new PrintWriter(sw);
3283 this.dump(null, pw, null);
3284 Log.i(TAG, sw.toString());
3285 }
3286 try {
3287 IBinder surfaceFlinger = ServiceManager.getService("SurfaceFlinger");
3288 if (surfaceFlinger != null) {
3289 //Log.i(TAG, "******* TELLING SURFACE FLINGER WE ARE BOOTED!");
3290 Parcel data = Parcel.obtain();
3291 data.writeInterfaceToken("android.ui.ISurfaceComposer");
3292 surfaceFlinger.transact(IBinder.FIRST_CALL_TRANSACTION,
3293 data, null, 0);
3294 data.recycle();
3295 }
3296 } catch (RemoteException ex) {
3297 Log.e(TAG, "Boot completed: SurfaceFlinger is dead!");
3298 }
3299 }
Romain Guy06882f82009-06-10 13:36:04 -07003300
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003301 mPolicy.enableScreenAfterBoot();
Romain Guy06882f82009-06-10 13:36:04 -07003302
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003303 // Make sure the last requested orientation has been applied.
Dianne Hackborn321ae682009-03-27 16:16:03 -07003304 setRotationUnchecked(WindowManagerPolicy.USE_LAST_ROTATION, false,
3305 mLastRotationFlags | Surface.FLAGS_ORIENTATION_ANIMATION_DISABLE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003306 }
Romain Guy06882f82009-06-10 13:36:04 -07003307
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003308 public void setInTouchMode(boolean mode) {
3309 synchronized(mWindowMap) {
3310 mInTouchMode = mode;
3311 }
3312 }
3313
Romain Guy06882f82009-06-10 13:36:04 -07003314 public void setRotation(int rotation,
Dianne Hackborn1e880db2009-03-27 16:04:08 -07003315 boolean alwaysSendConfiguration, int animFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003316 if (!checkCallingPermission(android.Manifest.permission.SET_ORIENTATION,
Dianne Hackborn1e880db2009-03-27 16:04:08 -07003317 "setRotation()")) {
Dianne Hackborncfaef692009-06-15 14:24:44 -07003318 throw new SecurityException("Requires SET_ORIENTATION permission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003319 }
3320
Dianne Hackborn1e880db2009-03-27 16:04:08 -07003321 setRotationUnchecked(rotation, alwaysSendConfiguration, animFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003322 }
Romain Guy06882f82009-06-10 13:36:04 -07003323
Dianne Hackborn1e880db2009-03-27 16:04:08 -07003324 public void setRotationUnchecked(int rotation,
3325 boolean alwaysSendConfiguration, int animFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003326 if(DEBUG_ORIENTATION) Log.v(TAG,
3327 "alwaysSendConfiguration set to "+alwaysSendConfiguration);
Romain Guy06882f82009-06-10 13:36:04 -07003328
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003329 long origId = Binder.clearCallingIdentity();
3330 boolean changed;
3331 synchronized(mWindowMap) {
Dianne Hackborn1e880db2009-03-27 16:04:08 -07003332 changed = setRotationUncheckedLocked(rotation, animFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003333 }
Romain Guy06882f82009-06-10 13:36:04 -07003334
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003335 if (changed) {
3336 sendNewConfiguration();
3337 synchronized(mWindowMap) {
3338 mLayoutNeeded = true;
3339 performLayoutAndPlaceSurfacesLocked();
3340 }
3341 } else if (alwaysSendConfiguration) {
3342 //update configuration ignoring orientation change
3343 sendNewConfiguration();
3344 }
Romain Guy06882f82009-06-10 13:36:04 -07003345
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003346 Binder.restoreCallingIdentity(origId);
3347 }
Romain Guy06882f82009-06-10 13:36:04 -07003348
Dianne Hackborn1e880db2009-03-27 16:04:08 -07003349 public boolean setRotationUncheckedLocked(int rotation, int animFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003350 boolean changed;
3351 if (rotation == WindowManagerPolicy.USE_LAST_ROTATION) {
3352 rotation = mRequestedRotation;
3353 } else {
3354 mRequestedRotation = rotation;
Dianne Hackborn321ae682009-03-27 16:16:03 -07003355 mLastRotationFlags = animFlags;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003356 }
3357 if (DEBUG_ORIENTATION) Log.v(TAG, "Overwriting rotation value from " + rotation);
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07003358 rotation = mPolicy.rotationForOrientationLw(mForcedAppOrientation,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003359 mRotation, mDisplayEnabled);
3360 if (DEBUG_ORIENTATION) Log.v(TAG, "new rotation is set to " + rotation);
3361 changed = mDisplayEnabled && mRotation != rotation;
Romain Guy06882f82009-06-10 13:36:04 -07003362
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003363 if (changed) {
Romain Guy06882f82009-06-10 13:36:04 -07003364 if (DEBUG_ORIENTATION) Log.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003365 "Rotation changed to " + rotation
3366 + " from " + mRotation
3367 + " (forceApp=" + mForcedAppOrientation
3368 + ", req=" + mRequestedRotation + ")");
3369 mRotation = rotation;
3370 mWindowsFreezingScreen = true;
3371 mH.removeMessages(H.WINDOW_FREEZE_TIMEOUT);
3372 mH.sendMessageDelayed(mH.obtainMessage(H.WINDOW_FREEZE_TIMEOUT),
3373 2000);
3374 startFreezingDisplayLocked();
Dianne Hackborn1e880db2009-03-27 16:04:08 -07003375 Log.i(TAG, "Setting rotation to " + rotation + ", animFlags=" + animFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003376 mQueue.setOrientation(rotation);
3377 if (mDisplayEnabled) {
Dianne Hackborn321ae682009-03-27 16:16:03 -07003378 Surface.setOrientation(0, rotation, animFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003379 }
3380 for (int i=mWindows.size()-1; i>=0; i--) {
3381 WindowState w = (WindowState)mWindows.get(i);
3382 if (w.mSurface != null) {
3383 w.mOrientationChanging = true;
3384 }
3385 }
3386 for (int i=mRotationWatchers.size()-1; i>=0; i--) {
3387 try {
3388 mRotationWatchers.get(i).onRotationChanged(rotation);
3389 } catch (RemoteException e) {
3390 }
3391 }
3392 } //end if changed
Romain Guy06882f82009-06-10 13:36:04 -07003393
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003394 return changed;
3395 }
Romain Guy06882f82009-06-10 13:36:04 -07003396
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003397 public int getRotation() {
3398 return mRotation;
3399 }
3400
3401 public int watchRotation(IRotationWatcher watcher) {
3402 final IBinder watcherBinder = watcher.asBinder();
3403 IBinder.DeathRecipient dr = new IBinder.DeathRecipient() {
3404 public void binderDied() {
3405 synchronized (mWindowMap) {
3406 for (int i=0; i<mRotationWatchers.size(); i++) {
3407 if (watcherBinder == mRotationWatchers.get(i).asBinder()) {
3408 mRotationWatchers.remove(i);
3409 i--;
3410 }
3411 }
3412 }
3413 }
3414 };
Romain Guy06882f82009-06-10 13:36:04 -07003415
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003416 synchronized (mWindowMap) {
3417 try {
3418 watcher.asBinder().linkToDeath(dr, 0);
3419 mRotationWatchers.add(watcher);
3420 } catch (RemoteException e) {
3421 // Client died, no cleanup needed.
3422 }
Romain Guy06882f82009-06-10 13:36:04 -07003423
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003424 return mRotation;
3425 }
3426 }
3427
3428 /**
3429 * Starts the view server on the specified port.
3430 *
3431 * @param port The port to listener to.
3432 *
3433 * @return True if the server was successfully started, false otherwise.
3434 *
3435 * @see com.android.server.ViewServer
3436 * @see com.android.server.ViewServer#VIEW_SERVER_DEFAULT_PORT
3437 */
3438 public boolean startViewServer(int port) {
Romain Guy06882f82009-06-10 13:36:04 -07003439 if (isSystemSecure()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003440 return false;
3441 }
3442
3443 if (!checkCallingPermission(Manifest.permission.DUMP, "startViewServer")) {
3444 return false;
3445 }
3446
3447 if (port < 1024) {
3448 return false;
3449 }
3450
3451 if (mViewServer != null) {
3452 if (!mViewServer.isRunning()) {
3453 try {
3454 return mViewServer.start();
3455 } catch (IOException e) {
Romain Guy06882f82009-06-10 13:36:04 -07003456 Log.w(TAG, "View server did not start");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003457 }
3458 }
3459 return false;
3460 }
3461
3462 try {
3463 mViewServer = new ViewServer(this, port);
3464 return mViewServer.start();
3465 } catch (IOException e) {
3466 Log.w(TAG, "View server did not start");
3467 }
3468 return false;
3469 }
3470
Romain Guy06882f82009-06-10 13:36:04 -07003471 private boolean isSystemSecure() {
3472 return "1".equals(SystemProperties.get(SYSTEM_SECURE, "1")) &&
3473 "0".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
3474 }
3475
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003476 /**
3477 * Stops the view server if it exists.
3478 *
3479 * @return True if the server stopped, false if it wasn't started or
3480 * couldn't be stopped.
3481 *
3482 * @see com.android.server.ViewServer
3483 */
3484 public boolean stopViewServer() {
Romain Guy06882f82009-06-10 13:36:04 -07003485 if (isSystemSecure()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003486 return false;
3487 }
3488
3489 if (!checkCallingPermission(Manifest.permission.DUMP, "stopViewServer")) {
3490 return false;
3491 }
3492
3493 if (mViewServer != null) {
3494 return mViewServer.stop();
3495 }
3496 return false;
3497 }
3498
3499 /**
3500 * Indicates whether the view server is running.
3501 *
3502 * @return True if the server is running, false otherwise.
3503 *
3504 * @see com.android.server.ViewServer
3505 */
3506 public boolean isViewServerRunning() {
Romain Guy06882f82009-06-10 13:36:04 -07003507 if (isSystemSecure()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003508 return false;
3509 }
3510
3511 if (!checkCallingPermission(Manifest.permission.DUMP, "isViewServerRunning")) {
3512 return false;
3513 }
3514
3515 return mViewServer != null && mViewServer.isRunning();
3516 }
3517
3518 /**
3519 * Lists all availble windows in the system. The listing is written in the
3520 * specified Socket's output stream with the following syntax:
3521 * windowHashCodeInHexadecimal windowName
3522 * Each line of the ouput represents a different window.
3523 *
3524 * @param client The remote client to send the listing to.
3525 * @return False if an error occured, true otherwise.
3526 */
3527 boolean viewServerListWindows(Socket client) {
Romain Guy06882f82009-06-10 13:36:04 -07003528 if (isSystemSecure()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003529 return false;
3530 }
3531
3532 boolean result = true;
3533
3534 Object[] windows;
3535 synchronized (mWindowMap) {
3536 windows = new Object[mWindows.size()];
3537 //noinspection unchecked
3538 windows = mWindows.toArray(windows);
3539 }
3540
3541 BufferedWriter out = null;
3542
3543 // Any uncaught exception will crash the system process
3544 try {
3545 OutputStream clientStream = client.getOutputStream();
3546 out = new BufferedWriter(new OutputStreamWriter(clientStream), 8 * 1024);
3547
3548 final int count = windows.length;
3549 for (int i = 0; i < count; i++) {
3550 final WindowState w = (WindowState) windows[i];
3551 out.write(Integer.toHexString(System.identityHashCode(w)));
3552 out.write(' ');
3553 out.append(w.mAttrs.getTitle());
3554 out.write('\n');
3555 }
3556
3557 out.write("DONE.\n");
3558 out.flush();
3559 } catch (Exception e) {
3560 result = false;
3561 } finally {
3562 if (out != null) {
3563 try {
3564 out.close();
3565 } catch (IOException e) {
3566 result = false;
3567 }
3568 }
3569 }
3570
3571 return result;
3572 }
3573
3574 /**
3575 * Sends a command to a target window. The result of the command, if any, will be
3576 * written in the output stream of the specified socket.
3577 *
3578 * The parameters must follow this syntax:
3579 * windowHashcode extra
3580 *
3581 * Where XX is the length in characeters of the windowTitle.
3582 *
3583 * The first parameter is the target window. The window with the specified hashcode
3584 * will be the target. If no target can be found, nothing happens. The extra parameters
3585 * will be delivered to the target window and as parameters to the command itself.
3586 *
3587 * @param client The remote client to sent the result, if any, to.
3588 * @param command The command to execute.
3589 * @param parameters The command parameters.
3590 *
3591 * @return True if the command was successfully delivered, false otherwise. This does
3592 * not indicate whether the command itself was successful.
3593 */
3594 boolean viewServerWindowCommand(Socket client, String command, String parameters) {
Romain Guy06882f82009-06-10 13:36:04 -07003595 if (isSystemSecure()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003596 return false;
3597 }
3598
3599 boolean success = true;
3600 Parcel data = null;
3601 Parcel reply = null;
3602
3603 // Any uncaught exception will crash the system process
3604 try {
3605 // Find the hashcode of the window
3606 int index = parameters.indexOf(' ');
3607 if (index == -1) {
3608 index = parameters.length();
3609 }
3610 final String code = parameters.substring(0, index);
3611 int hashCode = "ffffffff".equals(code) ? -1 : Integer.parseInt(code, 16);
3612
3613 // Extract the command's parameter after the window description
3614 if (index < parameters.length()) {
3615 parameters = parameters.substring(index + 1);
3616 } else {
3617 parameters = "";
3618 }
3619
3620 final WindowManagerService.WindowState window = findWindow(hashCode);
3621 if (window == null) {
3622 return false;
3623 }
3624
3625 data = Parcel.obtain();
3626 data.writeInterfaceToken("android.view.IWindow");
3627 data.writeString(command);
3628 data.writeString(parameters);
3629 data.writeInt(1);
3630 ParcelFileDescriptor.fromSocket(client).writeToParcel(data, 0);
3631
3632 reply = Parcel.obtain();
3633
3634 final IBinder binder = window.mClient.asBinder();
3635 // TODO: GET THE TRANSACTION CODE IN A SAFER MANNER
3636 binder.transact(IBinder.FIRST_CALL_TRANSACTION, data, reply, 0);
3637
3638 reply.readException();
3639
3640 } catch (Exception e) {
3641 Log.w(TAG, "Could not send command " + command + " with parameters " + parameters, e);
3642 success = false;
3643 } finally {
3644 if (data != null) {
3645 data.recycle();
3646 }
3647 if (reply != null) {
3648 reply.recycle();
3649 }
3650 }
3651
3652 return success;
3653 }
3654
3655 private WindowState findWindow(int hashCode) {
3656 if (hashCode == -1) {
3657 return getFocusedWindow();
3658 }
3659
3660 synchronized (mWindowMap) {
3661 final ArrayList windows = mWindows;
3662 final int count = windows.size();
3663
3664 for (int i = 0; i < count; i++) {
3665 WindowState w = (WindowState) windows.get(i);
3666 if (System.identityHashCode(w) == hashCode) {
3667 return w;
3668 }
3669 }
3670 }
3671
3672 return null;
3673 }
3674
3675 /*
3676 * Instruct the Activity Manager to fetch the current configuration and broadcast
3677 * that to config-changed listeners if appropriate.
3678 */
3679 void sendNewConfiguration() {
3680 try {
3681 mActivityManager.updateConfiguration(null);
3682 } catch (RemoteException e) {
3683 }
3684 }
Romain Guy06882f82009-06-10 13:36:04 -07003685
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003686 public Configuration computeNewConfiguration() {
3687 synchronized (mWindowMap) {
Dianne Hackbornc485a602009-03-24 22:39:49 -07003688 return computeNewConfigurationLocked();
3689 }
3690 }
Romain Guy06882f82009-06-10 13:36:04 -07003691
Dianne Hackbornc485a602009-03-24 22:39:49 -07003692 Configuration computeNewConfigurationLocked() {
3693 Configuration config = new Configuration();
3694 if (!computeNewConfigurationLocked(config)) {
3695 return null;
3696 }
3697 Log.i(TAG, "Config changed: " + config);
3698 long now = SystemClock.uptimeMillis();
3699 //Log.i(TAG, "Config changing, gc pending: " + mFreezeGcPending + ", now " + now);
3700 if (mFreezeGcPending != 0) {
3701 if (now > (mFreezeGcPending+1000)) {
3702 //Log.i(TAG, "Gc! " + now + " > " + (mFreezeGcPending+1000));
3703 mH.removeMessages(H.FORCE_GC);
3704 Runtime.getRuntime().gc();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003705 mFreezeGcPending = now;
3706 }
Dianne Hackbornc485a602009-03-24 22:39:49 -07003707 } else {
3708 mFreezeGcPending = now;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003709 }
Dianne Hackbornc485a602009-03-24 22:39:49 -07003710 return config;
3711 }
Romain Guy06882f82009-06-10 13:36:04 -07003712
Dianne Hackbornc485a602009-03-24 22:39:49 -07003713 boolean computeNewConfigurationLocked(Configuration config) {
3714 if (mDisplay == null) {
3715 return false;
3716 }
3717 mQueue.getInputConfiguration(config);
3718 final int dw = mDisplay.getWidth();
3719 final int dh = mDisplay.getHeight();
3720 int orientation = Configuration.ORIENTATION_SQUARE;
3721 if (dw < dh) {
3722 orientation = Configuration.ORIENTATION_PORTRAIT;
3723 } else if (dw > dh) {
3724 orientation = Configuration.ORIENTATION_LANDSCAPE;
3725 }
3726 config.orientation = orientation;
3727 config.keyboardHidden = Configuration.KEYBOARDHIDDEN_NO;
3728 config.hardKeyboardHidden = Configuration.HARDKEYBOARDHIDDEN_NO;
3729 mPolicy.adjustConfigurationLw(config);
3730 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003731 }
Romain Guy06882f82009-06-10 13:36:04 -07003732
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003733 // -------------------------------------------------------------
3734 // Input Events and Focus Management
3735 // -------------------------------------------------------------
3736
3737 private final void wakeupIfNeeded(WindowState targetWin, int eventType) {
Michael Chane96440f2009-05-06 10:27:36 -07003738 long curTime = SystemClock.uptimeMillis();
3739
3740 if (eventType == LONG_TOUCH_EVENT || eventType == CHEEK_EVENT) {
3741 if (mLastTouchEventType == eventType &&
3742 (curTime - mLastUserActivityCallTime) < MIN_TIME_BETWEEN_USERACTIVITIES) {
3743 return;
3744 }
3745 mLastUserActivityCallTime = curTime;
3746 mLastTouchEventType = eventType;
3747 }
3748
3749 if (targetWin == null
3750 || targetWin.mAttrs.type != WindowManager.LayoutParams.TYPE_KEYGUARD) {
3751 mPowerManager.userActivity(curTime, false, eventType, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003752 }
3753 }
3754
3755 // tells if it's a cheek event or not -- this function is stateful
3756 private static final int EVENT_NONE = 0;
3757 private static final int EVENT_UNKNOWN = 0;
3758 private static final int EVENT_CHEEK = 0;
3759 private static final int EVENT_IGNORE_DURATION = 300; // ms
3760 private static final float CHEEK_THRESHOLD = 0.6f;
3761 private int mEventState = EVENT_NONE;
3762 private float mEventSize;
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07003763
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003764 private int eventType(MotionEvent ev) {
3765 float size = ev.getSize();
3766 switch (ev.getAction()) {
3767 case MotionEvent.ACTION_DOWN:
3768 mEventSize = size;
3769 return (mEventSize > CHEEK_THRESHOLD) ? CHEEK_EVENT : TOUCH_EVENT;
3770 case MotionEvent.ACTION_UP:
3771 if (size > mEventSize) mEventSize = size;
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07003772 return (mEventSize > CHEEK_THRESHOLD) ? CHEEK_EVENT : TOUCH_UP_EVENT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003773 case MotionEvent.ACTION_MOVE:
3774 final int N = ev.getHistorySize();
3775 if (size > mEventSize) mEventSize = size;
3776 if (mEventSize > CHEEK_THRESHOLD) return CHEEK_EVENT;
3777 for (int i=0; i<N; i++) {
3778 size = ev.getHistoricalSize(i);
3779 if (size > mEventSize) mEventSize = size;
3780 if (mEventSize > CHEEK_THRESHOLD) return CHEEK_EVENT;
3781 }
3782 if (ev.getEventTime() < ev.getDownTime() + EVENT_IGNORE_DURATION) {
3783 return TOUCH_EVENT;
3784 } else {
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07003785 return LONG_TOUCH_EVENT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003786 }
3787 default:
3788 // not good
3789 return OTHER_EVENT;
3790 }
3791 }
3792
3793 /**
3794 * @return Returns true if event was dispatched, false if it was dropped for any reason
3795 */
Dianne Hackborncfaef692009-06-15 14:24:44 -07003796 private int dispatchPointer(QueuedEvent qev, MotionEvent ev, int pid, int uid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003797 if (DEBUG_INPUT || WindowManagerPolicy.WATCH_POINTER) Log.v(TAG,
3798 "dispatchPointer " + ev);
3799
3800 Object targetObj = mKeyWaiter.waitForNextEventTarget(null, qev,
3801 ev, true, false);
Romain Guy06882f82009-06-10 13:36:04 -07003802
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003803 int action = ev.getAction();
Romain Guy06882f82009-06-10 13:36:04 -07003804
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003805 if (action == MotionEvent.ACTION_UP) {
3806 // let go of our target
3807 mKeyWaiter.mMotionTarget = null;
3808 mPowerManager.logPointerUpEvent();
3809 } else if (action == MotionEvent.ACTION_DOWN) {
3810 mPowerManager.logPointerDownEvent();
3811 }
3812
3813 if (targetObj == null) {
3814 // In this case we are either dropping the event, or have received
3815 // a move or up without a down. It is common to receive move
3816 // events in such a way, since this means the user is moving the
3817 // pointer without actually pressing down. All other cases should
3818 // be atypical, so let's log them.
Michael Chane96440f2009-05-06 10:27:36 -07003819 if (action != MotionEvent.ACTION_MOVE) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003820 Log.w(TAG, "No window to dispatch pointer action " + ev.getAction());
3821 }
3822 if (qev != null) {
3823 mQueue.recycleEvent(qev);
3824 }
3825 ev.recycle();
Dianne Hackborncfaef692009-06-15 14:24:44 -07003826 return INJECT_FAILED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003827 }
3828 if (targetObj == mKeyWaiter.CONSUMED_EVENT_TOKEN) {
3829 if (qev != null) {
3830 mQueue.recycleEvent(qev);
3831 }
3832 ev.recycle();
Dianne Hackborncfaef692009-06-15 14:24:44 -07003833 return INJECT_SUCCEEDED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003834 }
Romain Guy06882f82009-06-10 13:36:04 -07003835
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003836 WindowState target = (WindowState)targetObj;
Romain Guy06882f82009-06-10 13:36:04 -07003837
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003838 final long eventTime = ev.getEventTime();
Romain Guy06882f82009-06-10 13:36:04 -07003839
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003840 //Log.i(TAG, "Sending " + ev + " to " + target);
3841
3842 if (uid != 0 && uid != target.mSession.mUid) {
3843 if (mContext.checkPermission(
3844 android.Manifest.permission.INJECT_EVENTS, pid, uid)
3845 != PackageManager.PERMISSION_GRANTED) {
3846 Log.w(TAG, "Permission denied: injecting pointer event from pid "
3847 + pid + " uid " + uid + " to window " + target
3848 + " owned by uid " + target.mSession.mUid);
3849 if (qev != null) {
3850 mQueue.recycleEvent(qev);
3851 }
3852 ev.recycle();
Dianne Hackborncfaef692009-06-15 14:24:44 -07003853 return INJECT_NO_PERMISSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003854 }
3855 }
Romain Guy06882f82009-06-10 13:36:04 -07003856
3857 if ((target.mAttrs.flags &
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003858 WindowManager.LayoutParams.FLAG_IGNORE_CHEEK_PRESSES) != 0) {
3859 //target wants to ignore fat touch events
3860 boolean cheekPress = mPolicy.isCheekPressedAgainstScreen(ev);
3861 //explicit flag to return without processing event further
3862 boolean returnFlag = false;
3863 if((action == MotionEvent.ACTION_DOWN)) {
3864 mFatTouch = false;
3865 if(cheekPress) {
3866 mFatTouch = true;
3867 returnFlag = true;
3868 }
3869 } else {
3870 if(action == MotionEvent.ACTION_UP) {
3871 if(mFatTouch) {
3872 //earlier even was invalid doesnt matter if current up is cheekpress or not
3873 mFatTouch = false;
3874 returnFlag = true;
3875 } else if(cheekPress) {
3876 //cancel the earlier event
3877 ev.setAction(MotionEvent.ACTION_CANCEL);
3878 action = MotionEvent.ACTION_CANCEL;
3879 }
3880 } else if(action == MotionEvent.ACTION_MOVE) {
3881 if(mFatTouch) {
3882 //two cases here
3883 //an invalid down followed by 0 or moves(valid or invalid)
Romain Guy06882f82009-06-10 13:36:04 -07003884 //a valid down, invalid move, more moves. want to ignore till up
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003885 returnFlag = true;
3886 } else if(cheekPress) {
3887 //valid down followed by invalid moves
3888 //an invalid move have to cancel earlier action
3889 ev.setAction(MotionEvent.ACTION_CANCEL);
3890 action = MotionEvent.ACTION_CANCEL;
3891 if (DEBUG_INPUT) Log.v(TAG, "Sending cancel for invalid ACTION_MOVE");
3892 //note that the subsequent invalid moves will not get here
3893 mFatTouch = true;
3894 }
3895 }
3896 } //else if action
3897 if(returnFlag) {
3898 //recycle que, ev
3899 if (qev != null) {
3900 mQueue.recycleEvent(qev);
3901 }
3902 ev.recycle();
Dianne Hackborncfaef692009-06-15 14:24:44 -07003903 return INJECT_FAILED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003904 }
3905 } //end if target
Michael Chane96440f2009-05-06 10:27:36 -07003906
3907 // TODO remove once we settle on a value or make it app specific
3908 if (action == MotionEvent.ACTION_DOWN) {
3909 int max_events_per_sec = 35;
3910 try {
3911 max_events_per_sec = Integer.parseInt(SystemProperties
3912 .get("windowsmgr.max_events_per_sec"));
3913 if (max_events_per_sec < 1) {
3914 max_events_per_sec = 35;
3915 }
3916 } catch (NumberFormatException e) {
3917 }
3918 mMinWaitTimeBetweenTouchEvents = 1000 / max_events_per_sec;
3919 }
3920
3921 /*
3922 * Throttle events to minimize CPU usage when there's a flood of events
3923 * e.g. constant contact with the screen
3924 */
3925 if (action == MotionEvent.ACTION_MOVE) {
3926 long nextEventTime = mLastTouchEventTime + mMinWaitTimeBetweenTouchEvents;
3927 long now = SystemClock.uptimeMillis();
3928 if (now < nextEventTime) {
3929 try {
3930 Thread.sleep(nextEventTime - now);
3931 } catch (InterruptedException e) {
3932 }
3933 mLastTouchEventTime = nextEventTime;
3934 } else {
3935 mLastTouchEventTime = now;
3936 }
3937 }
3938
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003939 synchronized(mWindowMap) {
3940 if (qev != null && action == MotionEvent.ACTION_MOVE) {
3941 mKeyWaiter.bindTargetWindowLocked(target,
3942 KeyWaiter.RETURN_PENDING_POINTER, qev);
3943 ev = null;
3944 } else {
3945 if (action == MotionEvent.ACTION_DOWN) {
3946 WindowState out = mKeyWaiter.mOutsideTouchTargets;
3947 if (out != null) {
3948 MotionEvent oev = MotionEvent.obtain(ev);
3949 oev.setAction(MotionEvent.ACTION_OUTSIDE);
3950 do {
3951 final Rect frame = out.mFrame;
3952 oev.offsetLocation(-(float)frame.left, -(float)frame.top);
3953 try {
3954 out.mClient.dispatchPointer(oev, eventTime);
3955 } catch (android.os.RemoteException e) {
3956 Log.i(TAG, "WINDOW DIED during outside motion dispatch: " + out);
3957 }
3958 oev.offsetLocation((float)frame.left, (float)frame.top);
3959 out = out.mNextOutsideTouch;
3960 } while (out != null);
3961 mKeyWaiter.mOutsideTouchTargets = null;
3962 }
3963 }
3964 final Rect frame = target.mFrame;
3965 ev.offsetLocation(-(float)frame.left, -(float)frame.top);
3966 mKeyWaiter.bindTargetWindowLocked(target);
3967 }
3968 }
Romain Guy06882f82009-06-10 13:36:04 -07003969
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003970 // finally offset the event to the target's coordinate system and
3971 // dispatch the event.
3972 try {
3973 if (DEBUG_INPUT || DEBUG_FOCUS || WindowManagerPolicy.WATCH_POINTER) {
3974 Log.v(TAG, "Delivering pointer " + qev + " to " + target);
3975 }
3976 target.mClient.dispatchPointer(ev, eventTime);
Dianne Hackborncfaef692009-06-15 14:24:44 -07003977 return INJECT_SUCCEEDED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003978 } catch (android.os.RemoteException e) {
3979 Log.i(TAG, "WINDOW DIED during motion dispatch: " + target);
3980 mKeyWaiter.mMotionTarget = null;
3981 try {
3982 removeWindow(target.mSession, target.mClient);
3983 } catch (java.util.NoSuchElementException ex) {
3984 // This will happen if the window has already been
3985 // removed.
3986 }
3987 }
Dianne Hackborncfaef692009-06-15 14:24:44 -07003988 return INJECT_FAILED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003989 }
Romain Guy06882f82009-06-10 13:36:04 -07003990
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003991 /**
3992 * @return Returns true if event was dispatched, false if it was dropped for any reason
3993 */
Dianne Hackborncfaef692009-06-15 14:24:44 -07003994 private int dispatchTrackball(QueuedEvent qev, MotionEvent ev, int pid, int uid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003995 if (DEBUG_INPUT) Log.v(
3996 TAG, "dispatchTrackball [" + ev.getAction() +"] <" + ev.getX() + ", " + ev.getY() + ">");
Romain Guy06882f82009-06-10 13:36:04 -07003997
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003998 Object focusObj = mKeyWaiter.waitForNextEventTarget(null, qev,
3999 ev, false, false);
4000 if (focusObj == null) {
4001 Log.w(TAG, "No focus window, dropping trackball: " + ev);
4002 if (qev != null) {
4003 mQueue.recycleEvent(qev);
4004 }
4005 ev.recycle();
Dianne Hackborncfaef692009-06-15 14:24:44 -07004006 return INJECT_FAILED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004007 }
4008 if (focusObj == mKeyWaiter.CONSUMED_EVENT_TOKEN) {
4009 if (qev != null) {
4010 mQueue.recycleEvent(qev);
4011 }
4012 ev.recycle();
Dianne Hackborncfaef692009-06-15 14:24:44 -07004013 return INJECT_SUCCEEDED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004014 }
Romain Guy06882f82009-06-10 13:36:04 -07004015
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004016 WindowState focus = (WindowState)focusObj;
Romain Guy06882f82009-06-10 13:36:04 -07004017
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004018 if (uid != 0 && uid != focus.mSession.mUid) {
4019 if (mContext.checkPermission(
4020 android.Manifest.permission.INJECT_EVENTS, pid, uid)
4021 != PackageManager.PERMISSION_GRANTED) {
4022 Log.w(TAG, "Permission denied: injecting key event from pid "
4023 + pid + " uid " + uid + " to window " + focus
4024 + " owned by uid " + focus.mSession.mUid);
4025 if (qev != null) {
4026 mQueue.recycleEvent(qev);
4027 }
4028 ev.recycle();
Dianne Hackborncfaef692009-06-15 14:24:44 -07004029 return INJECT_NO_PERMISSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004030 }
4031 }
Romain Guy06882f82009-06-10 13:36:04 -07004032
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004033 final long eventTime = ev.getEventTime();
Romain Guy06882f82009-06-10 13:36:04 -07004034
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004035 synchronized(mWindowMap) {
4036 if (qev != null && ev.getAction() == MotionEvent.ACTION_MOVE) {
4037 mKeyWaiter.bindTargetWindowLocked(focus,
4038 KeyWaiter.RETURN_PENDING_TRACKBALL, qev);
4039 // We don't deliver movement events to the client, we hold
4040 // them and wait for them to call back.
4041 ev = null;
4042 } else {
4043 mKeyWaiter.bindTargetWindowLocked(focus);
4044 }
4045 }
Romain Guy06882f82009-06-10 13:36:04 -07004046
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004047 try {
4048 focus.mClient.dispatchTrackball(ev, eventTime);
Dianne Hackborncfaef692009-06-15 14:24:44 -07004049 return INJECT_SUCCEEDED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004050 } catch (android.os.RemoteException e) {
4051 Log.i(TAG, "WINDOW DIED during key dispatch: " + focus);
4052 try {
4053 removeWindow(focus.mSession, focus.mClient);
4054 } catch (java.util.NoSuchElementException ex) {
4055 // This will happen if the window has already been
4056 // removed.
4057 }
4058 }
Romain Guy06882f82009-06-10 13:36:04 -07004059
Dianne Hackborncfaef692009-06-15 14:24:44 -07004060 return INJECT_FAILED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004061 }
Romain Guy06882f82009-06-10 13:36:04 -07004062
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004063 /**
4064 * @return Returns true if event was dispatched, false if it was dropped for any reason
4065 */
Dianne Hackborncfaef692009-06-15 14:24:44 -07004066 private int dispatchKey(KeyEvent event, int pid, int uid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004067 if (DEBUG_INPUT) Log.v(TAG, "Dispatch key: " + event);
4068
4069 Object focusObj = mKeyWaiter.waitForNextEventTarget(event, null,
4070 null, false, false);
4071 if (focusObj == null) {
4072 Log.w(TAG, "No focus window, dropping: " + event);
Dianne Hackborncfaef692009-06-15 14:24:44 -07004073 return INJECT_FAILED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004074 }
4075 if (focusObj == mKeyWaiter.CONSUMED_EVENT_TOKEN) {
Dianne Hackborncfaef692009-06-15 14:24:44 -07004076 return INJECT_SUCCEEDED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004077 }
Romain Guy06882f82009-06-10 13:36:04 -07004078
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004079 WindowState focus = (WindowState)focusObj;
Romain Guy06882f82009-06-10 13:36:04 -07004080
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004081 if (DEBUG_INPUT) Log.v(
4082 TAG, "Dispatching to " + focus + ": " + event);
4083
4084 if (uid != 0 && uid != focus.mSession.mUid) {
4085 if (mContext.checkPermission(
4086 android.Manifest.permission.INJECT_EVENTS, pid, uid)
4087 != PackageManager.PERMISSION_GRANTED) {
4088 Log.w(TAG, "Permission denied: injecting key event from pid "
4089 + pid + " uid " + uid + " to window " + focus
4090 + " owned by uid " + focus.mSession.mUid);
Dianne Hackborncfaef692009-06-15 14:24:44 -07004091 return INJECT_NO_PERMISSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004092 }
4093 }
Romain Guy06882f82009-06-10 13:36:04 -07004094
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004095 synchronized(mWindowMap) {
4096 mKeyWaiter.bindTargetWindowLocked(focus);
4097 }
4098
4099 // NOSHIP extra state logging
4100 mKeyWaiter.recordDispatchState(event, focus);
4101 // END NOSHIP
Romain Guy06882f82009-06-10 13:36:04 -07004102
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004103 try {
4104 if (DEBUG_INPUT || DEBUG_FOCUS) {
4105 Log.v(TAG, "Delivering key " + event.getKeyCode()
4106 + " to " + focus);
4107 }
4108 focus.mClient.dispatchKey(event);
Dianne Hackborncfaef692009-06-15 14:24:44 -07004109 return INJECT_SUCCEEDED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004110 } catch (android.os.RemoteException e) {
4111 Log.i(TAG, "WINDOW DIED during key dispatch: " + focus);
4112 try {
4113 removeWindow(focus.mSession, focus.mClient);
4114 } catch (java.util.NoSuchElementException ex) {
4115 // This will happen if the window has already been
4116 // removed.
4117 }
4118 }
Romain Guy06882f82009-06-10 13:36:04 -07004119
Dianne Hackborncfaef692009-06-15 14:24:44 -07004120 return INJECT_FAILED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004121 }
Romain Guy06882f82009-06-10 13:36:04 -07004122
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004123 public void pauseKeyDispatching(IBinder _token) {
4124 if (!checkCallingPermission(android.Manifest.permission.MANAGE_APP_TOKENS,
4125 "pauseKeyDispatching()")) {
Dianne Hackborncfaef692009-06-15 14:24:44 -07004126 throw new SecurityException("Requires MANAGE_APP_TOKENS permission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004127 }
4128
4129 synchronized (mWindowMap) {
4130 WindowToken token = mTokenMap.get(_token);
4131 if (token != null) {
4132 mKeyWaiter.pauseDispatchingLocked(token);
4133 }
4134 }
4135 }
4136
4137 public void resumeKeyDispatching(IBinder _token) {
4138 if (!checkCallingPermission(android.Manifest.permission.MANAGE_APP_TOKENS,
4139 "resumeKeyDispatching()")) {
Dianne Hackborncfaef692009-06-15 14:24:44 -07004140 throw new SecurityException("Requires MANAGE_APP_TOKENS permission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004141 }
4142
4143 synchronized (mWindowMap) {
4144 WindowToken token = mTokenMap.get(_token);
4145 if (token != null) {
4146 mKeyWaiter.resumeDispatchingLocked(token);
4147 }
4148 }
4149 }
4150
4151 public void setEventDispatching(boolean enabled) {
4152 if (!checkCallingPermission(android.Manifest.permission.MANAGE_APP_TOKENS,
4153 "resumeKeyDispatching()")) {
Dianne Hackborncfaef692009-06-15 14:24:44 -07004154 throw new SecurityException("Requires MANAGE_APP_TOKENS permission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004155 }
4156
4157 synchronized (mWindowMap) {
4158 mKeyWaiter.setEventDispatchingLocked(enabled);
4159 }
4160 }
Romain Guy06882f82009-06-10 13:36:04 -07004161
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004162 /**
4163 * Injects a keystroke event into the UI.
Romain Guy06882f82009-06-10 13:36:04 -07004164 *
4165 * @param ev A motion event describing the keystroke action. (Be sure to use
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004166 * {@link SystemClock#uptimeMillis()} as the timebase.)
4167 * @param sync If true, wait for the event to be completed before returning to the caller.
4168 * @return Returns true if event was dispatched, false if it was dropped for any reason
4169 */
4170 public boolean injectKeyEvent(KeyEvent ev, boolean sync) {
4171 long downTime = ev.getDownTime();
4172 long eventTime = ev.getEventTime();
4173
4174 int action = ev.getAction();
4175 int code = ev.getKeyCode();
4176 int repeatCount = ev.getRepeatCount();
4177 int metaState = ev.getMetaState();
4178 int deviceId = ev.getDeviceId();
4179 int scancode = ev.getScanCode();
4180
4181 if (eventTime == 0) eventTime = SystemClock.uptimeMillis();
4182 if (downTime == 0) downTime = eventTime;
4183
4184 KeyEvent newEvent = new KeyEvent(downTime, eventTime, action, code, repeatCount, metaState,
The Android Open Source Project10592532009-03-18 17:39:46 -07004185 deviceId, scancode, KeyEvent.FLAG_FROM_SYSTEM);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004186
Dianne Hackborncfaef692009-06-15 14:24:44 -07004187 int result = dispatchKey(newEvent, Binder.getCallingPid(), Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004188 if (sync) {
4189 mKeyWaiter.waitForNextEventTarget(null, null, null, false, true);
4190 }
Dianne Hackborncfaef692009-06-15 14:24:44 -07004191 switch (result) {
4192 case INJECT_NO_PERMISSION:
4193 throw new SecurityException(
4194 "Injecting to another application requires INJECT_EVENT permission");
4195 case INJECT_SUCCEEDED:
4196 return true;
4197 }
4198 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004199 }
4200
4201 /**
4202 * Inject a pointer (touch) event into the UI.
Romain Guy06882f82009-06-10 13:36:04 -07004203 *
4204 * @param ev A motion event describing the pointer (touch) action. (As noted in
4205 * {@link MotionEvent#obtain(long, long, int, float, float, int)}, be sure to use
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004206 * {@link SystemClock#uptimeMillis()} as the timebase.)
4207 * @param sync If true, wait for the event to be completed before returning to the caller.
4208 * @return Returns true if event was dispatched, false if it was dropped for any reason
4209 */
4210 public boolean injectPointerEvent(MotionEvent ev, boolean sync) {
Dianne Hackborncfaef692009-06-15 14:24:44 -07004211 int result = dispatchPointer(null, ev, Binder.getCallingPid(), Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004212 if (sync) {
4213 mKeyWaiter.waitForNextEventTarget(null, null, null, false, true);
4214 }
Dianne Hackborncfaef692009-06-15 14:24:44 -07004215 switch (result) {
4216 case INJECT_NO_PERMISSION:
4217 throw new SecurityException(
4218 "Injecting to another application requires INJECT_EVENT permission");
4219 case INJECT_SUCCEEDED:
4220 return true;
4221 }
4222 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004223 }
Romain Guy06882f82009-06-10 13:36:04 -07004224
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004225 /**
4226 * Inject a trackball (navigation device) event into the UI.
Romain Guy06882f82009-06-10 13:36:04 -07004227 *
4228 * @param ev A motion event describing the trackball action. (As noted in
4229 * {@link MotionEvent#obtain(long, long, int, float, float, int)}, be sure to use
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004230 * {@link SystemClock#uptimeMillis()} as the timebase.)
4231 * @param sync If true, wait for the event to be completed before returning to the caller.
4232 * @return Returns true if event was dispatched, false if it was dropped for any reason
4233 */
4234 public boolean injectTrackballEvent(MotionEvent ev, boolean sync) {
Dianne Hackborncfaef692009-06-15 14:24:44 -07004235 int result = dispatchTrackball(null, ev, Binder.getCallingPid(), Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004236 if (sync) {
4237 mKeyWaiter.waitForNextEventTarget(null, null, null, false, true);
4238 }
Dianne Hackborncfaef692009-06-15 14:24:44 -07004239 switch (result) {
4240 case INJECT_NO_PERMISSION:
4241 throw new SecurityException(
4242 "Injecting to another application requires INJECT_EVENT permission");
4243 case INJECT_SUCCEEDED:
4244 return true;
4245 }
4246 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004247 }
Romain Guy06882f82009-06-10 13:36:04 -07004248
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004249 private WindowState getFocusedWindow() {
4250 synchronized (mWindowMap) {
4251 return getFocusedWindowLocked();
4252 }
4253 }
4254
4255 private WindowState getFocusedWindowLocked() {
4256 return mCurrentFocus;
4257 }
Romain Guy06882f82009-06-10 13:36:04 -07004258
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004259 /**
4260 * This class holds the state for dispatching key events. This state
4261 * is protected by the KeyWaiter instance, NOT by the window lock. You
4262 * can be holding the main window lock while acquire the KeyWaiter lock,
4263 * but not the other way around.
4264 */
4265 final class KeyWaiter {
4266 // NOSHIP debugging
4267 public class DispatchState {
4268 private KeyEvent event;
4269 private WindowState focus;
4270 private long time;
4271 private WindowState lastWin;
4272 private IBinder lastBinder;
4273 private boolean finished;
4274 private boolean gotFirstWindow;
4275 private boolean eventDispatching;
4276 private long timeToSwitch;
4277 private boolean wasFrozen;
4278 private boolean focusPaused;
The Android Open Source Projectc474dec2009-03-04 09:49:09 -08004279 private WindowState curFocus;
Romain Guy06882f82009-06-10 13:36:04 -07004280
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004281 DispatchState(KeyEvent theEvent, WindowState theFocus) {
4282 focus = theFocus;
4283 event = theEvent;
4284 time = System.currentTimeMillis();
4285 // snapshot KeyWaiter state
4286 lastWin = mLastWin;
4287 lastBinder = mLastBinder;
4288 finished = mFinished;
4289 gotFirstWindow = mGotFirstWindow;
4290 eventDispatching = mEventDispatching;
4291 timeToSwitch = mTimeToSwitch;
4292 wasFrozen = mWasFrozen;
The Android Open Source Projectc474dec2009-03-04 09:49:09 -08004293 curFocus = mCurrentFocus;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004294 // cache the paused state at ctor time as well
4295 if (theFocus == null || theFocus.mToken == null) {
4296 Log.i(TAG, "focus " + theFocus + " mToken is null at event dispatch!");
4297 focusPaused = false;
4298 } else {
4299 focusPaused = theFocus.mToken.paused;
4300 }
4301 }
Romain Guy06882f82009-06-10 13:36:04 -07004302
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004303 public String toString() {
4304 return "{{" + event + " to " + focus + " @ " + time
4305 + " lw=" + lastWin + " lb=" + lastBinder
4306 + " fin=" + finished + " gfw=" + gotFirstWindow
4307 + " ed=" + eventDispatching + " tts=" + timeToSwitch
The Android Open Source Projectc474dec2009-03-04 09:49:09 -08004308 + " wf=" + wasFrozen + " fp=" + focusPaused
4309 + " mcf=" + mCurrentFocus + "}}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004310 }
4311 };
4312 private DispatchState mDispatchState = null;
4313 public void recordDispatchState(KeyEvent theEvent, WindowState theFocus) {
4314 mDispatchState = new DispatchState(theEvent, theFocus);
4315 }
4316 // END NOSHIP
4317
4318 public static final int RETURN_NOTHING = 0;
4319 public static final int RETURN_PENDING_POINTER = 1;
4320 public static final int RETURN_PENDING_TRACKBALL = 2;
Romain Guy06882f82009-06-10 13:36:04 -07004321
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004322 final Object SKIP_TARGET_TOKEN = new Object();
4323 final Object CONSUMED_EVENT_TOKEN = new Object();
Romain Guy06882f82009-06-10 13:36:04 -07004324
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004325 private WindowState mLastWin = null;
4326 private IBinder mLastBinder = null;
4327 private boolean mFinished = true;
4328 private boolean mGotFirstWindow = false;
4329 private boolean mEventDispatching = true;
4330 private long mTimeToSwitch = 0;
4331 /* package */ boolean mWasFrozen = false;
Romain Guy06882f82009-06-10 13:36:04 -07004332
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004333 // Target of Motion events
4334 WindowState mMotionTarget;
Romain Guy06882f82009-06-10 13:36:04 -07004335
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004336 // Windows above the target who would like to receive an "outside"
4337 // touch event for any down events outside of them.
4338 WindowState mOutsideTouchTargets;
4339
4340 /**
4341 * Wait for the last event dispatch to complete, then find the next
4342 * target that should receive the given event and wait for that one
4343 * to be ready to receive it.
4344 */
4345 Object waitForNextEventTarget(KeyEvent nextKey, QueuedEvent qev,
4346 MotionEvent nextMotion, boolean isPointerEvent,
4347 boolean failIfTimeout) {
4348 long startTime = SystemClock.uptimeMillis();
4349 long keyDispatchingTimeout = 5 * 1000;
4350 long waitedFor = 0;
4351
4352 while (true) {
4353 // Figure out which window we care about. It is either the
4354 // last window we are waiting to have process the event or,
4355 // if none, then the next window we think the event should go
4356 // to. Note: we retrieve mLastWin outside of the lock, so
4357 // it may change before we lock. Thus we must check it again.
4358 WindowState targetWin = mLastWin;
4359 boolean targetIsNew = targetWin == null;
4360 if (DEBUG_INPUT) Log.v(
4361 TAG, "waitForLastKey: mFinished=" + mFinished +
4362 ", mLastWin=" + mLastWin);
4363 if (targetIsNew) {
4364 Object target = findTargetWindow(nextKey, qev, nextMotion,
4365 isPointerEvent);
4366 if (target == SKIP_TARGET_TOKEN) {
4367 // The user has pressed a special key, and we are
4368 // dropping all pending events before it.
4369 if (DEBUG_INPUT) Log.v(TAG, "Skipping: " + nextKey
4370 + " " + nextMotion);
4371 return null;
4372 }
4373 if (target == CONSUMED_EVENT_TOKEN) {
4374 if (DEBUG_INPUT) Log.v(TAG, "Consumed: " + nextKey
4375 + " " + nextMotion);
4376 return target;
4377 }
4378 targetWin = (WindowState)target;
4379 }
Romain Guy06882f82009-06-10 13:36:04 -07004380
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004381 AppWindowToken targetApp = null;
Romain Guy06882f82009-06-10 13:36:04 -07004382
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004383 // Now: is it okay to send the next event to this window?
4384 synchronized (this) {
4385 // First: did we come here based on the last window not
4386 // being null, but it changed by the time we got here?
4387 // If so, try again.
4388 if (!targetIsNew && mLastWin == null) {
4389 continue;
4390 }
Romain Guy06882f82009-06-10 13:36:04 -07004391
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004392 // We never dispatch events if not finished with the
4393 // last one, or the display is frozen.
4394 if (mFinished && !mDisplayFrozen) {
4395 // If event dispatching is disabled, then we
4396 // just consume the events.
4397 if (!mEventDispatching) {
4398 if (DEBUG_INPUT) Log.v(TAG,
4399 "Skipping event; dispatching disabled: "
4400 + nextKey + " " + nextMotion);
4401 return null;
4402 }
4403 if (targetWin != null) {
4404 // If this is a new target, and that target is not
4405 // paused or unresponsive, then all looks good to
4406 // handle the event.
4407 if (targetIsNew && !targetWin.mToken.paused) {
4408 return targetWin;
4409 }
Romain Guy06882f82009-06-10 13:36:04 -07004410
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004411 // If we didn't find a target window, and there is no
4412 // focused app window, then just eat the events.
4413 } else if (mFocusedApp == null) {
4414 if (DEBUG_INPUT) Log.v(TAG,
4415 "Skipping event; no focused app: "
4416 + nextKey + " " + nextMotion);
4417 return null;
4418 }
4419 }
Romain Guy06882f82009-06-10 13:36:04 -07004420
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004421 if (DEBUG_INPUT) Log.v(
4422 TAG, "Waiting for last key in " + mLastBinder
4423 + " target=" + targetWin
4424 + " mFinished=" + mFinished
4425 + " mDisplayFrozen=" + mDisplayFrozen
4426 + " targetIsNew=" + targetIsNew
4427 + " paused="
4428 + (targetWin != null ? targetWin.mToken.paused : false)
The Android Open Source Projectc474dec2009-03-04 09:49:09 -08004429 + " mFocusedApp=" + mFocusedApp
4430 + " mCurrentFocus=" + mCurrentFocus);
Romain Guy06882f82009-06-10 13:36:04 -07004431
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004432 targetApp = targetWin != null
4433 ? targetWin.mAppToken : mFocusedApp;
Romain Guy06882f82009-06-10 13:36:04 -07004434
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004435 long curTimeout = keyDispatchingTimeout;
4436 if (mTimeToSwitch != 0) {
4437 long now = SystemClock.uptimeMillis();
4438 if (mTimeToSwitch <= now) {
4439 // If an app switch key has been pressed, and we have
4440 // waited too long for the current app to finish
4441 // processing keys, then wait no more!
4442 doFinishedKeyLocked(true);
4443 continue;
4444 }
4445 long switchTimeout = mTimeToSwitch - now;
4446 if (curTimeout > switchTimeout) {
4447 curTimeout = switchTimeout;
4448 }
4449 }
Romain Guy06882f82009-06-10 13:36:04 -07004450
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004451 try {
4452 // after that continue
4453 // processing keys, so we don't get stuck.
4454 if (DEBUG_INPUT) Log.v(
4455 TAG, "Waiting for key dispatch: " + curTimeout);
4456 wait(curTimeout);
4457 if (DEBUG_INPUT) Log.v(TAG, "Finished waiting @"
4458 + SystemClock.uptimeMillis() + " startTime="
The Android Open Source Projectc474dec2009-03-04 09:49:09 -08004459 + startTime + " switchTime=" + mTimeToSwitch
4460 + " target=" + targetWin + " mLW=" + mLastWin
4461 + " mLB=" + mLastBinder + " fin=" + mFinished
4462 + " mCurrentFocus=" + mCurrentFocus);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004463 } catch (InterruptedException e) {
4464 }
4465 }
4466
4467 // If we were frozen during configuration change, restart the
4468 // timeout checks from now; otherwise look at whether we timed
4469 // out before awakening.
4470 if (mWasFrozen) {
4471 waitedFor = 0;
4472 mWasFrozen = false;
4473 } else {
4474 waitedFor = SystemClock.uptimeMillis() - startTime;
4475 }
4476
4477 if (waitedFor >= keyDispatchingTimeout && mTimeToSwitch == 0) {
4478 IApplicationToken at = null;
4479 synchronized (this) {
4480 Log.w(TAG, "Key dispatching timed out sending to " +
4481 (targetWin != null ? targetWin.mAttrs.getTitle()
4482 : "<null>"));
4483 // NOSHIP debugging
4484 Log.w(TAG, "Dispatch state: " + mDispatchState);
4485 Log.w(TAG, "Current state: " + new DispatchState(nextKey, targetWin));
4486 // END NOSHIP
4487 //dump();
4488 if (targetWin != null) {
4489 at = targetWin.getAppToken();
4490 } else if (targetApp != null) {
4491 at = targetApp.appToken;
4492 }
4493 }
4494
4495 boolean abort = true;
4496 if (at != null) {
4497 try {
4498 long timeout = at.getKeyDispatchingTimeout();
4499 if (timeout > waitedFor) {
4500 // we did not wait the proper amount of time for this application.
4501 // set the timeout to be the real timeout and wait again.
4502 keyDispatchingTimeout = timeout - waitedFor;
4503 continue;
4504 } else {
4505 abort = at.keyDispatchingTimedOut();
4506 }
4507 } catch (RemoteException ex) {
4508 }
4509 }
4510
4511 synchronized (this) {
4512 if (abort && (mLastWin == targetWin || targetWin == null)) {
4513 mFinished = true;
Romain Guy06882f82009-06-10 13:36:04 -07004514 if (mLastWin != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004515 if (DEBUG_INPUT) Log.v(TAG,
4516 "Window " + mLastWin +
4517 " timed out on key input");
4518 if (mLastWin.mToken.paused) {
4519 Log.w(TAG, "Un-pausing dispatching to this window");
4520 mLastWin.mToken.paused = false;
4521 }
4522 }
4523 if (mMotionTarget == targetWin) {
4524 mMotionTarget = null;
4525 }
4526 mLastWin = null;
4527 mLastBinder = null;
4528 if (failIfTimeout || targetWin == null) {
4529 return null;
4530 }
4531 } else {
4532 Log.w(TAG, "Continuing to wait for key to be dispatched");
4533 startTime = SystemClock.uptimeMillis();
4534 }
4535 }
4536 }
4537 }
4538 }
Romain Guy06882f82009-06-10 13:36:04 -07004539
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004540 Object findTargetWindow(KeyEvent nextKey, QueuedEvent qev,
4541 MotionEvent nextMotion, boolean isPointerEvent) {
4542 mOutsideTouchTargets = null;
Romain Guy06882f82009-06-10 13:36:04 -07004543
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004544 if (nextKey != null) {
4545 // Find the target window for a normal key event.
4546 final int keycode = nextKey.getKeyCode();
4547 final int repeatCount = nextKey.getRepeatCount();
4548 final boolean down = nextKey.getAction() != KeyEvent.ACTION_UP;
4549 boolean dispatch = mKeyWaiter.checkShouldDispatchKey(keycode);
4550 if (!dispatch) {
4551 mPolicy.interceptKeyTi(null, keycode,
4552 nextKey.getMetaState(), down, repeatCount);
4553 Log.w(TAG, "Event timeout during app switch: dropping "
4554 + nextKey);
4555 return SKIP_TARGET_TOKEN;
4556 }
Romain Guy06882f82009-06-10 13:36:04 -07004557
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004558 // System.out.println("##### [" + SystemClock.uptimeMillis() + "] WindowManagerService.dispatchKey(" + keycode + ", " + down + ", " + repeatCount + ")");
Romain Guy06882f82009-06-10 13:36:04 -07004559
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004560 WindowState focus = null;
4561 synchronized(mWindowMap) {
4562 focus = getFocusedWindowLocked();
4563 }
Romain Guy06882f82009-06-10 13:36:04 -07004564
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004565 wakeupIfNeeded(focus, LocalPowerManager.BUTTON_EVENT);
Romain Guy06882f82009-06-10 13:36:04 -07004566
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004567 if (mPolicy.interceptKeyTi(focus,
4568 keycode, nextKey.getMetaState(), down, repeatCount)) {
4569 return CONSUMED_EVENT_TOKEN;
4570 }
Romain Guy06882f82009-06-10 13:36:04 -07004571
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004572 return focus;
Romain Guy06882f82009-06-10 13:36:04 -07004573
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004574 } else if (!isPointerEvent) {
4575 boolean dispatch = mKeyWaiter.checkShouldDispatchKey(-1);
4576 if (!dispatch) {
4577 Log.w(TAG, "Event timeout during app switch: dropping trackball "
4578 + nextMotion);
4579 return SKIP_TARGET_TOKEN;
4580 }
Romain Guy06882f82009-06-10 13:36:04 -07004581
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004582 WindowState focus = null;
4583 synchronized(mWindowMap) {
4584 focus = getFocusedWindowLocked();
4585 }
Romain Guy06882f82009-06-10 13:36:04 -07004586
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004587 wakeupIfNeeded(focus, LocalPowerManager.BUTTON_EVENT);
4588 return focus;
4589 }
Romain Guy06882f82009-06-10 13:36:04 -07004590
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004591 if (nextMotion == null) {
4592 return SKIP_TARGET_TOKEN;
4593 }
Romain Guy06882f82009-06-10 13:36:04 -07004594
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004595 boolean dispatch = mKeyWaiter.checkShouldDispatchKey(
4596 KeyEvent.KEYCODE_UNKNOWN);
4597 if (!dispatch) {
4598 Log.w(TAG, "Event timeout during app switch: dropping pointer "
4599 + nextMotion);
4600 return SKIP_TARGET_TOKEN;
4601 }
Romain Guy06882f82009-06-10 13:36:04 -07004602
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004603 // Find the target window for a pointer event.
4604 int action = nextMotion.getAction();
4605 final float xf = nextMotion.getX();
4606 final float yf = nextMotion.getY();
4607 final long eventTime = nextMotion.getEventTime();
Romain Guy06882f82009-06-10 13:36:04 -07004608
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004609 final boolean screenWasOff = qev != null
4610 && (qev.flags&WindowManagerPolicy.FLAG_BRIGHT_HERE) != 0;
Romain Guy06882f82009-06-10 13:36:04 -07004611
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004612 WindowState target = null;
Romain Guy06882f82009-06-10 13:36:04 -07004613
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004614 synchronized(mWindowMap) {
4615 synchronized (this) {
4616 if (action == MotionEvent.ACTION_DOWN) {
4617 if (mMotionTarget != null) {
4618 // this is weird, we got a pen down, but we thought it was
4619 // already down!
4620 // XXX: We should probably send an ACTION_UP to the current
4621 // target.
4622 Log.w(TAG, "Pointer down received while already down in: "
4623 + mMotionTarget);
4624 mMotionTarget = null;
4625 }
Romain Guy06882f82009-06-10 13:36:04 -07004626
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004627 // ACTION_DOWN is special, because we need to lock next events to
4628 // the window we'll land onto.
4629 final int x = (int)xf;
4630 final int y = (int)yf;
Romain Guy06882f82009-06-10 13:36:04 -07004631
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004632 final ArrayList windows = mWindows;
4633 final int N = windows.size();
4634 WindowState topErrWindow = null;
4635 final Rect tmpRect = mTempRect;
4636 for (int i=N-1; i>=0; i--) {
4637 WindowState child = (WindowState)windows.get(i);
4638 //Log.i(TAG, "Checking dispatch to: " + child);
4639 final int flags = child.mAttrs.flags;
4640 if ((flags & WindowManager.LayoutParams.FLAG_SYSTEM_ERROR) != 0) {
4641 if (topErrWindow == null) {
4642 topErrWindow = child;
4643 }
4644 }
4645 if (!child.isVisibleLw()) {
4646 //Log.i(TAG, "Not visible!");
4647 continue;
4648 }
4649 if ((flags & WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE) != 0) {
4650 //Log.i(TAG, "Not touchable!");
4651 if ((flags & WindowManager.LayoutParams
4652 .FLAG_WATCH_OUTSIDE_TOUCH) != 0) {
4653 child.mNextOutsideTouch = mOutsideTouchTargets;
4654 mOutsideTouchTargets = child;
4655 }
4656 continue;
4657 }
4658 tmpRect.set(child.mFrame);
4659 if (child.mTouchableInsets == ViewTreeObserver
4660 .InternalInsetsInfo.TOUCHABLE_INSETS_CONTENT) {
4661 // The touch is inside of the window if it is
4662 // inside the frame, AND the content part of that
4663 // frame that was given by the application.
4664 tmpRect.left += child.mGivenContentInsets.left;
4665 tmpRect.top += child.mGivenContentInsets.top;
4666 tmpRect.right -= child.mGivenContentInsets.right;
4667 tmpRect.bottom -= child.mGivenContentInsets.bottom;
4668 } else if (child.mTouchableInsets == ViewTreeObserver
4669 .InternalInsetsInfo.TOUCHABLE_INSETS_VISIBLE) {
4670 // The touch is inside of the window if it is
4671 // inside the frame, AND the visible part of that
4672 // frame that was given by the application.
4673 tmpRect.left += child.mGivenVisibleInsets.left;
4674 tmpRect.top += child.mGivenVisibleInsets.top;
4675 tmpRect.right -= child.mGivenVisibleInsets.right;
4676 tmpRect.bottom -= child.mGivenVisibleInsets.bottom;
4677 }
4678 final int touchFlags = flags &
4679 (WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
4680 |WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL);
4681 if (tmpRect.contains(x, y) || touchFlags == 0) {
4682 //Log.i(TAG, "Using this target!");
4683 if (!screenWasOff || (flags &
4684 WindowManager.LayoutParams.FLAG_TOUCHABLE_WHEN_WAKING) != 0) {
4685 mMotionTarget = child;
4686 } else {
4687 //Log.i(TAG, "Waking, skip!");
4688 mMotionTarget = null;
4689 }
4690 break;
4691 }
Romain Guy06882f82009-06-10 13:36:04 -07004692
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004693 if ((flags & WindowManager.LayoutParams
4694 .FLAG_WATCH_OUTSIDE_TOUCH) != 0) {
4695 child.mNextOutsideTouch = mOutsideTouchTargets;
4696 mOutsideTouchTargets = child;
4697 //Log.i(TAG, "Adding to outside target list: " + child);
4698 }
4699 }
4700
4701 // if there's an error window but it's not accepting
4702 // focus (typically because it is not yet visible) just
4703 // wait for it -- any other focused window may in fact
4704 // be in ANR state.
4705 if (topErrWindow != null && mMotionTarget != topErrWindow) {
4706 mMotionTarget = null;
4707 }
4708 }
Romain Guy06882f82009-06-10 13:36:04 -07004709
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004710 target = mMotionTarget;
4711 }
4712 }
Romain Guy06882f82009-06-10 13:36:04 -07004713
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004714 wakeupIfNeeded(target, eventType(nextMotion));
Romain Guy06882f82009-06-10 13:36:04 -07004715
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004716 // Pointer events are a little different -- if there isn't a
4717 // target found for any event, then just drop it.
4718 return target != null ? target : SKIP_TARGET_TOKEN;
4719 }
Romain Guy06882f82009-06-10 13:36:04 -07004720
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004721 boolean checkShouldDispatchKey(int keycode) {
4722 synchronized (this) {
4723 if (mPolicy.isAppSwitchKeyTqTiLwLi(keycode)) {
4724 mTimeToSwitch = 0;
4725 return true;
4726 }
4727 if (mTimeToSwitch != 0
4728 && mTimeToSwitch < SystemClock.uptimeMillis()) {
4729 return false;
4730 }
4731 return true;
4732 }
4733 }
Romain Guy06882f82009-06-10 13:36:04 -07004734
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004735 void bindTargetWindowLocked(WindowState win,
4736 int pendingWhat, QueuedEvent pendingMotion) {
4737 synchronized (this) {
4738 bindTargetWindowLockedLocked(win, pendingWhat, pendingMotion);
4739 }
4740 }
Romain Guy06882f82009-06-10 13:36:04 -07004741
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004742 void bindTargetWindowLocked(WindowState win) {
4743 synchronized (this) {
4744 bindTargetWindowLockedLocked(win, RETURN_NOTHING, null);
4745 }
4746 }
4747
4748 void bindTargetWindowLockedLocked(WindowState win,
4749 int pendingWhat, QueuedEvent pendingMotion) {
4750 mLastWin = win;
4751 mLastBinder = win.mClient.asBinder();
4752 mFinished = false;
4753 if (pendingMotion != null) {
4754 final Session s = win.mSession;
4755 if (pendingWhat == RETURN_PENDING_POINTER) {
4756 releasePendingPointerLocked(s);
4757 s.mPendingPointerMove = pendingMotion;
4758 s.mPendingPointerWindow = win;
Romain Guy06882f82009-06-10 13:36:04 -07004759 if (DEBUG_INPUT) Log.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004760 "bindTargetToWindow " + s.mPendingPointerMove);
4761 } else if (pendingWhat == RETURN_PENDING_TRACKBALL) {
4762 releasePendingTrackballLocked(s);
4763 s.mPendingTrackballMove = pendingMotion;
4764 s.mPendingTrackballWindow = win;
4765 }
4766 }
4767 }
Romain Guy06882f82009-06-10 13:36:04 -07004768
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004769 void releasePendingPointerLocked(Session s) {
4770 if (DEBUG_INPUT) Log.v(TAG,
4771 "releasePendingPointer " + s.mPendingPointerMove);
4772 if (s.mPendingPointerMove != null) {
4773 mQueue.recycleEvent(s.mPendingPointerMove);
4774 s.mPendingPointerMove = null;
4775 }
4776 }
Romain Guy06882f82009-06-10 13:36:04 -07004777
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004778 void releasePendingTrackballLocked(Session s) {
4779 if (s.mPendingTrackballMove != null) {
4780 mQueue.recycleEvent(s.mPendingTrackballMove);
4781 s.mPendingTrackballMove = null;
4782 }
4783 }
Romain Guy06882f82009-06-10 13:36:04 -07004784
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004785 MotionEvent finishedKey(Session session, IWindow client, boolean force,
4786 int returnWhat) {
4787 if (DEBUG_INPUT) Log.v(
4788 TAG, "finishedKey: client=" + client + ", force=" + force);
4789
4790 if (client == null) {
4791 return null;
4792 }
4793
4794 synchronized (this) {
4795 if (DEBUG_INPUT) Log.v(
4796 TAG, "finishedKey: client=" + client.asBinder()
4797 + ", force=" + force + ", last=" + mLastBinder
4798 + " (token=" + (mLastWin != null ? mLastWin.mToken : null) + ")");
4799
4800 QueuedEvent qev = null;
4801 WindowState win = null;
4802 if (returnWhat == RETURN_PENDING_POINTER) {
4803 qev = session.mPendingPointerMove;
4804 win = session.mPendingPointerWindow;
4805 session.mPendingPointerMove = null;
4806 session.mPendingPointerWindow = null;
4807 } else if (returnWhat == RETURN_PENDING_TRACKBALL) {
4808 qev = session.mPendingTrackballMove;
4809 win = session.mPendingTrackballWindow;
4810 session.mPendingTrackballMove = null;
4811 session.mPendingTrackballWindow = null;
4812 }
Romain Guy06882f82009-06-10 13:36:04 -07004813
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004814 if (mLastBinder == client.asBinder()) {
4815 if (DEBUG_INPUT) Log.v(
4816 TAG, "finishedKey: last paused="
4817 + ((mLastWin != null) ? mLastWin.mToken.paused : "null"));
4818 if (mLastWin != null && (!mLastWin.mToken.paused || force
4819 || !mEventDispatching)) {
4820 doFinishedKeyLocked(false);
4821 } else {
4822 // Make sure to wake up anyone currently waiting to
4823 // dispatch a key, so they can re-evaluate their
4824 // current situation.
4825 mFinished = true;
4826 notifyAll();
4827 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004828 }
Romain Guy06882f82009-06-10 13:36:04 -07004829
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004830 if (qev != null) {
4831 MotionEvent res = (MotionEvent)qev.event;
4832 if (DEBUG_INPUT) Log.v(TAG,
4833 "Returning pending motion: " + res);
4834 mQueue.recycleEvent(qev);
4835 if (win != null && returnWhat == RETURN_PENDING_POINTER) {
4836 res.offsetLocation(-win.mFrame.left, -win.mFrame.top);
4837 }
4838 return res;
4839 }
4840 return null;
4841 }
4842 }
4843
4844 void tickle() {
4845 synchronized (this) {
4846 notifyAll();
4847 }
4848 }
Romain Guy06882f82009-06-10 13:36:04 -07004849
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004850 void handleNewWindowLocked(WindowState newWindow) {
4851 if (!newWindow.canReceiveKeys()) {
4852 return;
4853 }
4854 synchronized (this) {
The Android Open Source Projectc474dec2009-03-04 09:49:09 -08004855 if (DEBUG_INPUT) Log.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004856 TAG, "New key dispatch window: win="
4857 + newWindow.mClient.asBinder()
4858 + ", last=" + mLastBinder
4859 + " (token=" + (mLastWin != null ? mLastWin.mToken : null)
4860 + "), finished=" + mFinished + ", paused="
4861 + newWindow.mToken.paused);
4862
4863 // Displaying a window implicitly causes dispatching to
4864 // be unpaused. (This is to protect against bugs if someone
4865 // pauses dispatching but forgets to resume.)
4866 newWindow.mToken.paused = false;
4867
4868 mGotFirstWindow = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004869
4870 if ((newWindow.mAttrs.flags & FLAG_SYSTEM_ERROR) != 0) {
4871 if (DEBUG_INPUT) Log.v(TAG,
4872 "New SYSTEM_ERROR window; resetting state");
4873 mLastWin = null;
4874 mLastBinder = null;
4875 mMotionTarget = null;
4876 mFinished = true;
4877 } else if (mLastWin != null) {
4878 // If the new window is above the window we are
4879 // waiting on, then stop waiting and let key dispatching
4880 // start on the new guy.
4881 if (DEBUG_INPUT) Log.v(
4882 TAG, "Last win layer=" + mLastWin.mLayer
4883 + ", new win layer=" + newWindow.mLayer);
4884 if (newWindow.mLayer >= mLastWin.mLayer) {
The Android Open Source Projectc474dec2009-03-04 09:49:09 -08004885 // The new window is above the old; finish pending input to the last
4886 // window and start directing it to the new one.
4887 mLastWin.mToken.paused = false;
4888 doFinishedKeyLocked(true); // does a notifyAll()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004889 }
The Android Open Source Projectc474dec2009-03-04 09:49:09 -08004890 // Either the new window is lower, so there is no need to wake key waiters,
4891 // or we just finished key input to the previous window, which implicitly
4892 // notified the key waiters. In both cases, we don't need to issue the
4893 // notification here.
4894 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004895 }
4896
The Android Open Source Projectc474dec2009-03-04 09:49:09 -08004897 // Now that we've put a new window state in place, make the event waiter
4898 // take notice and retarget its attentions.
4899 notifyAll();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004900 }
4901 }
4902
4903 void pauseDispatchingLocked(WindowToken token) {
4904 synchronized (this)
4905 {
4906 if (DEBUG_INPUT) Log.v(TAG, "Pausing WindowToken " + token);
4907 token.paused = true;
4908
4909 /*
4910 if (mLastWin != null && !mFinished && mLastWin.mBaseLayer <= layer) {
4911 mPaused = true;
4912 } else {
4913 if (mLastWin == null) {
Dave Bortcfe65242009-04-09 14:51:04 -07004914 Log.i(TAG, "Key dispatching not paused: no last window.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004915 } else if (mFinished) {
Dave Bortcfe65242009-04-09 14:51:04 -07004916 Log.i(TAG, "Key dispatching not paused: finished last key.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004917 } else {
Dave Bortcfe65242009-04-09 14:51:04 -07004918 Log.i(TAG, "Key dispatching not paused: window in higher layer.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004919 }
4920 }
4921 */
4922 }
4923 }
4924
4925 void resumeDispatchingLocked(WindowToken token) {
4926 synchronized (this) {
4927 if (token.paused) {
4928 if (DEBUG_INPUT) Log.v(
4929 TAG, "Resuming WindowToken " + token
4930 + ", last=" + mLastBinder
4931 + " (token=" + (mLastWin != null ? mLastWin.mToken : null)
4932 + "), finished=" + mFinished + ", paused="
4933 + token.paused);
4934 token.paused = false;
4935 if (mLastWin != null && mLastWin.mToken == token && mFinished) {
4936 doFinishedKeyLocked(true);
4937 } else {
4938 notifyAll();
4939 }
4940 }
4941 }
4942 }
4943
4944 void setEventDispatchingLocked(boolean enabled) {
4945 synchronized (this) {
4946 mEventDispatching = enabled;
4947 notifyAll();
4948 }
4949 }
Romain Guy06882f82009-06-10 13:36:04 -07004950
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004951 void appSwitchComing() {
4952 synchronized (this) {
4953 // Don't wait for more than .5 seconds for app to finish
4954 // processing the pending events.
4955 long now = SystemClock.uptimeMillis() + 500;
4956 if (DEBUG_INPUT) Log.v(TAG, "appSwitchComing: " + now);
4957 if (mTimeToSwitch == 0 || now < mTimeToSwitch) {
4958 mTimeToSwitch = now;
4959 }
4960 notifyAll();
4961 }
4962 }
Romain Guy06882f82009-06-10 13:36:04 -07004963
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004964 private final void doFinishedKeyLocked(boolean doRecycle) {
4965 if (mLastWin != null) {
4966 releasePendingPointerLocked(mLastWin.mSession);
4967 releasePendingTrackballLocked(mLastWin.mSession);
4968 }
Romain Guy06882f82009-06-10 13:36:04 -07004969
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004970 if (mLastWin == null || !mLastWin.mToken.paused
4971 || !mLastWin.isVisibleLw()) {
4972 // If the current window has been paused, we aren't -really-
4973 // finished... so let the waiters still wait.
4974 mLastWin = null;
4975 mLastBinder = null;
4976 }
4977 mFinished = true;
4978 notifyAll();
4979 }
4980 }
4981
4982 private class KeyQ extends KeyInputQueue
4983 implements KeyInputQueue.FilterCallback {
4984 PowerManager.WakeLock mHoldingScreen;
Romain Guy06882f82009-06-10 13:36:04 -07004985
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004986 KeyQ() {
4987 super(mContext);
4988 PowerManager pm = (PowerManager)mContext.getSystemService(Context.POWER_SERVICE);
4989 mHoldingScreen = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK,
4990 "KEEP_SCREEN_ON_FLAG");
4991 mHoldingScreen.setReferenceCounted(false);
4992 }
4993
4994 @Override
4995 boolean preprocessEvent(InputDevice device, RawInputEvent event) {
4996 if (mPolicy.preprocessInputEventTq(event)) {
4997 return true;
4998 }
Romain Guy06882f82009-06-10 13:36:04 -07004999
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005000 switch (event.type) {
5001 case RawInputEvent.EV_KEY: {
5002 // XXX begin hack
5003 if (DEBUG) {
5004 if (event.keycode == KeyEvent.KEYCODE_G) {
5005 if (event.value != 0) {
5006 // G down
5007 mPolicy.screenTurnedOff(WindowManagerPolicy.OFF_BECAUSE_OF_USER);
5008 }
5009 return false;
5010 }
5011 if (event.keycode == KeyEvent.KEYCODE_D) {
5012 if (event.value != 0) {
5013 //dump();
5014 }
5015 return false;
5016 }
5017 }
5018 // XXX end hack
Romain Guy06882f82009-06-10 13:36:04 -07005019
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005020 boolean screenIsOff = !mPowerManager.screenIsOn();
5021 boolean screenIsDim = !mPowerManager.screenIsBright();
5022 int actions = mPolicy.interceptKeyTq(event, !screenIsOff);
Romain Guy06882f82009-06-10 13:36:04 -07005023
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005024 if ((actions & WindowManagerPolicy.ACTION_GO_TO_SLEEP) != 0) {
5025 mPowerManager.goToSleep(event.when);
5026 }
5027
5028 if (screenIsOff) {
5029 event.flags |= WindowManagerPolicy.FLAG_WOKE_HERE;
5030 }
5031 if (screenIsDim) {
5032 event.flags |= WindowManagerPolicy.FLAG_BRIGHT_HERE;
5033 }
5034 if ((actions & WindowManagerPolicy.ACTION_POKE_USER_ACTIVITY) != 0) {
5035 mPowerManager.userActivity(event.when, false,
Michael Chane96440f2009-05-06 10:27:36 -07005036 LocalPowerManager.BUTTON_EVENT, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005037 }
Romain Guy06882f82009-06-10 13:36:04 -07005038
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005039 if ((actions & WindowManagerPolicy.ACTION_PASS_TO_USER) != 0) {
5040 if (event.value != 0 && mPolicy.isAppSwitchKeyTqTiLwLi(event.keycode)) {
5041 filterQueue(this);
5042 mKeyWaiter.appSwitchComing();
5043 }
5044 return true;
5045 } else {
5046 return false;
5047 }
5048 }
Romain Guy06882f82009-06-10 13:36:04 -07005049
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005050 case RawInputEvent.EV_REL: {
5051 boolean screenIsOff = !mPowerManager.screenIsOn();
5052 boolean screenIsDim = !mPowerManager.screenIsBright();
5053 if (screenIsOff) {
5054 if (!mPolicy.isWakeRelMovementTq(event.deviceId,
5055 device.classes, event)) {
5056 //Log.i(TAG, "dropping because screenIsOff and !isWakeKey");
5057 return false;
5058 }
5059 event.flags |= WindowManagerPolicy.FLAG_WOKE_HERE;
5060 }
5061 if (screenIsDim) {
5062 event.flags |= WindowManagerPolicy.FLAG_BRIGHT_HERE;
5063 }
5064 return true;
5065 }
Romain Guy06882f82009-06-10 13:36:04 -07005066
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005067 case RawInputEvent.EV_ABS: {
5068 boolean screenIsOff = !mPowerManager.screenIsOn();
5069 boolean screenIsDim = !mPowerManager.screenIsBright();
5070 if (screenIsOff) {
5071 if (!mPolicy.isWakeAbsMovementTq(event.deviceId,
5072 device.classes, event)) {
5073 //Log.i(TAG, "dropping because screenIsOff and !isWakeKey");
5074 return false;
5075 }
5076 event.flags |= WindowManagerPolicy.FLAG_WOKE_HERE;
5077 }
5078 if (screenIsDim) {
5079 event.flags |= WindowManagerPolicy.FLAG_BRIGHT_HERE;
5080 }
5081 return true;
5082 }
Romain Guy06882f82009-06-10 13:36:04 -07005083
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005084 default:
5085 return true;
5086 }
5087 }
5088
5089 public int filterEvent(QueuedEvent ev) {
5090 switch (ev.classType) {
5091 case RawInputEvent.CLASS_KEYBOARD:
5092 KeyEvent ke = (KeyEvent)ev.event;
5093 if (mPolicy.isMovementKeyTi(ke.getKeyCode())) {
5094 Log.w(TAG, "Dropping movement key during app switch: "
5095 + ke.getKeyCode() + ", action=" + ke.getAction());
5096 return FILTER_REMOVE;
5097 }
5098 return FILTER_ABORT;
5099 default:
5100 return FILTER_KEEP;
5101 }
5102 }
Romain Guy06882f82009-06-10 13:36:04 -07005103
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005104 /**
5105 * Must be called with the main window manager lock held.
5106 */
5107 void setHoldScreenLocked(boolean holding) {
5108 boolean state = mHoldingScreen.isHeld();
5109 if (holding != state) {
5110 if (holding) {
5111 mHoldingScreen.acquire();
5112 } else {
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07005113 mPolicy.screenOnStoppedLw();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005114 mHoldingScreen.release();
5115 }
5116 }
5117 }
5118 };
5119
5120 public boolean detectSafeMode() {
5121 mSafeMode = mPolicy.detectSafeMode();
5122 return mSafeMode;
5123 }
Romain Guy06882f82009-06-10 13:36:04 -07005124
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005125 public void systemReady() {
5126 mPolicy.systemReady();
5127 }
Romain Guy06882f82009-06-10 13:36:04 -07005128
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005129 private final class InputDispatcherThread extends Thread {
5130 // Time to wait when there is nothing to do: 9999 seconds.
5131 static final int LONG_WAIT=9999*1000;
5132
5133 public InputDispatcherThread() {
5134 super("InputDispatcher");
5135 }
Romain Guy06882f82009-06-10 13:36:04 -07005136
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005137 @Override
5138 public void run() {
5139 while (true) {
5140 try {
5141 process();
5142 } catch (Exception e) {
5143 Log.e(TAG, "Exception in input dispatcher", e);
5144 }
5145 }
5146 }
Romain Guy06882f82009-06-10 13:36:04 -07005147
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005148 private void process() {
5149 android.os.Process.setThreadPriority(
5150 android.os.Process.THREAD_PRIORITY_URGENT_DISPLAY);
Romain Guy06882f82009-06-10 13:36:04 -07005151
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005152 // The last key event we saw
5153 KeyEvent lastKey = null;
5154
5155 // Last keydown time for auto-repeating keys
5156 long lastKeyTime = SystemClock.uptimeMillis();
5157 long nextKeyTime = lastKeyTime+LONG_WAIT;
5158
Romain Guy06882f82009-06-10 13:36:04 -07005159 // How many successive repeats we generated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005160 int keyRepeatCount = 0;
5161
5162 // Need to report that configuration has changed?
5163 boolean configChanged = false;
Romain Guy06882f82009-06-10 13:36:04 -07005164
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005165 while (true) {
5166 long curTime = SystemClock.uptimeMillis();
5167
5168 if (DEBUG_INPUT) Log.v(
5169 TAG, "Waiting for next key: now=" + curTime
5170 + ", repeat @ " + nextKeyTime);
5171
5172 // Retrieve next event, waiting only as long as the next
5173 // repeat timeout. If the configuration has changed, then
5174 // don't wait at all -- we'll report the change as soon as
5175 // we have processed all events.
5176 QueuedEvent ev = mQueue.getEvent(
5177 (int)((!configChanged && curTime < nextKeyTime)
5178 ? (nextKeyTime-curTime) : 0));
5179
5180 if (DEBUG_INPUT && ev != null) Log.v(
5181 TAG, "Event: type=" + ev.classType + " data=" + ev.event);
5182
5183 try {
5184 if (ev != null) {
5185 curTime = ev.when;
5186 int eventType;
5187 if (ev.classType == RawInputEvent.CLASS_TOUCHSCREEN) {
5188 eventType = eventType((MotionEvent)ev.event);
5189 } else if (ev.classType == RawInputEvent.CLASS_KEYBOARD ||
5190 ev.classType == RawInputEvent.CLASS_TRACKBALL) {
5191 eventType = LocalPowerManager.BUTTON_EVENT;
5192 } else {
5193 eventType = LocalPowerManager.OTHER_EVENT;
5194 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07005195 try {
Michael Chane96440f2009-05-06 10:27:36 -07005196 long now = SystemClock.uptimeMillis();
5197
5198 if ((now - mLastBatteryStatsCallTime)
5199 >= MIN_TIME_BETWEEN_USERACTIVITIES) {
5200 mLastBatteryStatsCallTime = now;
5201 mBatteryStats.noteInputEvent();
5202 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07005203 } catch (RemoteException e) {
5204 // Ignore
5205 }
Michael Chane96440f2009-05-06 10:27:36 -07005206 mPowerManager.userActivity(curTime, false, eventType, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005207 switch (ev.classType) {
5208 case RawInputEvent.CLASS_KEYBOARD:
5209 KeyEvent ke = (KeyEvent)ev.event;
5210 if (ke.isDown()) {
5211 lastKey = ke;
5212 keyRepeatCount = 0;
5213 lastKeyTime = curTime;
5214 nextKeyTime = lastKeyTime
5215 + KEY_REPEAT_FIRST_DELAY;
5216 if (DEBUG_INPUT) Log.v(
5217 TAG, "Received key down: first repeat @ "
5218 + nextKeyTime);
5219 } else {
5220 lastKey = null;
5221 // Arbitrary long timeout.
5222 lastKeyTime = curTime;
5223 nextKeyTime = curTime + LONG_WAIT;
5224 if (DEBUG_INPUT) Log.v(
5225 TAG, "Received key up: ignore repeat @ "
5226 + nextKeyTime);
5227 }
5228 dispatchKey((KeyEvent)ev.event, 0, 0);
5229 mQueue.recycleEvent(ev);
5230 break;
5231 case RawInputEvent.CLASS_TOUCHSCREEN:
5232 //Log.i(TAG, "Read next event " + ev);
5233 dispatchPointer(ev, (MotionEvent)ev.event, 0, 0);
5234 break;
5235 case RawInputEvent.CLASS_TRACKBALL:
5236 dispatchTrackball(ev, (MotionEvent)ev.event, 0, 0);
5237 break;
5238 case RawInputEvent.CLASS_CONFIGURATION_CHANGED:
5239 configChanged = true;
5240 break;
5241 default:
5242 mQueue.recycleEvent(ev);
5243 break;
5244 }
Romain Guy06882f82009-06-10 13:36:04 -07005245
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005246 } else if (configChanged) {
5247 configChanged = false;
5248 sendNewConfiguration();
Romain Guy06882f82009-06-10 13:36:04 -07005249
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005250 } else if (lastKey != null) {
5251 curTime = SystemClock.uptimeMillis();
Romain Guy06882f82009-06-10 13:36:04 -07005252
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005253 // Timeout occurred while key was down. If it is at or
5254 // past the key repeat time, dispatch the repeat.
5255 if (DEBUG_INPUT) Log.v(
5256 TAG, "Key timeout: repeat=" + nextKeyTime
5257 + ", now=" + curTime);
5258 if (curTime < nextKeyTime) {
5259 continue;
5260 }
Romain Guy06882f82009-06-10 13:36:04 -07005261
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005262 lastKeyTime = nextKeyTime;
5263 nextKeyTime = nextKeyTime + KEY_REPEAT_DELAY;
5264 keyRepeatCount++;
5265 if (DEBUG_INPUT) Log.v(
5266 TAG, "Key repeat: count=" + keyRepeatCount
5267 + ", next @ " + nextKeyTime);
The Android Open Source Project10592532009-03-18 17:39:46 -07005268 dispatchKey(KeyEvent.changeTimeRepeat(lastKey, curTime, keyRepeatCount), 0, 0);
Romain Guy06882f82009-06-10 13:36:04 -07005269
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005270 } else {
5271 curTime = SystemClock.uptimeMillis();
Romain Guy06882f82009-06-10 13:36:04 -07005272
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005273 lastKeyTime = curTime;
5274 nextKeyTime = curTime + LONG_WAIT;
5275 }
Romain Guy06882f82009-06-10 13:36:04 -07005276
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005277 } catch (Exception e) {
5278 Log.e(TAG,
5279 "Input thread received uncaught exception: " + e, e);
5280 }
5281 }
5282 }
5283 }
5284
5285 // -------------------------------------------------------------
5286 // Client Session State
5287 // -------------------------------------------------------------
5288
5289 private final class Session extends IWindowSession.Stub
5290 implements IBinder.DeathRecipient {
5291 final IInputMethodClient mClient;
5292 final IInputContext mInputContext;
5293 final int mUid;
5294 final int mPid;
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005295 final String mStringName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005296 SurfaceSession mSurfaceSession;
5297 int mNumWindow = 0;
5298 boolean mClientDead = false;
Romain Guy06882f82009-06-10 13:36:04 -07005299
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005300 /**
5301 * Current pointer move event being dispatched to client window... must
5302 * hold key lock to access.
5303 */
5304 QueuedEvent mPendingPointerMove;
5305 WindowState mPendingPointerWindow;
Romain Guy06882f82009-06-10 13:36:04 -07005306
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005307 /**
5308 * Current trackball move event being dispatched to client window... must
5309 * hold key lock to access.
5310 */
5311 QueuedEvent mPendingTrackballMove;
5312 WindowState mPendingTrackballWindow;
5313
5314 public Session(IInputMethodClient client, IInputContext inputContext) {
5315 mClient = client;
5316 mInputContext = inputContext;
5317 mUid = Binder.getCallingUid();
5318 mPid = Binder.getCallingPid();
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005319 StringBuilder sb = new StringBuilder();
5320 sb.append("Session{");
5321 sb.append(Integer.toHexString(System.identityHashCode(this)));
5322 sb.append(" uid ");
5323 sb.append(mUid);
5324 sb.append("}");
5325 mStringName = sb.toString();
Romain Guy06882f82009-06-10 13:36:04 -07005326
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005327 synchronized (mWindowMap) {
5328 if (mInputMethodManager == null && mHaveInputMethods) {
5329 IBinder b = ServiceManager.getService(
5330 Context.INPUT_METHOD_SERVICE);
5331 mInputMethodManager = IInputMethodManager.Stub.asInterface(b);
5332 }
5333 }
5334 long ident = Binder.clearCallingIdentity();
5335 try {
5336 // Note: it is safe to call in to the input method manager
5337 // here because we are not holding our lock.
5338 if (mInputMethodManager != null) {
5339 mInputMethodManager.addClient(client, inputContext,
5340 mUid, mPid);
5341 } else {
5342 client.setUsingInputMethod(false);
5343 }
5344 client.asBinder().linkToDeath(this, 0);
5345 } catch (RemoteException e) {
5346 // The caller has died, so we can just forget about this.
5347 try {
5348 if (mInputMethodManager != null) {
5349 mInputMethodManager.removeClient(client);
5350 }
5351 } catch (RemoteException ee) {
5352 }
5353 } finally {
5354 Binder.restoreCallingIdentity(ident);
5355 }
5356 }
Romain Guy06882f82009-06-10 13:36:04 -07005357
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005358 @Override
5359 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
5360 throws RemoteException {
5361 try {
5362 return super.onTransact(code, data, reply, flags);
5363 } catch (RuntimeException e) {
5364 // Log all 'real' exceptions thrown to the caller
5365 if (!(e instanceof SecurityException)) {
5366 Log.e(TAG, "Window Session Crash", e);
5367 }
5368 throw e;
5369 }
5370 }
5371
5372 public void binderDied() {
5373 // Note: it is safe to call in to the input method manager
5374 // here because we are not holding our lock.
5375 try {
5376 if (mInputMethodManager != null) {
5377 mInputMethodManager.removeClient(mClient);
5378 }
5379 } catch (RemoteException e) {
5380 }
5381 synchronized(mWindowMap) {
5382 mClientDead = true;
5383 killSessionLocked();
5384 }
5385 }
5386
5387 public int add(IWindow window, WindowManager.LayoutParams attrs,
5388 int viewVisibility, Rect outContentInsets) {
5389 return addWindow(this, window, attrs, viewVisibility, outContentInsets);
5390 }
Romain Guy06882f82009-06-10 13:36:04 -07005391
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005392 public void remove(IWindow window) {
5393 removeWindow(this, window);
5394 }
Romain Guy06882f82009-06-10 13:36:04 -07005395
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005396 public int relayout(IWindow window, WindowManager.LayoutParams attrs,
5397 int requestedWidth, int requestedHeight, int viewFlags,
5398 boolean insetsPending, Rect outFrame, Rect outContentInsets,
5399 Rect outVisibleInsets, Surface outSurface) {
5400 return relayoutWindow(this, window, attrs,
5401 requestedWidth, requestedHeight, viewFlags, insetsPending,
5402 outFrame, outContentInsets, outVisibleInsets, outSurface);
5403 }
Romain Guy06882f82009-06-10 13:36:04 -07005404
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005405 public void setTransparentRegion(IWindow window, Region region) {
5406 setTransparentRegionWindow(this, window, region);
5407 }
Romain Guy06882f82009-06-10 13:36:04 -07005408
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005409 public void setInsets(IWindow window, int touchableInsets,
5410 Rect contentInsets, Rect visibleInsets) {
5411 setInsetsWindow(this, window, touchableInsets, contentInsets,
5412 visibleInsets);
5413 }
Romain Guy06882f82009-06-10 13:36:04 -07005414
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005415 public void getDisplayFrame(IWindow window, Rect outDisplayFrame) {
5416 getWindowDisplayFrame(this, window, outDisplayFrame);
5417 }
Romain Guy06882f82009-06-10 13:36:04 -07005418
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005419 public void finishDrawing(IWindow window) {
5420 if (localLOGV) Log.v(
5421 TAG, "IWindow finishDrawing called for " + window);
5422 finishDrawingWindow(this, window);
5423 }
5424
5425 public void finishKey(IWindow window) {
5426 if (localLOGV) Log.v(
5427 TAG, "IWindow finishKey called for " + window);
5428 mKeyWaiter.finishedKey(this, window, false,
5429 KeyWaiter.RETURN_NOTHING);
5430 }
5431
5432 public MotionEvent getPendingPointerMove(IWindow window) {
5433 if (localLOGV) Log.v(
5434 TAG, "IWindow getPendingMotionEvent called for " + window);
5435 return mKeyWaiter.finishedKey(this, window, false,
5436 KeyWaiter.RETURN_PENDING_POINTER);
5437 }
Romain Guy06882f82009-06-10 13:36:04 -07005438
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005439 public MotionEvent getPendingTrackballMove(IWindow window) {
5440 if (localLOGV) Log.v(
5441 TAG, "IWindow getPendingMotionEvent called for " + window);
5442 return mKeyWaiter.finishedKey(this, window, false,
5443 KeyWaiter.RETURN_PENDING_TRACKBALL);
5444 }
5445
5446 public void setInTouchMode(boolean mode) {
5447 synchronized(mWindowMap) {
5448 mInTouchMode = mode;
5449 }
5450 }
5451
5452 public boolean getInTouchMode() {
5453 synchronized(mWindowMap) {
5454 return mInTouchMode;
5455 }
5456 }
5457
5458 public boolean performHapticFeedback(IWindow window, int effectId,
5459 boolean always) {
5460 synchronized(mWindowMap) {
5461 long ident = Binder.clearCallingIdentity();
5462 try {
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07005463 return mPolicy.performHapticFeedbackLw(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005464 windowForClientLocked(this, window), effectId, always);
5465 } finally {
5466 Binder.restoreCallingIdentity(ident);
5467 }
5468 }
5469 }
Romain Guy06882f82009-06-10 13:36:04 -07005470
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005471 void windowAddedLocked() {
5472 if (mSurfaceSession == null) {
5473 if (localLOGV) Log.v(
5474 TAG, "First window added to " + this + ", creating SurfaceSession");
5475 mSurfaceSession = new SurfaceSession();
5476 mSessions.add(this);
5477 }
5478 mNumWindow++;
5479 }
5480
5481 void windowRemovedLocked() {
5482 mNumWindow--;
5483 killSessionLocked();
5484 }
Romain Guy06882f82009-06-10 13:36:04 -07005485
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005486 void killSessionLocked() {
5487 if (mNumWindow <= 0 && mClientDead) {
5488 mSessions.remove(this);
5489 if (mSurfaceSession != null) {
5490 if (localLOGV) Log.v(
5491 TAG, "Last window removed from " + this
5492 + ", destroying " + mSurfaceSession);
5493 try {
5494 mSurfaceSession.kill();
5495 } catch (Exception e) {
5496 Log.w(TAG, "Exception thrown when killing surface session "
5497 + mSurfaceSession + " in session " + this
5498 + ": " + e.toString());
5499 }
5500 mSurfaceSession = null;
5501 }
5502 }
5503 }
Romain Guy06882f82009-06-10 13:36:04 -07005504
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005505 void dump(PrintWriter pw, String prefix) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005506 pw.print(prefix); pw.print("mNumWindow="); pw.print(mNumWindow);
5507 pw.print(" mClientDead="); pw.print(mClientDead);
5508 pw.print(" mSurfaceSession="); pw.println(mSurfaceSession);
5509 if (mPendingPointerWindow != null || mPendingPointerMove != null) {
5510 pw.print(prefix);
5511 pw.print("mPendingPointerWindow="); pw.print(mPendingPointerWindow);
5512 pw.print(" mPendingPointerMove="); pw.println(mPendingPointerMove);
5513 }
5514 if (mPendingTrackballWindow != null || mPendingTrackballMove != null) {
5515 pw.print(prefix);
5516 pw.print("mPendingTrackballWindow="); pw.print(mPendingTrackballWindow);
5517 pw.print(" mPendingTrackballMove="); pw.println(mPendingTrackballMove);
5518 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005519 }
5520
5521 @Override
5522 public String toString() {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005523 return mStringName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005524 }
5525 }
5526
5527 // -------------------------------------------------------------
5528 // Client Window State
5529 // -------------------------------------------------------------
5530
5531 private final class WindowState implements WindowManagerPolicy.WindowState {
5532 final Session mSession;
5533 final IWindow mClient;
5534 WindowToken mToken;
The Android Open Source Project10592532009-03-18 17:39:46 -07005535 WindowToken mRootToken;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005536 AppWindowToken mAppToken;
5537 AppWindowToken mTargetAppToken;
5538 final WindowManager.LayoutParams mAttrs = new WindowManager.LayoutParams();
5539 final DeathRecipient mDeathRecipient;
5540 final WindowState mAttachedWindow;
5541 final ArrayList mChildWindows = new ArrayList();
5542 final int mBaseLayer;
5543 final int mSubLayer;
5544 final boolean mLayoutAttached;
5545 final boolean mIsImWindow;
5546 int mViewVisibility;
5547 boolean mPolicyVisibility = true;
5548 boolean mPolicyVisibilityAfterAnim = true;
5549 boolean mAppFreezing;
5550 Surface mSurface;
5551 boolean mAttachedHidden; // is our parent window hidden?
5552 boolean mLastHidden; // was this window last hidden?
5553 int mRequestedWidth;
5554 int mRequestedHeight;
5555 int mLastRequestedWidth;
5556 int mLastRequestedHeight;
5557 int mReqXPos;
5558 int mReqYPos;
5559 int mLayer;
5560 int mAnimLayer;
5561 int mLastLayer;
5562 boolean mHaveFrame;
5563
5564 WindowState mNextOutsideTouch;
Romain Guy06882f82009-06-10 13:36:04 -07005565
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005566 // Actual frame shown on-screen (may be modified by animation)
5567 final Rect mShownFrame = new Rect();
5568 final Rect mLastShownFrame = new Rect();
Romain Guy06882f82009-06-10 13:36:04 -07005569
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005570 /**
5571 * Insets that determine the actually visible area
5572 */
5573 final Rect mVisibleInsets = new Rect();
5574 final Rect mLastVisibleInsets = new Rect();
5575 boolean mVisibleInsetsChanged;
5576
5577 /**
5578 * Insets that are covered by system windows
5579 */
5580 final Rect mContentInsets = new Rect();
5581 final Rect mLastContentInsets = new Rect();
5582 boolean mContentInsetsChanged;
5583
5584 /**
5585 * Set to true if we are waiting for this window to receive its
5586 * given internal insets before laying out other windows based on it.
5587 */
5588 boolean mGivenInsetsPending;
Romain Guy06882f82009-06-10 13:36:04 -07005589
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005590 /**
5591 * These are the content insets that were given during layout for
5592 * this window, to be applied to windows behind it.
5593 */
5594 final Rect mGivenContentInsets = new Rect();
Romain Guy06882f82009-06-10 13:36:04 -07005595
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005596 /**
5597 * These are the visible insets that were given during layout for
5598 * this window, to be applied to windows behind it.
5599 */
5600 final Rect mGivenVisibleInsets = new Rect();
Romain Guy06882f82009-06-10 13:36:04 -07005601
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005602 /**
5603 * Flag indicating whether the touchable region should be adjusted by
5604 * the visible insets; if false the area outside the visible insets is
5605 * NOT touchable, so we must use those to adjust the frame during hit
5606 * tests.
5607 */
5608 int mTouchableInsets = ViewTreeObserver.InternalInsetsInfo.TOUCHABLE_INSETS_FRAME;
Romain Guy06882f82009-06-10 13:36:04 -07005609
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005610 // Current transformation being applied.
5611 float mDsDx=1, mDtDx=0, mDsDy=0, mDtDy=1;
5612 float mLastDsDx=1, mLastDtDx=0, mLastDsDy=0, mLastDtDy=1;
5613 float mHScale=1, mVScale=1;
5614 float mLastHScale=1, mLastVScale=1;
5615 final Matrix mTmpMatrix = new Matrix();
5616
5617 // "Real" frame that the application sees.
5618 final Rect mFrame = new Rect();
5619 final Rect mLastFrame = new Rect();
5620
5621 final Rect mContainingFrame = new Rect();
5622 final Rect mDisplayFrame = new Rect();
5623 final Rect mContentFrame = new Rect();
5624 final Rect mVisibleFrame = new Rect();
5625
5626 float mShownAlpha = 1;
5627 float mAlpha = 1;
5628 float mLastAlpha = 1;
5629
5630 // Set to true if, when the window gets displayed, it should perform
5631 // an enter animation.
5632 boolean mEnterAnimationPending;
5633
5634 // Currently running animation.
5635 boolean mAnimating;
5636 boolean mLocalAnimating;
5637 Animation mAnimation;
5638 boolean mAnimationIsEntrance;
5639 boolean mHasTransformation;
5640 boolean mHasLocalTransformation;
5641 final Transformation mTransformation = new Transformation();
5642
5643 // This is set after IWindowSession.relayout() has been called at
5644 // least once for the window. It allows us to detect the situation
5645 // where we don't yet have a surface, but should have one soon, so
5646 // we can give the window focus before waiting for the relayout.
5647 boolean mRelayoutCalled;
Romain Guy06882f82009-06-10 13:36:04 -07005648
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005649 // This is set after the Surface has been created but before the
5650 // window has been drawn. During this time the surface is hidden.
5651 boolean mDrawPending;
5652
5653 // This is set after the window has finished drawing for the first
5654 // time but before its surface is shown. The surface will be
5655 // displayed when the next layout is run.
5656 boolean mCommitDrawPending;
5657
5658 // This is set during the time after the window's drawing has been
5659 // committed, and before its surface is actually shown. It is used
5660 // to delay showing the surface until all windows in a token are ready
5661 // to be shown.
5662 boolean mReadyToShow;
Romain Guy06882f82009-06-10 13:36:04 -07005663
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005664 // Set when the window has been shown in the screen the first time.
5665 boolean mHasDrawn;
5666
5667 // Currently running an exit animation?
5668 boolean mExiting;
5669
5670 // Currently on the mDestroySurface list?
5671 boolean mDestroying;
Romain Guy06882f82009-06-10 13:36:04 -07005672
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005673 // Completely remove from window manager after exit animation?
5674 boolean mRemoveOnExit;
5675
5676 // Set when the orientation is changing and this window has not yet
5677 // been updated for the new orientation.
5678 boolean mOrientationChanging;
Romain Guy06882f82009-06-10 13:36:04 -07005679
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005680 // Is this window now (or just being) removed?
5681 boolean mRemoved;
Romain Guy06882f82009-06-10 13:36:04 -07005682
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005683 WindowState(Session s, IWindow c, WindowToken token,
5684 WindowState attachedWindow, WindowManager.LayoutParams a,
5685 int viewVisibility) {
5686 mSession = s;
5687 mClient = c;
5688 mToken = token;
5689 mAttrs.copyFrom(a);
5690 mViewVisibility = viewVisibility;
5691 DeathRecipient deathRecipient = new DeathRecipient();
5692 mAlpha = a.alpha;
5693 if (localLOGV) Log.v(
5694 TAG, "Window " + this + " client=" + c.asBinder()
5695 + " token=" + token + " (" + mAttrs.token + ")");
5696 try {
5697 c.asBinder().linkToDeath(deathRecipient, 0);
5698 } catch (RemoteException e) {
5699 mDeathRecipient = null;
5700 mAttachedWindow = null;
5701 mLayoutAttached = false;
5702 mIsImWindow = false;
5703 mBaseLayer = 0;
5704 mSubLayer = 0;
5705 return;
5706 }
5707 mDeathRecipient = deathRecipient;
Romain Guy06882f82009-06-10 13:36:04 -07005708
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005709 if ((mAttrs.type >= FIRST_SUB_WINDOW &&
5710 mAttrs.type <= LAST_SUB_WINDOW)) {
5711 // The multiplier here is to reserve space for multiple
5712 // windows in the same type layer.
5713 mBaseLayer = mPolicy.windowTypeToLayerLw(
5714 attachedWindow.mAttrs.type) * TYPE_LAYER_MULTIPLIER
5715 + TYPE_LAYER_OFFSET;
5716 mSubLayer = mPolicy.subWindowTypeToLayerLw(a.type);
5717 mAttachedWindow = attachedWindow;
5718 mAttachedWindow.mChildWindows.add(this);
5719 mLayoutAttached = mAttrs.type !=
5720 WindowManager.LayoutParams.TYPE_APPLICATION_ATTACHED_DIALOG;
5721 mIsImWindow = attachedWindow.mAttrs.type == TYPE_INPUT_METHOD
5722 || attachedWindow.mAttrs.type == TYPE_INPUT_METHOD_DIALOG;
5723 } else {
5724 // The multiplier here is to reserve space for multiple
5725 // windows in the same type layer.
5726 mBaseLayer = mPolicy.windowTypeToLayerLw(a.type)
5727 * TYPE_LAYER_MULTIPLIER
5728 + TYPE_LAYER_OFFSET;
5729 mSubLayer = 0;
5730 mAttachedWindow = null;
5731 mLayoutAttached = false;
5732 mIsImWindow = mAttrs.type == TYPE_INPUT_METHOD
5733 || mAttrs.type == TYPE_INPUT_METHOD_DIALOG;
5734 }
5735
5736 WindowState appWin = this;
5737 while (appWin.mAttachedWindow != null) {
5738 appWin = mAttachedWindow;
5739 }
5740 WindowToken appToken = appWin.mToken;
5741 while (appToken.appWindowToken == null) {
5742 WindowToken parent = mTokenMap.get(appToken.token);
5743 if (parent == null || appToken == parent) {
5744 break;
5745 }
5746 appToken = parent;
5747 }
The Android Open Source Project10592532009-03-18 17:39:46 -07005748 mRootToken = appToken;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005749 mAppToken = appToken.appWindowToken;
5750
5751 mSurface = null;
5752 mRequestedWidth = 0;
5753 mRequestedHeight = 0;
5754 mLastRequestedWidth = 0;
5755 mLastRequestedHeight = 0;
5756 mReqXPos = 0;
5757 mReqYPos = 0;
5758 mLayer = 0;
5759 mAnimLayer = 0;
5760 mLastLayer = 0;
5761 }
5762
5763 void attach() {
5764 if (localLOGV) Log.v(
5765 TAG, "Attaching " + this + " token=" + mToken
5766 + ", list=" + mToken.windows);
5767 mSession.windowAddedLocked();
5768 }
5769
5770 public void computeFrameLw(Rect pf, Rect df, Rect cf, Rect vf) {
5771 mHaveFrame = true;
5772
5773 final int pw = pf.right-pf.left;
5774 final int ph = pf.bottom-pf.top;
5775
5776 int w,h;
5777 if ((mAttrs.flags & mAttrs.FLAG_SCALED) != 0) {
5778 w = mAttrs.width < 0 ? pw : mAttrs.width;
5779 h = mAttrs.height< 0 ? ph : mAttrs.height;
5780 } else {
5781 w = mAttrs.width == mAttrs.FILL_PARENT ? pw : mRequestedWidth;
5782 h = mAttrs.height== mAttrs.FILL_PARENT ? ph : mRequestedHeight;
5783 }
Romain Guy06882f82009-06-10 13:36:04 -07005784
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005785 final Rect container = mContainingFrame;
5786 container.set(pf);
5787
5788 final Rect display = mDisplayFrame;
5789 display.set(df);
5790
5791 final Rect content = mContentFrame;
5792 content.set(cf);
Romain Guy06882f82009-06-10 13:36:04 -07005793
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005794 final Rect visible = mVisibleFrame;
5795 visible.set(vf);
Romain Guy06882f82009-06-10 13:36:04 -07005796
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005797 final Rect frame = mFrame;
Romain Guy06882f82009-06-10 13:36:04 -07005798
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005799 //System.out.println("In: w=" + w + " h=" + h + " container=" +
5800 // container + " x=" + mAttrs.x + " y=" + mAttrs.y);
5801
5802 Gravity.apply(mAttrs.gravity, w, h, container,
5803 (int) (mAttrs.x + mAttrs.horizontalMargin * pw),
5804 (int) (mAttrs.y + mAttrs.verticalMargin * ph), frame);
5805
5806 //System.out.println("Out: " + mFrame);
5807
5808 // Now make sure the window fits in the overall display.
5809 Gravity.applyDisplay(mAttrs.gravity, df, frame);
Romain Guy06882f82009-06-10 13:36:04 -07005810
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005811 // Make sure the content and visible frames are inside of the
5812 // final window frame.
5813 if (content.left < frame.left) content.left = frame.left;
5814 if (content.top < frame.top) content.top = frame.top;
5815 if (content.right > frame.right) content.right = frame.right;
5816 if (content.bottom > frame.bottom) content.bottom = frame.bottom;
5817 if (visible.left < frame.left) visible.left = frame.left;
5818 if (visible.top < frame.top) visible.top = frame.top;
5819 if (visible.right > frame.right) visible.right = frame.right;
5820 if (visible.bottom > frame.bottom) visible.bottom = frame.bottom;
Romain Guy06882f82009-06-10 13:36:04 -07005821
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005822 final Rect contentInsets = mContentInsets;
5823 contentInsets.left = content.left-frame.left;
5824 contentInsets.top = content.top-frame.top;
5825 contentInsets.right = frame.right-content.right;
5826 contentInsets.bottom = frame.bottom-content.bottom;
Romain Guy06882f82009-06-10 13:36:04 -07005827
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005828 final Rect visibleInsets = mVisibleInsets;
5829 visibleInsets.left = visible.left-frame.left;
5830 visibleInsets.top = visible.top-frame.top;
5831 visibleInsets.right = frame.right-visible.right;
5832 visibleInsets.bottom = frame.bottom-visible.bottom;
Romain Guy06882f82009-06-10 13:36:04 -07005833
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005834 if (localLOGV) {
5835 //if ("com.google.android.youtube".equals(mAttrs.packageName)
5836 // && mAttrs.type == WindowManager.LayoutParams.TYPE_APPLICATION_PANEL) {
5837 Log.v(TAG, "Resolving (mRequestedWidth="
5838 + mRequestedWidth + ", mRequestedheight="
5839 + mRequestedHeight + ") to" + " (pw=" + pw + ", ph=" + ph
5840 + "): frame=" + mFrame.toShortString()
5841 + " ci=" + contentInsets.toShortString()
5842 + " vi=" + visibleInsets.toShortString());
5843 //}
5844 }
5845 }
Romain Guy06882f82009-06-10 13:36:04 -07005846
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005847 public Rect getFrameLw() {
5848 return mFrame;
5849 }
5850
5851 public Rect getShownFrameLw() {
5852 return mShownFrame;
5853 }
5854
5855 public Rect getDisplayFrameLw() {
5856 return mDisplayFrame;
5857 }
5858
5859 public Rect getContentFrameLw() {
5860 return mContentFrame;
5861 }
5862
5863 public Rect getVisibleFrameLw() {
5864 return mVisibleFrame;
5865 }
5866
5867 public boolean getGivenInsetsPendingLw() {
5868 return mGivenInsetsPending;
5869 }
5870
5871 public Rect getGivenContentInsetsLw() {
5872 return mGivenContentInsets;
5873 }
Romain Guy06882f82009-06-10 13:36:04 -07005874
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005875 public Rect getGivenVisibleInsetsLw() {
5876 return mGivenVisibleInsets;
5877 }
Romain Guy06882f82009-06-10 13:36:04 -07005878
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005879 public WindowManager.LayoutParams getAttrs() {
5880 return mAttrs;
5881 }
5882
5883 public int getSurfaceLayer() {
5884 return mLayer;
5885 }
Romain Guy06882f82009-06-10 13:36:04 -07005886
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005887 public IApplicationToken getAppToken() {
5888 return mAppToken != null ? mAppToken.appToken : null;
5889 }
5890
5891 public boolean hasAppShownWindows() {
5892 return mAppToken != null ? mAppToken.firstWindowDrawn : false;
5893 }
5894
5895 public boolean hasAppStartingIcon() {
5896 return mAppToken != null ? (mAppToken.startingData != null) : false;
5897 }
5898
5899 public WindowManagerPolicy.WindowState getAppStartingWindow() {
5900 return mAppToken != null ? mAppToken.startingWindow : null;
5901 }
5902
5903 public void setAnimation(Animation anim) {
5904 if (localLOGV) Log.v(
5905 TAG, "Setting animation in " + this + ": " + anim);
5906 mAnimating = false;
5907 mLocalAnimating = false;
5908 mAnimation = anim;
5909 mAnimation.restrictDuration(MAX_ANIMATION_DURATION);
5910 mAnimation.scaleCurrentDuration(mWindowAnimationScale);
5911 }
5912
5913 public void clearAnimation() {
5914 if (mAnimation != null) {
5915 mAnimating = true;
5916 mLocalAnimating = false;
5917 mAnimation = null;
5918 }
5919 }
Romain Guy06882f82009-06-10 13:36:04 -07005920
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005921 Surface createSurfaceLocked() {
5922 if (mSurface == null) {
5923 mDrawPending = true;
5924 mCommitDrawPending = false;
5925 mReadyToShow = false;
5926 if (mAppToken != null) {
5927 mAppToken.allDrawn = false;
5928 }
5929
5930 int flags = 0;
5931 if (mAttrs.memoryType == MEMORY_TYPE_HARDWARE) {
5932 flags |= Surface.HARDWARE;
5933 } else if (mAttrs.memoryType == MEMORY_TYPE_GPU) {
5934 flags |= Surface.GPU;
5935 } else if (mAttrs.memoryType == MEMORY_TYPE_PUSH_BUFFERS) {
5936 flags |= Surface.PUSH_BUFFERS;
5937 }
5938
5939 if ((mAttrs.flags&WindowManager.LayoutParams.FLAG_SECURE) != 0) {
5940 flags |= Surface.SECURE;
5941 }
5942 if (DEBUG_VISIBILITY) Log.v(
5943 TAG, "Creating surface in session "
5944 + mSession.mSurfaceSession + " window " + this
5945 + " w=" + mFrame.width()
5946 + " h=" + mFrame.height() + " format="
5947 + mAttrs.format + " flags=" + flags);
5948
5949 int w = mFrame.width();
5950 int h = mFrame.height();
5951 if ((mAttrs.flags & LayoutParams.FLAG_SCALED) != 0) {
5952 // for a scaled surface, we always want the requested
5953 // size.
5954 w = mRequestedWidth;
5955 h = mRequestedHeight;
5956 }
5957
5958 try {
5959 mSurface = new Surface(
Romain Guy06882f82009-06-10 13:36:04 -07005960 mSession.mSurfaceSession, mSession.mPid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005961 0, w, h, mAttrs.format, flags);
5962 } catch (Surface.OutOfResourcesException e) {
5963 Log.w(TAG, "OutOfResourcesException creating surface");
5964 reclaimSomeSurfaceMemoryLocked(this, "create");
5965 return null;
5966 } catch (Exception e) {
5967 Log.e(TAG, "Exception creating surface", e);
5968 return null;
5969 }
Romain Guy06882f82009-06-10 13:36:04 -07005970
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005971 if (localLOGV) Log.v(
5972 TAG, "Got surface: " + mSurface
5973 + ", set left=" + mFrame.left + " top=" + mFrame.top
5974 + ", animLayer=" + mAnimLayer);
5975 if (SHOW_TRANSACTIONS) {
5976 Log.i(TAG, ">>> OPEN TRANSACTION");
5977 Log.i(TAG, " SURFACE " + mSurface + ": CREATE ("
5978 + mAttrs.getTitle() + ") pos=(" +
5979 mFrame.left + "," + mFrame.top + ") (" +
5980 mFrame.width() + "x" + mFrame.height() + "), layer=" +
5981 mAnimLayer + " HIDE");
5982 }
5983 Surface.openTransaction();
5984 try {
5985 try {
5986 mSurface.setPosition(mFrame.left, mFrame.top);
5987 mSurface.setLayer(mAnimLayer);
5988 mSurface.hide();
5989 if ((mAttrs.flags&WindowManager.LayoutParams.FLAG_DITHER) != 0) {
5990 mSurface.setFlags(Surface.SURFACE_DITHER,
5991 Surface.SURFACE_DITHER);
5992 }
5993 } catch (RuntimeException e) {
5994 Log.w(TAG, "Error creating surface in " + w, e);
5995 reclaimSomeSurfaceMemoryLocked(this, "create-init");
5996 }
5997 mLastHidden = true;
5998 } finally {
5999 if (SHOW_TRANSACTIONS) Log.i(TAG, "<<< CLOSE TRANSACTION");
6000 Surface.closeTransaction();
6001 }
6002 if (localLOGV) Log.v(
6003 TAG, "Created surface " + this);
6004 }
6005 return mSurface;
6006 }
Romain Guy06882f82009-06-10 13:36:04 -07006007
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006008 void destroySurfaceLocked() {
6009 // Window is no longer on-screen, so can no longer receive
6010 // key events... if we were waiting for it to finish
6011 // handling a key event, the wait is over!
6012 mKeyWaiter.finishedKey(mSession, mClient, true,
6013 KeyWaiter.RETURN_NOTHING);
6014 mKeyWaiter.releasePendingPointerLocked(mSession);
6015 mKeyWaiter.releasePendingTrackballLocked(mSession);
6016
6017 if (mAppToken != null && this == mAppToken.startingWindow) {
6018 mAppToken.startingDisplayed = false;
6019 }
Romain Guy06882f82009-06-10 13:36:04 -07006020
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006021 if (localLOGV) Log.v(
6022 TAG, "Window " + this
6023 + " destroying surface " + mSurface + ", session " + mSession);
6024 if (mSurface != null) {
6025 try {
6026 if (SHOW_TRANSACTIONS) {
6027 RuntimeException ex = new RuntimeException();
6028 ex.fillInStackTrace();
6029 Log.i(TAG, " SURFACE " + mSurface + ": DESTROY ("
6030 + mAttrs.getTitle() + ")", ex);
6031 }
6032 mSurface.clear();
6033 } catch (RuntimeException e) {
6034 Log.w(TAG, "Exception thrown when destroying Window " + this
6035 + " surface " + mSurface + " session " + mSession
6036 + ": " + e.toString());
6037 }
6038 mSurface = null;
6039 mDrawPending = false;
6040 mCommitDrawPending = false;
6041 mReadyToShow = false;
6042
6043 int i = mChildWindows.size();
6044 while (i > 0) {
6045 i--;
6046 WindowState c = (WindowState)mChildWindows.get(i);
6047 c.mAttachedHidden = true;
6048 }
6049 }
6050 }
6051
6052 boolean finishDrawingLocked() {
6053 if (mDrawPending) {
6054 if (SHOW_TRANSACTIONS || DEBUG_ORIENTATION) Log.v(
6055 TAG, "finishDrawingLocked: " + mSurface);
6056 mCommitDrawPending = true;
6057 mDrawPending = false;
6058 return true;
6059 }
6060 return false;
6061 }
6062
6063 // This must be called while inside a transaction.
6064 void commitFinishDrawingLocked(long currentTime) {
6065 //Log.i(TAG, "commitFinishDrawingLocked: " + mSurface);
6066 if (!mCommitDrawPending) {
6067 return;
6068 }
6069 mCommitDrawPending = false;
6070 mReadyToShow = true;
6071 final boolean starting = mAttrs.type == TYPE_APPLICATION_STARTING;
6072 final AppWindowToken atoken = mAppToken;
6073 if (atoken == null || atoken.allDrawn || starting) {
6074 performShowLocked();
6075 }
6076 }
6077
6078 // This must be called while inside a transaction.
6079 boolean performShowLocked() {
6080 if (DEBUG_VISIBILITY) {
6081 RuntimeException e = new RuntimeException();
6082 e.fillInStackTrace();
6083 Log.v(TAG, "performShow on " + this
6084 + ": readyToShow=" + mReadyToShow + " readyForDisplay=" + isReadyForDisplay()
6085 + " starting=" + (mAttrs.type == TYPE_APPLICATION_STARTING), e);
6086 }
6087 if (mReadyToShow && isReadyForDisplay()) {
6088 if (SHOW_TRANSACTIONS || DEBUG_ORIENTATION) Log.i(
6089 TAG, " SURFACE " + mSurface + ": SHOW (performShowLocked)");
6090 if (DEBUG_VISIBILITY) Log.v(TAG, "Showing " + this
6091 + " during animation: policyVis=" + mPolicyVisibility
6092 + " attHidden=" + mAttachedHidden
6093 + " tok.hiddenRequested="
6094 + (mAppToken != null ? mAppToken.hiddenRequested : false)
6095 + " tok.idden="
6096 + (mAppToken != null ? mAppToken.hidden : false)
6097 + " animating=" + mAnimating
6098 + " tok animating="
6099 + (mAppToken != null ? mAppToken.animating : false));
6100 if (!showSurfaceRobustlyLocked(this)) {
6101 return false;
6102 }
6103 mLastAlpha = -1;
6104 mHasDrawn = true;
6105 mLastHidden = false;
6106 mReadyToShow = false;
6107 enableScreenIfNeededLocked();
6108
6109 applyEnterAnimationLocked(this);
Romain Guy06882f82009-06-10 13:36:04 -07006110
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006111 int i = mChildWindows.size();
6112 while (i > 0) {
6113 i--;
6114 WindowState c = (WindowState)mChildWindows.get(i);
6115 if (c.mSurface != null && c.mAttachedHidden) {
6116 c.mAttachedHidden = false;
6117 c.performShowLocked();
6118 }
6119 }
Romain Guy06882f82009-06-10 13:36:04 -07006120
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006121 if (mAttrs.type != TYPE_APPLICATION_STARTING
6122 && mAppToken != null) {
6123 mAppToken.firstWindowDrawn = true;
6124 if (mAnimation == null && mAppToken.startingData != null) {
6125 if (DEBUG_STARTING_WINDOW) Log.v(TAG, "Finish starting "
6126 + mToken
6127 + ": first real window is shown, no animation");
6128 mFinishedStarting.add(mAppToken);
6129 mH.sendEmptyMessage(H.FINISHED_STARTING);
6130 }
6131 mAppToken.updateReportedVisibilityLocked();
6132 }
6133 }
6134 return true;
6135 }
Romain Guy06882f82009-06-10 13:36:04 -07006136
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006137 // This must be called while inside a transaction. Returns true if
6138 // there is more animation to run.
6139 boolean stepAnimationLocked(long currentTime, int dw, int dh) {
6140 if (!mDisplayFrozen) {
6141 // We will run animations as long as the display isn't frozen.
Romain Guy06882f82009-06-10 13:36:04 -07006142
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006143 if (!mDrawPending && !mCommitDrawPending && mAnimation != null) {
6144 mHasTransformation = true;
6145 mHasLocalTransformation = true;
6146 if (!mLocalAnimating) {
6147 if (DEBUG_ANIM) Log.v(
6148 TAG, "Starting animation in " + this +
6149 " @ " + currentTime + ": ww=" + mFrame.width() + " wh=" + mFrame.height() +
6150 " dw=" + dw + " dh=" + dh + " scale=" + mWindowAnimationScale);
6151 mAnimation.initialize(mFrame.width(), mFrame.height(), dw, dh);
6152 mAnimation.setStartTime(currentTime);
6153 mLocalAnimating = true;
6154 mAnimating = true;
6155 }
6156 mTransformation.clear();
6157 final boolean more = mAnimation.getTransformation(
6158 currentTime, mTransformation);
6159 if (DEBUG_ANIM) Log.v(
6160 TAG, "Stepped animation in " + this +
6161 ": more=" + more + ", xform=" + mTransformation);
6162 if (more) {
6163 // we're not done!
6164 return true;
6165 }
6166 if (DEBUG_ANIM) Log.v(
6167 TAG, "Finished animation in " + this +
6168 " @ " + currentTime);
6169 mAnimation = null;
6170 //WindowManagerService.this.dump();
6171 }
6172 mHasLocalTransformation = false;
6173 if ((!mLocalAnimating || mAnimationIsEntrance) && mAppToken != null
6174 && mAppToken.hasTransformation) {
6175 // When our app token is animating, we kind-of pretend like
6176 // we are as well. Note the mLocalAnimating mAnimationIsEntrance
6177 // part of this check means that we will only do this if
6178 // our window is not currently exiting, or it is not
6179 // locally animating itself. The idea being that one that
6180 // is exiting and doing a local animation should be removed
6181 // once that animation is done.
6182 mAnimating = true;
6183 mHasTransformation = true;
6184 mTransformation.clear();
6185 return false;
6186 } else if (mHasTransformation) {
6187 // Little trick to get through the path below to act like
6188 // we have finished an animation.
6189 mAnimating = true;
6190 } else if (isAnimating()) {
6191 mAnimating = true;
6192 }
6193 } else if (mAnimation != null) {
6194 // If the display is frozen, and there is a pending animation,
6195 // clear it and make sure we run the cleanup code.
6196 mAnimating = true;
6197 mLocalAnimating = true;
6198 mAnimation = null;
6199 }
Romain Guy06882f82009-06-10 13:36:04 -07006200
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006201 if (!mAnimating && !mLocalAnimating) {
6202 return false;
6203 }
6204
6205 if (DEBUG_ANIM) Log.v(
6206 TAG, "Animation done in " + this + ": exiting=" + mExiting
6207 + ", reportedVisible="
6208 + (mAppToken != null ? mAppToken.reportedVisible : false));
Romain Guy06882f82009-06-10 13:36:04 -07006209
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006210 mAnimating = false;
6211 mLocalAnimating = false;
6212 mAnimation = null;
6213 mAnimLayer = mLayer;
6214 if (mIsImWindow) {
6215 mAnimLayer += mInputMethodAnimLayerAdjustment;
6216 }
6217 if (DEBUG_LAYERS) Log.v(TAG, "Stepping win " + this
6218 + " anim layer: " + mAnimLayer);
6219 mHasTransformation = false;
6220 mHasLocalTransformation = false;
6221 mPolicyVisibility = mPolicyVisibilityAfterAnim;
6222 mTransformation.clear();
6223 if (mHasDrawn
6224 && mAttrs.type == WindowManager.LayoutParams.TYPE_APPLICATION_STARTING
6225 && mAppToken != null
6226 && mAppToken.firstWindowDrawn
6227 && mAppToken.startingData != null) {
6228 if (DEBUG_STARTING_WINDOW) Log.v(TAG, "Finish starting "
6229 + mToken + ": first real window done animating");
6230 mFinishedStarting.add(mAppToken);
6231 mH.sendEmptyMessage(H.FINISHED_STARTING);
6232 }
Romain Guy06882f82009-06-10 13:36:04 -07006233
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006234 finishExit();
6235
6236 if (mAppToken != null) {
6237 mAppToken.updateReportedVisibilityLocked();
6238 }
6239
6240 return false;
6241 }
6242
6243 void finishExit() {
6244 if (DEBUG_ANIM) Log.v(
6245 TAG, "finishExit in " + this
6246 + ": exiting=" + mExiting
6247 + " remove=" + mRemoveOnExit
6248 + " windowAnimating=" + isWindowAnimating());
Romain Guy06882f82009-06-10 13:36:04 -07006249
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006250 final int N = mChildWindows.size();
6251 for (int i=0; i<N; i++) {
6252 ((WindowState)mChildWindows.get(i)).finishExit();
6253 }
Romain Guy06882f82009-06-10 13:36:04 -07006254
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006255 if (!mExiting) {
6256 return;
6257 }
Romain Guy06882f82009-06-10 13:36:04 -07006258
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006259 if (isWindowAnimating()) {
6260 return;
6261 }
6262
6263 if (localLOGV) Log.v(
6264 TAG, "Exit animation finished in " + this
6265 + ": remove=" + mRemoveOnExit);
6266 if (mSurface != null) {
6267 mDestroySurface.add(this);
6268 mDestroying = true;
6269 if (SHOW_TRANSACTIONS) Log.i(
6270 TAG, " SURFACE " + mSurface + ": HIDE (finishExit)");
6271 try {
6272 mSurface.hide();
6273 } catch (RuntimeException e) {
6274 Log.w(TAG, "Error hiding surface in " + this, e);
6275 }
6276 mLastHidden = true;
6277 mKeyWaiter.releasePendingPointerLocked(mSession);
6278 }
6279 mExiting = false;
6280 if (mRemoveOnExit) {
6281 mPendingRemove.add(this);
6282 mRemoveOnExit = false;
6283 }
6284 }
Romain Guy06882f82009-06-10 13:36:04 -07006285
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006286 boolean isIdentityMatrix(float dsdx, float dtdx, float dsdy, float dtdy) {
6287 if (dsdx < .99999f || dsdx > 1.00001f) return false;
6288 if (dtdy < .99999f || dtdy > 1.00001f) return false;
6289 if (dtdx < -.000001f || dtdx > .000001f) return false;
6290 if (dsdy < -.000001f || dsdy > .000001f) return false;
6291 return true;
6292 }
Romain Guy06882f82009-06-10 13:36:04 -07006293
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006294 void computeShownFrameLocked() {
6295 final boolean selfTransformation = mHasLocalTransformation;
6296 Transformation attachedTransformation =
6297 (mAttachedWindow != null && mAttachedWindow.mHasLocalTransformation)
6298 ? mAttachedWindow.mTransformation : null;
6299 Transformation appTransformation =
6300 (mAppToken != null && mAppToken.hasTransformation)
6301 ? mAppToken.transformation : null;
6302 if (selfTransformation || attachedTransformation != null
6303 || appTransformation != null) {
Romain Guy06882f82009-06-10 13:36:04 -07006304 // cache often used attributes locally
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006305 final Rect frame = mFrame;
6306 final float tmpFloats[] = mTmpFloats;
6307 final Matrix tmpMatrix = mTmpMatrix;
6308
6309 // Compute the desired transformation.
6310 tmpMatrix.setTranslate(frame.left, frame.top);
6311 if (selfTransformation) {
6312 tmpMatrix.preConcat(mTransformation.getMatrix());
6313 }
6314 if (attachedTransformation != null) {
6315 tmpMatrix.preConcat(attachedTransformation.getMatrix());
6316 }
6317 if (appTransformation != null) {
6318 tmpMatrix.preConcat(appTransformation.getMatrix());
6319 }
6320
6321 // "convert" it into SurfaceFlinger's format
6322 // (a 2x2 matrix + an offset)
6323 // Here we must not transform the position of the surface
6324 // since it is already included in the transformation.
6325 //Log.i(TAG, "Transform: " + matrix);
Romain Guy06882f82009-06-10 13:36:04 -07006326
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006327 tmpMatrix.getValues(tmpFloats);
6328 mDsDx = tmpFloats[Matrix.MSCALE_X];
6329 mDtDx = tmpFloats[Matrix.MSKEW_X];
6330 mDsDy = tmpFloats[Matrix.MSKEW_Y];
6331 mDtDy = tmpFloats[Matrix.MSCALE_Y];
6332 int x = (int)tmpFloats[Matrix.MTRANS_X];
6333 int y = (int)tmpFloats[Matrix.MTRANS_Y];
6334 int w = frame.width();
6335 int h = frame.height();
6336 mShownFrame.set(x, y, x+w, y+h);
6337
6338 // Now set the alpha... but because our current hardware
6339 // can't do alpha transformation on a non-opaque surface,
6340 // turn it off if we are running an animation that is also
6341 // transforming since it is more important to have that
6342 // animation be smooth.
6343 mShownAlpha = mAlpha;
6344 if (!mLimitedAlphaCompositing
6345 || (!PixelFormat.formatHasAlpha(mAttrs.format)
6346 || (isIdentityMatrix(mDsDx, mDtDx, mDsDy, mDtDy)
6347 && x == frame.left && y == frame.top))) {
6348 //Log.i(TAG, "Applying alpha transform");
6349 if (selfTransformation) {
6350 mShownAlpha *= mTransformation.getAlpha();
6351 }
6352 if (attachedTransformation != null) {
6353 mShownAlpha *= attachedTransformation.getAlpha();
6354 }
6355 if (appTransformation != null) {
6356 mShownAlpha *= appTransformation.getAlpha();
6357 }
6358 } else {
6359 //Log.i(TAG, "Not applying alpha transform");
6360 }
Romain Guy06882f82009-06-10 13:36:04 -07006361
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006362 if (localLOGV) Log.v(
6363 TAG, "Continuing animation in " + this +
6364 ": " + mShownFrame +
6365 ", alpha=" + mTransformation.getAlpha());
6366 return;
6367 }
Romain Guy06882f82009-06-10 13:36:04 -07006368
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006369 mShownFrame.set(mFrame);
6370 mShownAlpha = mAlpha;
6371 mDsDx = 1;
6372 mDtDx = 0;
6373 mDsDy = 0;
6374 mDtDy = 1;
6375 }
Romain Guy06882f82009-06-10 13:36:04 -07006376
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006377 /**
6378 * Is this window visible? It is not visible if there is no
6379 * surface, or we are in the process of running an exit animation
6380 * that will remove the surface, or its app token has been hidden.
6381 */
6382 public boolean isVisibleLw() {
6383 final AppWindowToken atoken = mAppToken;
6384 return mSurface != null && mPolicyVisibility && !mAttachedHidden
6385 && (atoken == null || !atoken.hiddenRequested)
6386 && !mExiting && !mDestroying;
6387 }
6388
6389 /**
6390 * Is this window visible, ignoring its app token? It is not visible
6391 * if there is no surface, or we are in the process of running an exit animation
6392 * that will remove the surface.
6393 */
6394 public boolean isWinVisibleLw() {
6395 final AppWindowToken atoken = mAppToken;
6396 return mSurface != null && mPolicyVisibility && !mAttachedHidden
6397 && (atoken == null || !atoken.hiddenRequested || atoken.animating)
6398 && !mExiting && !mDestroying;
6399 }
6400
6401 /**
6402 * The same as isVisible(), but follows the current hidden state of
6403 * the associated app token, not the pending requested hidden state.
6404 */
6405 boolean isVisibleNow() {
6406 return mSurface != null && mPolicyVisibility && !mAttachedHidden
The Android Open Source Project10592532009-03-18 17:39:46 -07006407 && !mRootToken.hidden && !mExiting && !mDestroying;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006408 }
6409
6410 /**
6411 * Same as isVisible(), but we also count it as visible between the
6412 * call to IWindowSession.add() and the first relayout().
6413 */
6414 boolean isVisibleOrAdding() {
6415 final AppWindowToken atoken = mAppToken;
6416 return (mSurface != null
6417 || (!mRelayoutCalled && mViewVisibility == View.VISIBLE))
6418 && mPolicyVisibility && !mAttachedHidden
6419 && (atoken == null || !atoken.hiddenRequested)
6420 && !mExiting && !mDestroying;
6421 }
6422
6423 /**
6424 * Is this window currently on-screen? It is on-screen either if it
6425 * is visible or it is currently running an animation before no longer
6426 * being visible.
6427 */
6428 boolean isOnScreen() {
6429 final AppWindowToken atoken = mAppToken;
6430 if (atoken != null) {
6431 return mSurface != null && mPolicyVisibility && !mDestroying
6432 && ((!mAttachedHidden && !atoken.hiddenRequested)
6433 || mAnimating || atoken.animating);
6434 } else {
6435 return mSurface != null && mPolicyVisibility && !mDestroying
6436 && (!mAttachedHidden || mAnimating);
6437 }
6438 }
Romain Guy06882f82009-06-10 13:36:04 -07006439
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006440 /**
6441 * Like isOnScreen(), but we don't return true if the window is part
6442 * of a transition that has not yet been started.
6443 */
6444 boolean isReadyForDisplay() {
6445 final AppWindowToken atoken = mAppToken;
6446 final boolean animating = atoken != null ? atoken.animating : false;
6447 return mSurface != null && mPolicyVisibility && !mDestroying
The Android Open Source Project10592532009-03-18 17:39:46 -07006448 && ((!mAttachedHidden && !mRootToken.hidden)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006449 || mAnimating || animating);
6450 }
6451
6452 /** Is the window or its container currently animating? */
6453 boolean isAnimating() {
6454 final WindowState attached = mAttachedWindow;
6455 final AppWindowToken atoken = mAppToken;
6456 return mAnimation != null
6457 || (attached != null && attached.mAnimation != null)
Romain Guy06882f82009-06-10 13:36:04 -07006458 || (atoken != null &&
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006459 (atoken.animation != null
6460 || atoken.inPendingTransaction));
6461 }
6462
6463 /** Is this window currently animating? */
6464 boolean isWindowAnimating() {
6465 return mAnimation != null;
6466 }
6467
6468 /**
6469 * Like isOnScreen, but returns false if the surface hasn't yet
6470 * been drawn.
6471 */
6472 public boolean isDisplayedLw() {
6473 final AppWindowToken atoken = mAppToken;
6474 return mSurface != null && mPolicyVisibility && !mDestroying
6475 && !mDrawPending && !mCommitDrawPending
6476 && ((!mAttachedHidden &&
6477 (atoken == null || !atoken.hiddenRequested))
6478 || mAnimating);
6479 }
6480
6481 public boolean fillsScreenLw(int screenWidth, int screenHeight,
6482 boolean shownFrame, boolean onlyOpaque) {
6483 if (mSurface == null) {
6484 return false;
6485 }
6486 if (mAppToken != null && !mAppToken.appFullscreen) {
6487 return false;
6488 }
6489 if (onlyOpaque && mAttrs.format != PixelFormat.OPAQUE) {
6490 return false;
6491 }
6492 final Rect frame = shownFrame ? mShownFrame : mFrame;
6493 if (frame.left <= 0 && frame.top <= 0
6494 && frame.right >= screenWidth
6495 && frame.bottom >= screenHeight) {
6496 return true;
6497 }
6498 return false;
6499 }
Romain Guy06882f82009-06-10 13:36:04 -07006500
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006501 boolean isFullscreenOpaque(int screenWidth, int screenHeight) {
6502 if (mAttrs.format != PixelFormat.OPAQUE || mSurface == null
6503 || mAnimation != null || mDrawPending || mCommitDrawPending) {
6504 return false;
6505 }
6506 if (mFrame.left <= 0 && mFrame.top <= 0 &&
6507 mFrame.right >= screenWidth && mFrame.bottom >= screenHeight) {
6508 return true;
6509 }
6510 return false;
6511 }
6512
6513 void removeLocked() {
6514 if (mAttachedWindow != null) {
6515 mAttachedWindow.mChildWindows.remove(this);
6516 }
6517 destroySurfaceLocked();
6518 mSession.windowRemovedLocked();
6519 try {
6520 mClient.asBinder().unlinkToDeath(mDeathRecipient, 0);
6521 } catch (RuntimeException e) {
6522 // Ignore if it has already been removed (usually because
6523 // we are doing this as part of processing a death note.)
6524 }
6525 }
6526
6527 private class DeathRecipient implements IBinder.DeathRecipient {
6528 public void binderDied() {
6529 try {
6530 synchronized(mWindowMap) {
6531 WindowState win = windowForClientLocked(mSession, mClient);
6532 Log.i(TAG, "WIN DEATH: " + win);
6533 if (win != null) {
6534 removeWindowLocked(mSession, win);
6535 }
6536 }
6537 } catch (IllegalArgumentException ex) {
6538 // This will happen if the window has already been
6539 // removed.
6540 }
6541 }
6542 }
6543
6544 /** Returns true if this window desires key events. */
6545 public final boolean canReceiveKeys() {
6546 return isVisibleOrAdding()
6547 && (mViewVisibility == View.VISIBLE)
6548 && ((mAttrs.flags & WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE) == 0);
6549 }
6550
6551 public boolean hasDrawnLw() {
6552 return mHasDrawn;
6553 }
6554
6555 public boolean showLw(boolean doAnimation) {
6556 if (!mPolicyVisibility || !mPolicyVisibilityAfterAnim) {
6557 mPolicyVisibility = true;
6558 mPolicyVisibilityAfterAnim = true;
6559 if (doAnimation) {
6560 applyAnimationLocked(this, WindowManagerPolicy.TRANSIT_ENTER, true);
6561 }
6562 requestAnimationLocked(0);
6563 return true;
6564 }
6565 return false;
6566 }
6567
6568 public boolean hideLw(boolean doAnimation) {
6569 boolean current = doAnimation ? mPolicyVisibilityAfterAnim
6570 : mPolicyVisibility;
6571 if (current) {
6572 if (doAnimation) {
6573 applyAnimationLocked(this, WindowManagerPolicy.TRANSIT_EXIT, false);
6574 if (mAnimation == null) {
6575 doAnimation = false;
6576 }
6577 }
6578 if (doAnimation) {
6579 mPolicyVisibilityAfterAnim = false;
6580 } else {
6581 mPolicyVisibilityAfterAnim = false;
6582 mPolicyVisibility = false;
6583 }
6584 requestAnimationLocked(0);
6585 return true;
6586 }
6587 return false;
6588 }
6589
6590 void dump(PrintWriter pw, String prefix) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006591 StringBuilder sb = new StringBuilder(64);
Romain Guy06882f82009-06-10 13:36:04 -07006592
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006593 pw.print(prefix); pw.print("mSession="); pw.print(mSession);
6594 pw.print(" mClient="); pw.println(mClient.asBinder());
6595 pw.print(prefix); pw.print("mAttrs="); pw.println(mAttrs);
6596 if (mAttachedWindow != null || mLayoutAttached) {
6597 pw.print(prefix); pw.print("mAttachedWindow="); pw.print(mAttachedWindow);
6598 pw.print(" mLayoutAttached="); pw.println(mLayoutAttached);
6599 }
6600 if (mIsImWindow) {
6601 pw.print(prefix); pw.print("mIsImWindow="); pw.println(mIsImWindow);
6602 }
6603 pw.print(prefix); pw.print("mBaseLayer="); pw.print(mBaseLayer);
6604 pw.print(" mSubLayer="); pw.print(mSubLayer);
6605 pw.print(" mAnimLayer="); pw.print(mLayer); pw.print("+");
6606 pw.print((mTargetAppToken != null ? mTargetAppToken.animLayerAdjustment
6607 : (mAppToken != null ? mAppToken.animLayerAdjustment : 0)));
6608 pw.print("="); pw.print(mAnimLayer);
6609 pw.print(" mLastLayer="); pw.println(mLastLayer);
6610 if (mSurface != null) {
6611 pw.print(prefix); pw.print("mSurface="); pw.println(mSurface);
6612 }
6613 pw.print(prefix); pw.print("mToken="); pw.println(mToken);
6614 pw.print(prefix); pw.print("mRootToken="); pw.println(mRootToken);
6615 if (mAppToken != null) {
6616 pw.print(prefix); pw.print("mAppToken="); pw.println(mAppToken);
6617 }
6618 if (mTargetAppToken != null) {
6619 pw.print(prefix); pw.print("mTargetAppToken="); pw.println(mTargetAppToken);
6620 }
6621 pw.print(prefix); pw.print("mViewVisibility=0x");
6622 pw.print(Integer.toHexString(mViewVisibility));
6623 pw.print(" mLastHidden="); pw.print(mLastHidden);
6624 pw.print(" mHaveFrame="); pw.println(mHaveFrame);
6625 if (!mPolicyVisibility || !mPolicyVisibilityAfterAnim || mAttachedHidden) {
6626 pw.print(prefix); pw.print("mPolicyVisibility=");
6627 pw.print(mPolicyVisibility);
6628 pw.print(" mPolicyVisibilityAfterAnim=");
6629 pw.print(mPolicyVisibilityAfterAnim);
6630 pw.print(" mAttachedHidden="); pw.println(mAttachedHidden);
6631 }
6632 pw.print(prefix); pw.print("Requested w="); pw.print(mRequestedWidth);
6633 pw.print(" h="); pw.print(mRequestedHeight);
6634 pw.print(" x="); pw.print(mReqXPos);
6635 pw.print(" y="); pw.println(mReqYPos);
6636 pw.print(prefix); pw.print("mGivenContentInsets=");
6637 mGivenContentInsets.printShortString(pw);
6638 pw.print(" mGivenVisibleInsets=");
6639 mGivenVisibleInsets.printShortString(pw);
6640 pw.println();
6641 if (mTouchableInsets != 0 || mGivenInsetsPending) {
6642 pw.print(prefix); pw.print("mTouchableInsets="); pw.print(mTouchableInsets);
6643 pw.print(" mGivenInsetsPending="); pw.println(mGivenInsetsPending);
6644 }
6645 pw.print(prefix); pw.print("mShownFrame=");
6646 mShownFrame.printShortString(pw);
6647 pw.print(" last="); mLastShownFrame.printShortString(pw);
6648 pw.println();
6649 pw.print(prefix); pw.print("mFrame="); mFrame.printShortString(pw);
6650 pw.print(" last="); mLastFrame.printShortString(pw);
6651 pw.println();
6652 pw.print(prefix); pw.print("mContainingFrame=");
6653 mContainingFrame.printShortString(pw);
6654 pw.print(" mDisplayFrame=");
6655 mDisplayFrame.printShortString(pw);
6656 pw.println();
6657 pw.print(prefix); pw.print("mContentFrame="); mContentFrame.printShortString(pw);
6658 pw.print(" mVisibleFrame="); mVisibleFrame.printShortString(pw);
6659 pw.println();
6660 pw.print(prefix); pw.print("mContentInsets="); mContentInsets.printShortString(pw);
6661 pw.print(" last="); mLastContentInsets.printShortString(pw);
6662 pw.print(" mVisibleInsets="); mVisibleInsets.printShortString(pw);
6663 pw.print(" last="); mLastVisibleInsets.printShortString(pw);
6664 pw.println();
6665 if (mShownAlpha != 1 || mAlpha != 1 || mLastAlpha != 1) {
6666 pw.print(prefix); pw.print("mShownAlpha="); pw.print(mShownAlpha);
6667 pw.print(" mAlpha="); pw.print(mAlpha);
6668 pw.print(" mLastAlpha="); pw.println(mLastAlpha);
6669 }
6670 if (mAnimating || mLocalAnimating || mAnimationIsEntrance
6671 || mAnimation != null) {
6672 pw.print(prefix); pw.print("mAnimating="); pw.print(mAnimating);
6673 pw.print(" mLocalAnimating="); pw.print(mLocalAnimating);
6674 pw.print(" mAnimationIsEntrance="); pw.print(mAnimationIsEntrance);
6675 pw.print(" mAnimation="); pw.println(mAnimation);
6676 }
6677 if (mHasTransformation || mHasLocalTransformation) {
6678 pw.print(prefix); pw.print("XForm: has=");
6679 pw.print(mHasTransformation);
6680 pw.print(" hasLocal="); pw.print(mHasLocalTransformation);
6681 pw.print(" "); mTransformation.printShortString(pw);
6682 pw.println();
6683 }
6684 pw.print(prefix); pw.print("mDrawPending="); pw.print(mDrawPending);
6685 pw.print(" mCommitDrawPending="); pw.print(mCommitDrawPending);
6686 pw.print(" mReadyToShow="); pw.print(mReadyToShow);
6687 pw.print(" mHasDrawn="); pw.println(mHasDrawn);
6688 if (mExiting || mRemoveOnExit || mDestroying || mRemoved) {
6689 pw.print(prefix); pw.print("mExiting="); pw.print(mExiting);
6690 pw.print(" mRemoveOnExit="); pw.print(mRemoveOnExit);
6691 pw.print(" mDestroying="); pw.print(mDestroying);
6692 pw.print(" mRemoved="); pw.println(mRemoved);
6693 }
6694 if (mOrientationChanging || mAppFreezing) {
6695 pw.print(prefix); pw.print("mOrientationChanging=");
6696 pw.print(mOrientationChanging);
6697 pw.print(" mAppFreezing="); pw.println(mAppFreezing);
6698 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006699 }
6700
6701 @Override
6702 public String toString() {
6703 return "Window{"
6704 + Integer.toHexString(System.identityHashCode(this))
6705 + " " + mAttrs.getTitle() + " paused=" + mToken.paused + "}";
6706 }
6707 }
Romain Guy06882f82009-06-10 13:36:04 -07006708
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006709 // -------------------------------------------------------------
6710 // Window Token State
6711 // -------------------------------------------------------------
6712
6713 class WindowToken {
6714 // The actual token.
6715 final IBinder token;
6716
6717 // The type of window this token is for, as per WindowManager.LayoutParams.
6718 final int windowType;
Romain Guy06882f82009-06-10 13:36:04 -07006719
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006720 // Set if this token was explicitly added by a client, so should
6721 // not be removed when all windows are removed.
6722 final boolean explicit;
Romain Guy06882f82009-06-10 13:36:04 -07006723
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006724 // For printing.
6725 String stringName;
Romain Guy06882f82009-06-10 13:36:04 -07006726
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006727 // If this is an AppWindowToken, this is non-null.
6728 AppWindowToken appWindowToken;
Romain Guy06882f82009-06-10 13:36:04 -07006729
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006730 // All of the windows associated with this token.
6731 final ArrayList<WindowState> windows = new ArrayList<WindowState>();
6732
6733 // Is key dispatching paused for this token?
6734 boolean paused = false;
6735
6736 // Should this token's windows be hidden?
6737 boolean hidden;
6738
6739 // Temporary for finding which tokens no longer have visible windows.
6740 boolean hasVisible;
6741
6742 WindowToken(IBinder _token, int type, boolean _explicit) {
6743 token = _token;
6744 windowType = type;
6745 explicit = _explicit;
6746 }
6747
6748 void dump(PrintWriter pw, String prefix) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006749 pw.print(prefix); pw.print("token="); pw.println(token);
6750 pw.print(prefix); pw.print("windows="); pw.println(windows);
6751 pw.print(prefix); pw.print("windowType="); pw.print(windowType);
6752 pw.print(" hidden="); pw.print(hidden);
6753 pw.print(" hasVisible="); pw.println(hasVisible);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006754 }
6755
6756 @Override
6757 public String toString() {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006758 if (stringName == null) {
6759 StringBuilder sb = new StringBuilder();
6760 sb.append("WindowToken{");
6761 sb.append(Integer.toHexString(System.identityHashCode(this)));
6762 sb.append(" token="); sb.append(token); sb.append('}');
6763 stringName = sb.toString();
6764 }
6765 return stringName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006766 }
6767 };
6768
6769 class AppWindowToken extends WindowToken {
6770 // Non-null only for application tokens.
6771 final IApplicationToken appToken;
6772
6773 // All of the windows and child windows that are included in this
6774 // application token. Note this list is NOT sorted!
6775 final ArrayList<WindowState> allAppWindows = new ArrayList<WindowState>();
6776
6777 int groupId = -1;
6778 boolean appFullscreen;
6779 int requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
Romain Guy06882f82009-06-10 13:36:04 -07006780
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006781 // These are used for determining when all windows associated with
6782 // an activity have been drawn, so they can be made visible together
6783 // at the same time.
6784 int lastTransactionSequence = mTransactionSequence-1;
6785 int numInterestingWindows;
6786 int numDrawnWindows;
6787 boolean inPendingTransaction;
6788 boolean allDrawn;
Romain Guy06882f82009-06-10 13:36:04 -07006789
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006790 // Is this token going to be hidden in a little while? If so, it
6791 // won't be taken into account for setting the screen orientation.
6792 boolean willBeHidden;
Romain Guy06882f82009-06-10 13:36:04 -07006793
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006794 // Is this window's surface needed? This is almost like hidden, except
6795 // it will sometimes be true a little earlier: when the token has
6796 // been shown, but is still waiting for its app transition to execute
6797 // before making its windows shown.
6798 boolean hiddenRequested;
Romain Guy06882f82009-06-10 13:36:04 -07006799
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006800 // Have we told the window clients to hide themselves?
6801 boolean clientHidden;
Romain Guy06882f82009-06-10 13:36:04 -07006802
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006803 // Last visibility state we reported to the app token.
6804 boolean reportedVisible;
6805
6806 // Set to true when the token has been removed from the window mgr.
6807 boolean removed;
6808
6809 // Have we been asked to have this token keep the screen frozen?
6810 boolean freezingScreen;
Romain Guy06882f82009-06-10 13:36:04 -07006811
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006812 boolean animating;
6813 Animation animation;
6814 boolean hasTransformation;
6815 final Transformation transformation = new Transformation();
Romain Guy06882f82009-06-10 13:36:04 -07006816
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006817 // Offset to the window of all layers in the token, for use by
6818 // AppWindowToken animations.
6819 int animLayerAdjustment;
Romain Guy06882f82009-06-10 13:36:04 -07006820
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006821 // Information about an application starting window if displayed.
6822 StartingData startingData;
6823 WindowState startingWindow;
6824 View startingView;
6825 boolean startingDisplayed;
6826 boolean startingMoved;
6827 boolean firstWindowDrawn;
6828
6829 AppWindowToken(IApplicationToken _token) {
6830 super(_token.asBinder(),
6831 WindowManager.LayoutParams.TYPE_APPLICATION, true);
6832 appWindowToken = this;
6833 appToken = _token;
6834 }
Romain Guy06882f82009-06-10 13:36:04 -07006835
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006836 public void setAnimation(Animation anim) {
6837 if (localLOGV) Log.v(
6838 TAG, "Setting animation in " + this + ": " + anim);
6839 animation = anim;
6840 animating = false;
6841 anim.restrictDuration(MAX_ANIMATION_DURATION);
6842 anim.scaleCurrentDuration(mTransitionAnimationScale);
6843 int zorder = anim.getZAdjustment();
6844 int adj = 0;
6845 if (zorder == Animation.ZORDER_TOP) {
6846 adj = TYPE_LAYER_OFFSET;
6847 } else if (zorder == Animation.ZORDER_BOTTOM) {
6848 adj = -TYPE_LAYER_OFFSET;
6849 }
Romain Guy06882f82009-06-10 13:36:04 -07006850
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006851 if (animLayerAdjustment != adj) {
6852 animLayerAdjustment = adj;
6853 updateLayers();
6854 }
6855 }
Romain Guy06882f82009-06-10 13:36:04 -07006856
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006857 public void setDummyAnimation() {
6858 if (animation == null) {
6859 if (localLOGV) Log.v(
6860 TAG, "Setting dummy animation in " + this);
6861 animation = sDummyAnimation;
6862 }
6863 }
6864
6865 public void clearAnimation() {
6866 if (animation != null) {
6867 animation = null;
6868 animating = true;
6869 }
6870 }
Romain Guy06882f82009-06-10 13:36:04 -07006871
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006872 void updateLayers() {
6873 final int N = allAppWindows.size();
6874 final int adj = animLayerAdjustment;
6875 for (int i=0; i<N; i++) {
6876 WindowState w = allAppWindows.get(i);
6877 w.mAnimLayer = w.mLayer + adj;
6878 if (DEBUG_LAYERS) Log.v(TAG, "Updating layer " + w + ": "
6879 + w.mAnimLayer);
6880 if (w == mInputMethodTarget) {
6881 setInputMethodAnimLayerAdjustment(adj);
6882 }
6883 }
6884 }
Romain Guy06882f82009-06-10 13:36:04 -07006885
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006886 void sendAppVisibilityToClients() {
6887 final int N = allAppWindows.size();
6888 for (int i=0; i<N; i++) {
6889 WindowState win = allAppWindows.get(i);
6890 if (win == startingWindow && clientHidden) {
6891 // Don't hide the starting window.
6892 continue;
6893 }
6894 try {
6895 if (DEBUG_VISIBILITY) Log.v(TAG,
6896 "Setting visibility of " + win + ": " + (!clientHidden));
6897 win.mClient.dispatchAppVisibility(!clientHidden);
6898 } catch (RemoteException e) {
6899 }
6900 }
6901 }
Romain Guy06882f82009-06-10 13:36:04 -07006902
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006903 void showAllWindowsLocked() {
6904 final int NW = allAppWindows.size();
6905 for (int i=0; i<NW; i++) {
6906 WindowState w = allAppWindows.get(i);
6907 if (DEBUG_VISIBILITY) Log.v(TAG,
6908 "performing show on: " + w);
6909 w.performShowLocked();
6910 }
6911 }
Romain Guy06882f82009-06-10 13:36:04 -07006912
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006913 // This must be called while inside a transaction.
6914 boolean stepAnimationLocked(long currentTime, int dw, int dh) {
6915 if (!mDisplayFrozen) {
6916 // We will run animations as long as the display isn't frozen.
Romain Guy06882f82009-06-10 13:36:04 -07006917
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006918 if (animation == sDummyAnimation) {
6919 // This guy is going to animate, but not yet. For now count
6920 // it is not animating for purposes of scheduling transactions;
6921 // when it is really time to animate, this will be set to
6922 // a real animation and the next call will execute normally.
6923 return false;
6924 }
Romain Guy06882f82009-06-10 13:36:04 -07006925
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006926 if ((allDrawn || animating || startingDisplayed) && animation != null) {
6927 if (!animating) {
6928 if (DEBUG_ANIM) Log.v(
6929 TAG, "Starting animation in " + this +
6930 " @ " + currentTime + ": dw=" + dw + " dh=" + dh
6931 + " scale=" + mTransitionAnimationScale
6932 + " allDrawn=" + allDrawn + " animating=" + animating);
6933 animation.initialize(dw, dh, dw, dh);
6934 animation.setStartTime(currentTime);
6935 animating = true;
6936 }
6937 transformation.clear();
6938 final boolean more = animation.getTransformation(
6939 currentTime, transformation);
6940 if (DEBUG_ANIM) Log.v(
6941 TAG, "Stepped animation in " + this +
6942 ": more=" + more + ", xform=" + transformation);
6943 if (more) {
6944 // we're done!
6945 hasTransformation = true;
6946 return true;
6947 }
6948 if (DEBUG_ANIM) Log.v(
6949 TAG, "Finished animation in " + this +
6950 " @ " + currentTime);
6951 animation = null;
6952 }
6953 } else if (animation != null) {
6954 // If the display is frozen, and there is a pending animation,
6955 // clear it and make sure we run the cleanup code.
6956 animating = true;
6957 animation = null;
6958 }
6959
6960 hasTransformation = false;
Romain Guy06882f82009-06-10 13:36:04 -07006961
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006962 if (!animating) {
6963 return false;
6964 }
6965
6966 clearAnimation();
6967 animating = false;
6968 if (mInputMethodTarget != null && mInputMethodTarget.mAppToken == this) {
6969 moveInputMethodWindowsIfNeededLocked(true);
6970 }
Romain Guy06882f82009-06-10 13:36:04 -07006971
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006972 if (DEBUG_ANIM) Log.v(
6973 TAG, "Animation done in " + this
6974 + ": reportedVisible=" + reportedVisible);
6975
6976 transformation.clear();
6977 if (animLayerAdjustment != 0) {
6978 animLayerAdjustment = 0;
6979 updateLayers();
6980 }
Romain Guy06882f82009-06-10 13:36:04 -07006981
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006982 final int N = windows.size();
6983 for (int i=0; i<N; i++) {
6984 ((WindowState)windows.get(i)).finishExit();
6985 }
6986 updateReportedVisibilityLocked();
Romain Guy06882f82009-06-10 13:36:04 -07006987
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006988 return false;
6989 }
6990
6991 void updateReportedVisibilityLocked() {
6992 if (appToken == null) {
6993 return;
6994 }
Romain Guy06882f82009-06-10 13:36:04 -07006995
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006996 int numInteresting = 0;
6997 int numVisible = 0;
6998 boolean nowGone = true;
Romain Guy06882f82009-06-10 13:36:04 -07006999
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007000 if (DEBUG_VISIBILITY) Log.v(TAG, "Update reported visibility: " + this);
7001 final int N = allAppWindows.size();
7002 for (int i=0; i<N; i++) {
7003 WindowState win = allAppWindows.get(i);
7004 if (win == startingWindow || win.mAppFreezing) {
7005 continue;
7006 }
7007 if (DEBUG_VISIBILITY) {
7008 Log.v(TAG, "Win " + win + ": isDisplayed="
7009 + win.isDisplayedLw()
7010 + ", isAnimating=" + win.isAnimating());
7011 if (!win.isDisplayedLw()) {
7012 Log.v(TAG, "Not displayed: s=" + win.mSurface
7013 + " pv=" + win.mPolicyVisibility
7014 + " dp=" + win.mDrawPending
7015 + " cdp=" + win.mCommitDrawPending
7016 + " ah=" + win.mAttachedHidden
7017 + " th="
7018 + (win.mAppToken != null
7019 ? win.mAppToken.hiddenRequested : false)
7020 + " a=" + win.mAnimating);
7021 }
7022 }
7023 numInteresting++;
7024 if (win.isDisplayedLw()) {
7025 if (!win.isAnimating()) {
7026 numVisible++;
7027 }
7028 nowGone = false;
7029 } else if (win.isAnimating()) {
7030 nowGone = false;
7031 }
7032 }
Romain Guy06882f82009-06-10 13:36:04 -07007033
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007034 boolean nowVisible = numInteresting > 0 && numVisible >= numInteresting;
7035 if (DEBUG_VISIBILITY) Log.v(TAG, "VIS " + this + ": interesting="
7036 + numInteresting + " visible=" + numVisible);
7037 if (nowVisible != reportedVisible) {
7038 if (DEBUG_VISIBILITY) Log.v(
7039 TAG, "Visibility changed in " + this
7040 + ": vis=" + nowVisible);
7041 reportedVisible = nowVisible;
7042 Message m = mH.obtainMessage(
7043 H.REPORT_APPLICATION_TOKEN_WINDOWS,
7044 nowVisible ? 1 : 0,
7045 nowGone ? 1 : 0,
7046 this);
7047 mH.sendMessage(m);
7048 }
7049 }
Romain Guy06882f82009-06-10 13:36:04 -07007050
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007051 void dump(PrintWriter pw, String prefix) {
7052 super.dump(pw, prefix);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007053 if (appToken != null) {
7054 pw.print(prefix); pw.println("app=true");
7055 }
7056 if (allAppWindows.size() > 0) {
7057 pw.print(prefix); pw.print("allAppWindows="); pw.println(allAppWindows);
7058 }
7059 pw.print(prefix); pw.print("groupId="); pw.print(groupId);
7060 pw.print(" requestedOrientation="); pw.println(requestedOrientation);
7061 pw.print(prefix); pw.print("hiddenRequested="); pw.print(hiddenRequested);
7062 pw.print(" clientHidden="); pw.print(clientHidden);
7063 pw.print(" willBeHidden="); pw.print(willBeHidden);
7064 pw.print(" reportedVisible="); pw.println(reportedVisible);
7065 if (paused || freezingScreen) {
7066 pw.print(prefix); pw.print("paused="); pw.print(paused);
7067 pw.print(" freezingScreen="); pw.println(freezingScreen);
7068 }
7069 if (numInterestingWindows != 0 || numDrawnWindows != 0
7070 || inPendingTransaction || allDrawn) {
7071 pw.print(prefix); pw.print("numInterestingWindows=");
7072 pw.print(numInterestingWindows);
7073 pw.print(" numDrawnWindows="); pw.print(numDrawnWindows);
7074 pw.print(" inPendingTransaction="); pw.print(inPendingTransaction);
7075 pw.print(" allDrawn="); pw.println(allDrawn);
7076 }
7077 if (animating || animation != null) {
7078 pw.print(prefix); pw.print("animating="); pw.print(animating);
7079 pw.print(" animation="); pw.println(animation);
7080 }
7081 if (animLayerAdjustment != 0) {
7082 pw.print(prefix); pw.print("animLayerAdjustment="); pw.println(animLayerAdjustment);
7083 }
7084 if (hasTransformation) {
7085 pw.print(prefix); pw.print("hasTransformation="); pw.print(hasTransformation);
7086 pw.print(" transformation="); transformation.printShortString(pw);
7087 pw.println();
7088 }
7089 if (startingData != null || removed || firstWindowDrawn) {
7090 pw.print(prefix); pw.print("startingData="); pw.print(startingData);
7091 pw.print(" removed="); pw.print(removed);
7092 pw.print(" firstWindowDrawn="); pw.println(firstWindowDrawn);
7093 }
7094 if (startingWindow != null || startingView != null
7095 || startingDisplayed || startingMoved) {
7096 pw.print(prefix); pw.print("startingWindow="); pw.print(startingWindow);
7097 pw.print(" startingView="); pw.print(startingView);
7098 pw.print(" startingDisplayed="); pw.print(startingDisplayed);
7099 pw.print(" startingMoved"); pw.println(startingMoved);
7100 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007101 }
7102
7103 @Override
7104 public String toString() {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007105 if (stringName == null) {
7106 StringBuilder sb = new StringBuilder();
7107 sb.append("AppWindowToken{");
7108 sb.append(Integer.toHexString(System.identityHashCode(this)));
7109 sb.append(" token="); sb.append(token); sb.append('}');
7110 stringName = sb.toString();
7111 }
7112 return stringName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007113 }
7114 }
Romain Guy06882f82009-06-10 13:36:04 -07007115
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007116 public static WindowManager.LayoutParams findAnimations(
7117 ArrayList<AppWindowToken> order,
7118 ArrayList<AppWindowToken> tokenList1,
7119 ArrayList<AppWindowToken> tokenList2) {
7120 // We need to figure out which animation to use...
7121 WindowManager.LayoutParams animParams = null;
7122 int animSrc = 0;
Romain Guy06882f82009-06-10 13:36:04 -07007123
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007124 //Log.i(TAG, "Looking for animations...");
7125 for (int i=order.size()-1; i>=0; i--) {
7126 AppWindowToken wtoken = order.get(i);
7127 //Log.i(TAG, "Token " + wtoken + " with " + wtoken.windows.size() + " windows");
7128 if (tokenList1.contains(wtoken) || tokenList2.contains(wtoken)) {
7129 int j = wtoken.windows.size();
7130 while (j > 0) {
7131 j--;
7132 WindowState win = wtoken.windows.get(j);
7133 //Log.i(TAG, "Window " + win + ": type=" + win.mAttrs.type);
7134 if (win.mAttrs.type == WindowManager.LayoutParams.TYPE_BASE_APPLICATION
7135 || win.mAttrs.type == WindowManager.LayoutParams.TYPE_APPLICATION_STARTING) {
7136 //Log.i(TAG, "Found base or application window, done!");
7137 if (wtoken.appFullscreen) {
7138 return win.mAttrs;
7139 }
7140 if (animSrc < 2) {
7141 animParams = win.mAttrs;
7142 animSrc = 2;
7143 }
7144 } else if (animSrc < 1 && win.mAttrs.type == WindowManager.LayoutParams.TYPE_APPLICATION) {
7145 //Log.i(TAG, "Found normal window, we may use this...");
7146 animParams = win.mAttrs;
7147 animSrc = 1;
7148 }
7149 }
7150 }
7151 }
Romain Guy06882f82009-06-10 13:36:04 -07007152
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007153 return animParams;
7154 }
Romain Guy06882f82009-06-10 13:36:04 -07007155
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007156 // -------------------------------------------------------------
7157 // DummyAnimation
7158 // -------------------------------------------------------------
7159
7160 // This is an animation that does nothing: it just immediately finishes
7161 // itself every time it is called. It is used as a stub animation in cases
7162 // where we want to synchronize multiple things that may be animating.
7163 static final class DummyAnimation extends Animation {
7164 public boolean getTransformation(long currentTime, Transformation outTransformation) {
7165 return false;
7166 }
7167 }
7168 static final Animation sDummyAnimation = new DummyAnimation();
Romain Guy06882f82009-06-10 13:36:04 -07007169
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007170 // -------------------------------------------------------------
7171 // Async Handler
7172 // -------------------------------------------------------------
7173
7174 static final class StartingData {
7175 final String pkg;
7176 final int theme;
7177 final CharSequence nonLocalizedLabel;
7178 final int labelRes;
7179 final int icon;
Romain Guy06882f82009-06-10 13:36:04 -07007180
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007181 StartingData(String _pkg, int _theme, CharSequence _nonLocalizedLabel,
7182 int _labelRes, int _icon) {
7183 pkg = _pkg;
7184 theme = _theme;
7185 nonLocalizedLabel = _nonLocalizedLabel;
7186 labelRes = _labelRes;
7187 icon = _icon;
7188 }
7189 }
7190
7191 private final class H extends Handler {
7192 public static final int REPORT_FOCUS_CHANGE = 2;
7193 public static final int REPORT_LOSING_FOCUS = 3;
7194 public static final int ANIMATE = 4;
7195 public static final int ADD_STARTING = 5;
7196 public static final int REMOVE_STARTING = 6;
7197 public static final int FINISHED_STARTING = 7;
7198 public static final int REPORT_APPLICATION_TOKEN_WINDOWS = 8;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007199 public static final int WINDOW_FREEZE_TIMEOUT = 11;
7200 public static final int HOLD_SCREEN_CHANGED = 12;
7201 public static final int APP_TRANSITION_TIMEOUT = 13;
7202 public static final int PERSIST_ANIMATION_SCALE = 14;
7203 public static final int FORCE_GC = 15;
7204 public static final int ENABLE_SCREEN = 16;
7205 public static final int APP_FREEZE_TIMEOUT = 17;
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07007206 public static final int COMPUTE_AND_SEND_NEW_CONFIGURATION = 18;
Romain Guy06882f82009-06-10 13:36:04 -07007207
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007208 private Session mLastReportedHold;
Romain Guy06882f82009-06-10 13:36:04 -07007209
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007210 public H() {
7211 }
Romain Guy06882f82009-06-10 13:36:04 -07007212
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007213 @Override
7214 public void handleMessage(Message msg) {
7215 switch (msg.what) {
7216 case REPORT_FOCUS_CHANGE: {
7217 WindowState lastFocus;
7218 WindowState newFocus;
Romain Guy06882f82009-06-10 13:36:04 -07007219
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007220 synchronized(mWindowMap) {
7221 lastFocus = mLastFocus;
7222 newFocus = mCurrentFocus;
7223 if (lastFocus == newFocus) {
7224 // Focus is not changing, so nothing to do.
7225 return;
7226 }
7227 mLastFocus = newFocus;
7228 //Log.i(TAG, "Focus moving from " + lastFocus
7229 // + " to " + newFocus);
7230 if (newFocus != null && lastFocus != null
7231 && !newFocus.isDisplayedLw()) {
7232 //Log.i(TAG, "Delaying loss of focus...");
7233 mLosingFocus.add(lastFocus);
7234 lastFocus = null;
7235 }
7236 }
7237
7238 if (lastFocus != newFocus) {
7239 //System.out.println("Changing focus from " + lastFocus
7240 // + " to " + newFocus);
7241 if (newFocus != null) {
7242 try {
7243 //Log.i(TAG, "Gaining focus: " + newFocus);
7244 newFocus.mClient.windowFocusChanged(true, mInTouchMode);
7245 } catch (RemoteException e) {
7246 // Ignore if process has died.
7247 }
7248 }
7249
7250 if (lastFocus != null) {
7251 try {
7252 //Log.i(TAG, "Losing focus: " + lastFocus);
7253 lastFocus.mClient.windowFocusChanged(false, mInTouchMode);
7254 } catch (RemoteException e) {
7255 // Ignore if process has died.
7256 }
7257 }
7258 }
7259 } break;
7260
7261 case REPORT_LOSING_FOCUS: {
7262 ArrayList<WindowState> losers;
Romain Guy06882f82009-06-10 13:36:04 -07007263
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007264 synchronized(mWindowMap) {
7265 losers = mLosingFocus;
7266 mLosingFocus = new ArrayList<WindowState>();
7267 }
7268
7269 final int N = losers.size();
7270 for (int i=0; i<N; i++) {
7271 try {
7272 //Log.i(TAG, "Losing delayed focus: " + losers.get(i));
7273 losers.get(i).mClient.windowFocusChanged(false, mInTouchMode);
7274 } catch (RemoteException e) {
7275 // Ignore if process has died.
7276 }
7277 }
7278 } break;
7279
7280 case ANIMATE: {
7281 synchronized(mWindowMap) {
7282 mAnimationPending = false;
7283 performLayoutAndPlaceSurfacesLocked();
7284 }
7285 } break;
7286
7287 case ADD_STARTING: {
7288 final AppWindowToken wtoken = (AppWindowToken)msg.obj;
7289 final StartingData sd = wtoken.startingData;
7290
7291 if (sd == null) {
7292 // Animation has been canceled... do nothing.
7293 return;
7294 }
Romain Guy06882f82009-06-10 13:36:04 -07007295
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007296 if (DEBUG_STARTING_WINDOW) Log.v(TAG, "Add starting "
7297 + wtoken + ": pkg=" + sd.pkg);
Romain Guy06882f82009-06-10 13:36:04 -07007298
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007299 View view = null;
7300 try {
7301 view = mPolicy.addStartingWindow(
7302 wtoken.token, sd.pkg,
7303 sd.theme, sd.nonLocalizedLabel, sd.labelRes,
7304 sd.icon);
7305 } catch (Exception e) {
7306 Log.w(TAG, "Exception when adding starting window", e);
7307 }
7308
7309 if (view != null) {
7310 boolean abort = false;
7311
7312 synchronized(mWindowMap) {
7313 if (wtoken.removed || wtoken.startingData == null) {
7314 // If the window was successfully added, then
7315 // we need to remove it.
7316 if (wtoken.startingWindow != null) {
7317 if (DEBUG_STARTING_WINDOW) Log.v(TAG,
7318 "Aborted starting " + wtoken
7319 + ": removed=" + wtoken.removed
7320 + " startingData=" + wtoken.startingData);
7321 wtoken.startingWindow = null;
7322 wtoken.startingData = null;
7323 abort = true;
7324 }
7325 } else {
7326 wtoken.startingView = view;
7327 }
7328 if (DEBUG_STARTING_WINDOW && !abort) Log.v(TAG,
7329 "Added starting " + wtoken
7330 + ": startingWindow="
7331 + wtoken.startingWindow + " startingView="
7332 + wtoken.startingView);
7333 }
7334
7335 if (abort) {
7336 try {
7337 mPolicy.removeStartingWindow(wtoken.token, view);
7338 } catch (Exception e) {
7339 Log.w(TAG, "Exception when removing starting window", e);
7340 }
7341 }
7342 }
7343 } break;
7344
7345 case REMOVE_STARTING: {
7346 final AppWindowToken wtoken = (AppWindowToken)msg.obj;
7347 IBinder token = null;
7348 View view = null;
7349 synchronized (mWindowMap) {
7350 if (DEBUG_STARTING_WINDOW) Log.v(TAG, "Remove starting "
7351 + wtoken + ": startingWindow="
7352 + wtoken.startingWindow + " startingView="
7353 + wtoken.startingView);
7354 if (wtoken.startingWindow != null) {
7355 view = wtoken.startingView;
7356 token = wtoken.token;
7357 wtoken.startingData = null;
7358 wtoken.startingView = null;
7359 wtoken.startingWindow = null;
7360 }
7361 }
7362 if (view != null) {
7363 try {
7364 mPolicy.removeStartingWindow(token, view);
7365 } catch (Exception e) {
7366 Log.w(TAG, "Exception when removing starting window", e);
7367 }
7368 }
7369 } break;
7370
7371 case FINISHED_STARTING: {
7372 IBinder token = null;
7373 View view = null;
7374 while (true) {
7375 synchronized (mWindowMap) {
7376 final int N = mFinishedStarting.size();
7377 if (N <= 0) {
7378 break;
7379 }
7380 AppWindowToken wtoken = mFinishedStarting.remove(N-1);
7381
7382 if (DEBUG_STARTING_WINDOW) Log.v(TAG,
7383 "Finished starting " + wtoken
7384 + ": startingWindow=" + wtoken.startingWindow
7385 + " startingView=" + wtoken.startingView);
7386
7387 if (wtoken.startingWindow == null) {
7388 continue;
7389 }
7390
7391 view = wtoken.startingView;
7392 token = wtoken.token;
7393 wtoken.startingData = null;
7394 wtoken.startingView = null;
7395 wtoken.startingWindow = null;
7396 }
7397
7398 try {
7399 mPolicy.removeStartingWindow(token, view);
7400 } catch (Exception e) {
7401 Log.w(TAG, "Exception when removing starting window", e);
7402 }
7403 }
7404 } break;
7405
7406 case REPORT_APPLICATION_TOKEN_WINDOWS: {
7407 final AppWindowToken wtoken = (AppWindowToken)msg.obj;
7408
7409 boolean nowVisible = msg.arg1 != 0;
7410 boolean nowGone = msg.arg2 != 0;
7411
7412 try {
7413 if (DEBUG_VISIBILITY) Log.v(
7414 TAG, "Reporting visible in " + wtoken
7415 + " visible=" + nowVisible
7416 + " gone=" + nowGone);
7417 if (nowVisible) {
7418 wtoken.appToken.windowsVisible();
7419 } else {
7420 wtoken.appToken.windowsGone();
7421 }
7422 } catch (RemoteException ex) {
7423 }
7424 } break;
Romain Guy06882f82009-06-10 13:36:04 -07007425
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007426 case WINDOW_FREEZE_TIMEOUT: {
7427 synchronized (mWindowMap) {
7428 Log.w(TAG, "Window freeze timeout expired.");
7429 int i = mWindows.size();
7430 while (i > 0) {
7431 i--;
7432 WindowState w = (WindowState)mWindows.get(i);
7433 if (w.mOrientationChanging) {
7434 w.mOrientationChanging = false;
7435 Log.w(TAG, "Force clearing orientation change: " + w);
7436 }
7437 }
7438 performLayoutAndPlaceSurfacesLocked();
7439 }
7440 break;
7441 }
Romain Guy06882f82009-06-10 13:36:04 -07007442
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007443 case HOLD_SCREEN_CHANGED: {
7444 Session oldHold;
7445 Session newHold;
7446 synchronized (mWindowMap) {
7447 oldHold = mLastReportedHold;
7448 newHold = (Session)msg.obj;
7449 mLastReportedHold = newHold;
7450 }
Romain Guy06882f82009-06-10 13:36:04 -07007451
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007452 if (oldHold != newHold) {
7453 try {
7454 if (oldHold != null) {
7455 mBatteryStats.noteStopWakelock(oldHold.mUid,
7456 "window",
7457 BatteryStats.WAKE_TYPE_WINDOW);
7458 }
7459 if (newHold != null) {
7460 mBatteryStats.noteStartWakelock(newHold.mUid,
7461 "window",
7462 BatteryStats.WAKE_TYPE_WINDOW);
7463 }
7464 } catch (RemoteException e) {
7465 }
7466 }
7467 break;
7468 }
Romain Guy06882f82009-06-10 13:36:04 -07007469
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007470 case APP_TRANSITION_TIMEOUT: {
7471 synchronized (mWindowMap) {
7472 if (mNextAppTransition != WindowManagerPolicy.TRANSIT_NONE) {
7473 if (DEBUG_APP_TRANSITIONS) Log.v(TAG,
7474 "*** APP TRANSITION TIMEOUT");
7475 mAppTransitionReady = true;
7476 mAppTransitionTimeout = true;
7477 performLayoutAndPlaceSurfacesLocked();
7478 }
7479 }
7480 break;
7481 }
Romain Guy06882f82009-06-10 13:36:04 -07007482
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007483 case PERSIST_ANIMATION_SCALE: {
7484 Settings.System.putFloat(mContext.getContentResolver(),
7485 Settings.System.WINDOW_ANIMATION_SCALE, mWindowAnimationScale);
7486 Settings.System.putFloat(mContext.getContentResolver(),
7487 Settings.System.TRANSITION_ANIMATION_SCALE, mTransitionAnimationScale);
7488 break;
7489 }
Romain Guy06882f82009-06-10 13:36:04 -07007490
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007491 case FORCE_GC: {
7492 synchronized(mWindowMap) {
7493 if (mAnimationPending) {
7494 // If we are animating, don't do the gc now but
7495 // delay a bit so we don't interrupt the animation.
7496 mH.sendMessageDelayed(mH.obtainMessage(H.FORCE_GC),
7497 2000);
7498 return;
7499 }
7500 // If we are currently rotating the display, it will
7501 // schedule a new message when done.
7502 if (mDisplayFrozen) {
7503 return;
7504 }
7505 mFreezeGcPending = 0;
7506 }
7507 Runtime.getRuntime().gc();
7508 break;
7509 }
Romain Guy06882f82009-06-10 13:36:04 -07007510
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007511 case ENABLE_SCREEN: {
7512 performEnableScreen();
7513 break;
7514 }
Romain Guy06882f82009-06-10 13:36:04 -07007515
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007516 case APP_FREEZE_TIMEOUT: {
7517 synchronized (mWindowMap) {
7518 Log.w(TAG, "App freeze timeout expired.");
7519 int i = mAppTokens.size();
7520 while (i > 0) {
7521 i--;
7522 AppWindowToken tok = mAppTokens.get(i);
7523 if (tok.freezingScreen) {
7524 Log.w(TAG, "Force clearing freeze: " + tok);
7525 unsetAppFreezingScreenLocked(tok, true, true);
7526 }
7527 }
7528 }
7529 break;
7530 }
Romain Guy06882f82009-06-10 13:36:04 -07007531
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07007532 case COMPUTE_AND_SEND_NEW_CONFIGURATION: {
Dianne Hackborncfaef692009-06-15 14:24:44 -07007533 if (updateOrientationFromAppTokensUnchecked(null, null) != null) {
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07007534 sendNewConfiguration();
7535 }
7536 break;
7537 }
Romain Guy06882f82009-06-10 13:36:04 -07007538
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007539 }
7540 }
7541 }
7542
7543 // -------------------------------------------------------------
7544 // IWindowManager API
7545 // -------------------------------------------------------------
7546
7547 public IWindowSession openSession(IInputMethodClient client,
7548 IInputContext inputContext) {
7549 if (client == null) throw new IllegalArgumentException("null client");
7550 if (inputContext == null) throw new IllegalArgumentException("null inputContext");
7551 return new Session(client, inputContext);
7552 }
7553
7554 public boolean inputMethodClientHasFocus(IInputMethodClient client) {
7555 synchronized (mWindowMap) {
7556 // The focus for the client is the window immediately below
7557 // where we would place the input method window.
7558 int idx = findDesiredInputMethodWindowIndexLocked(false);
7559 WindowState imFocus;
7560 if (idx > 0) {
7561 imFocus = (WindowState)mWindows.get(idx-1);
7562 if (imFocus != null) {
7563 if (imFocus.mSession.mClient != null &&
7564 imFocus.mSession.mClient.asBinder() == client.asBinder()) {
7565 return true;
7566 }
7567 }
7568 }
7569 }
7570 return false;
7571 }
Romain Guy06882f82009-06-10 13:36:04 -07007572
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007573 // -------------------------------------------------------------
7574 // Internals
7575 // -------------------------------------------------------------
7576
7577 final WindowState windowForClientLocked(Session session, IWindow client) {
7578 return windowForClientLocked(session, client.asBinder());
7579 }
Romain Guy06882f82009-06-10 13:36:04 -07007580
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007581 final WindowState windowForClientLocked(Session session, IBinder client) {
7582 WindowState win = mWindowMap.get(client);
7583 if (localLOGV) Log.v(
7584 TAG, "Looking up client " + client + ": " + win);
7585 if (win == null) {
7586 RuntimeException ex = new RuntimeException();
7587 Log.w(TAG, "Requested window " + client + " does not exist", ex);
7588 return null;
7589 }
7590 if (session != null && win.mSession != session) {
7591 RuntimeException ex = new RuntimeException();
7592 Log.w(TAG, "Requested window " + client + " is in session " +
7593 win.mSession + ", not " + session, ex);
7594 return null;
7595 }
7596
7597 return win;
7598 }
7599
7600 private final void assignLayersLocked() {
7601 int N = mWindows.size();
7602 int curBaseLayer = 0;
7603 int curLayer = 0;
7604 int i;
Romain Guy06882f82009-06-10 13:36:04 -07007605
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007606 for (i=0; i<N; i++) {
7607 WindowState w = (WindowState)mWindows.get(i);
7608 if (w.mBaseLayer == curBaseLayer || w.mIsImWindow) {
7609 curLayer += WINDOW_LAYER_MULTIPLIER;
7610 w.mLayer = curLayer;
7611 } else {
7612 curBaseLayer = curLayer = w.mBaseLayer;
7613 w.mLayer = curLayer;
7614 }
7615 if (w.mTargetAppToken != null) {
7616 w.mAnimLayer = w.mLayer + w.mTargetAppToken.animLayerAdjustment;
7617 } else if (w.mAppToken != null) {
7618 w.mAnimLayer = w.mLayer + w.mAppToken.animLayerAdjustment;
7619 } else {
7620 w.mAnimLayer = w.mLayer;
7621 }
7622 if (w.mIsImWindow) {
7623 w.mAnimLayer += mInputMethodAnimLayerAdjustment;
7624 }
7625 if (DEBUG_LAYERS) Log.v(TAG, "Assign layer " + w + ": "
7626 + w.mAnimLayer);
7627 //System.out.println(
7628 // "Assigned layer " + curLayer + " to " + w.mClient.asBinder());
7629 }
7630 }
7631
7632 private boolean mInLayout = false;
7633 private final void performLayoutAndPlaceSurfacesLocked() {
7634 if (mInLayout) {
Dave Bortcfe65242009-04-09 14:51:04 -07007635 if (DEBUG) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007636 throw new RuntimeException("Recursive call!");
7637 }
7638 Log.w(TAG, "performLayoutAndPlaceSurfacesLocked called while in layout");
7639 return;
7640 }
7641
7642 boolean recoveringMemory = false;
7643 if (mForceRemoves != null) {
7644 recoveringMemory = true;
7645 // Wait a little it for things to settle down, and off we go.
7646 for (int i=0; i<mForceRemoves.size(); i++) {
7647 WindowState ws = mForceRemoves.get(i);
7648 Log.i(TAG, "Force removing: " + ws);
7649 removeWindowInnerLocked(ws.mSession, ws);
7650 }
7651 mForceRemoves = null;
7652 Log.w(TAG, "Due to memory failure, waiting a bit for next layout");
7653 Object tmp = new Object();
7654 synchronized (tmp) {
7655 try {
7656 tmp.wait(250);
7657 } catch (InterruptedException e) {
7658 }
7659 }
7660 }
Romain Guy06882f82009-06-10 13:36:04 -07007661
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007662 mInLayout = true;
7663 try {
7664 performLayoutAndPlaceSurfacesLockedInner(recoveringMemory);
Romain Guy06882f82009-06-10 13:36:04 -07007665
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007666 int i = mPendingRemove.size()-1;
7667 if (i >= 0) {
7668 while (i >= 0) {
7669 WindowState w = mPendingRemove.get(i);
7670 removeWindowInnerLocked(w.mSession, w);
7671 i--;
7672 }
7673 mPendingRemove.clear();
7674
7675 mInLayout = false;
7676 assignLayersLocked();
7677 mLayoutNeeded = true;
7678 performLayoutAndPlaceSurfacesLocked();
7679
7680 } else {
7681 mInLayout = false;
7682 if (mLayoutNeeded) {
7683 requestAnimationLocked(0);
7684 }
7685 }
7686 } catch (RuntimeException e) {
7687 mInLayout = false;
7688 Log.e(TAG, "Unhandled exception while layout out windows", e);
7689 }
7690 }
7691
7692 private final void performLayoutLockedInner() {
7693 final int dw = mDisplay.getWidth();
7694 final int dh = mDisplay.getHeight();
7695
7696 final int N = mWindows.size();
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07007697 int repeats = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007698 int i;
7699
7700 // FIRST LOOP: Perform a layout, if needed.
Romain Guy06882f82009-06-10 13:36:04 -07007701
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07007702 while (mLayoutNeeded) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007703 mPolicy.beginLayoutLw(dw, dh);
7704
7705 // First perform layout of any root windows (not attached
7706 // to another window).
7707 int topAttached = -1;
7708 for (i = N-1; i >= 0; i--) {
7709 WindowState win = (WindowState) mWindows.get(i);
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07007710
7711 // Don't do layout of a window if it is not visible, or
7712 // soon won't be visible, to avoid wasting time and funky
7713 // changes while a window is animating away.
7714 final AppWindowToken atoken = win.mAppToken;
7715 final boolean gone = win.mViewVisibility == View.GONE
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007716 || !win.mRelayoutCalled
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07007717 || win.mRootToken.hidden
7718 || (atoken != null && atoken.hiddenRequested)
7719 || !win.mPolicyVisibility
7720 || win.mAttachedHidden
7721 || win.mExiting || win.mDestroying;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007722
7723 // If this view is GONE, then skip it -- keep the current
7724 // frame, and let the caller know so they can ignore it
7725 // if they want. (We do the normal layout for INVISIBLE
7726 // windows, since that means "perform layout as normal,
7727 // just don't display").
7728 if (!gone || !win.mHaveFrame) {
7729 if (!win.mLayoutAttached) {
7730 mPolicy.layoutWindowLw(win, win.mAttrs, null);
7731 } else {
7732 if (topAttached < 0) topAttached = i;
7733 }
7734 }
7735 }
Romain Guy06882f82009-06-10 13:36:04 -07007736
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007737 // Now perform layout of attached windows, which usually
7738 // depend on the position of the window they are attached to.
7739 // XXX does not deal with windows that are attached to windows
7740 // that are themselves attached.
7741 for (i = topAttached; i >= 0; i--) {
7742 WindowState win = (WindowState) mWindows.get(i);
7743
7744 // If this view is GONE, then skip it -- keep the current
7745 // frame, and let the caller know so they can ignore it
7746 // if they want. (We do the normal layout for INVISIBLE
7747 // windows, since that means "perform layout as normal,
7748 // just don't display").
7749 if (win.mLayoutAttached) {
7750 if ((win.mViewVisibility != View.GONE && win.mRelayoutCalled)
7751 || !win.mHaveFrame) {
7752 mPolicy.layoutWindowLw(win, win.mAttrs, win.mAttachedWindow);
7753 }
7754 }
7755 }
7756
Dianne Hackborn958b9ad2009-03-31 18:00:36 -07007757 if (!mPolicy.finishLayoutLw()) {
7758 mLayoutNeeded = false;
7759 } else if (repeats > 2) {
7760 Log.w(TAG, "Layout repeat aborted after too many iterations");
7761 mLayoutNeeded = false;
7762 } else {
7763 repeats++;
7764 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007765 }
7766 }
Romain Guy06882f82009-06-10 13:36:04 -07007767
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007768 private final void performLayoutAndPlaceSurfacesLockedInner(
7769 boolean recoveringMemory) {
7770 final long currentTime = SystemClock.uptimeMillis();
7771 final int dw = mDisplay.getWidth();
7772 final int dh = mDisplay.getHeight();
7773
7774 final int N = mWindows.size();
7775 int i;
7776
7777 // FIRST LOOP: Perform a layout, if needed.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007778 performLayoutLockedInner();
Romain Guy06882f82009-06-10 13:36:04 -07007779
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007780 if (mFxSession == null) {
7781 mFxSession = new SurfaceSession();
7782 }
Romain Guy06882f82009-06-10 13:36:04 -07007783
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007784 if (SHOW_TRANSACTIONS) Log.i(TAG, ">>> OPEN TRANSACTION");
7785
7786 // Initialize state of exiting tokens.
7787 for (i=mExitingTokens.size()-1; i>=0; i--) {
7788 mExitingTokens.get(i).hasVisible = false;
7789 }
7790
7791 // Initialize state of exiting applications.
7792 for (i=mExitingAppTokens.size()-1; i>=0; i--) {
7793 mExitingAppTokens.get(i).hasVisible = false;
7794 }
7795
7796 // SECOND LOOP: Execute animations and update visibility of windows.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007797 boolean orientationChangeComplete = true;
7798 Session holdScreen = null;
7799 float screenBrightness = -1;
7800 boolean focusDisplayed = false;
7801 boolean animating = false;
7802
7803 Surface.openTransaction();
7804 try {
7805 boolean restart;
7806
7807 do {
7808 final int transactionSequence = ++mTransactionSequence;
7809
7810 // Update animations of all applications, including those
7811 // associated with exiting/removed apps
7812 boolean tokensAnimating = false;
7813 final int NAT = mAppTokens.size();
7814 for (i=0; i<NAT; i++) {
7815 if (mAppTokens.get(i).stepAnimationLocked(currentTime, dw, dh)) {
7816 tokensAnimating = true;
7817 }
7818 }
7819 final int NEAT = mExitingAppTokens.size();
7820 for (i=0; i<NEAT; i++) {
7821 if (mExitingAppTokens.get(i).stepAnimationLocked(currentTime, dw, dh)) {
7822 tokensAnimating = true;
7823 }
7824 }
7825
7826 animating = tokensAnimating;
7827 restart = false;
7828
7829 boolean tokenMayBeDrawn = false;
7830
7831 mPolicy.beginAnimationLw(dw, dh);
7832
7833 for (i=N-1; i>=0; i--) {
7834 WindowState w = (WindowState)mWindows.get(i);
7835
7836 final WindowManager.LayoutParams attrs = w.mAttrs;
7837
7838 if (w.mSurface != null) {
7839 // Execute animation.
7840 w.commitFinishDrawingLocked(currentTime);
7841 if (w.stepAnimationLocked(currentTime, dw, dh)) {
7842 animating = true;
7843 //w.dump(" ");
7844 }
7845
7846 mPolicy.animatingWindowLw(w, attrs);
7847 }
7848
7849 final AppWindowToken atoken = w.mAppToken;
7850 if (atoken != null && (!atoken.allDrawn || atoken.freezingScreen)) {
7851 if (atoken.lastTransactionSequence != transactionSequence) {
7852 atoken.lastTransactionSequence = transactionSequence;
7853 atoken.numInterestingWindows = atoken.numDrawnWindows = 0;
7854 atoken.startingDisplayed = false;
7855 }
7856 if ((w.isOnScreen() || w.mAttrs.type
7857 == WindowManager.LayoutParams.TYPE_BASE_APPLICATION)
7858 && !w.mExiting && !w.mDestroying) {
7859 if (DEBUG_VISIBILITY || DEBUG_ORIENTATION) {
7860 Log.v(TAG, "Eval win " + w + ": isDisplayed="
7861 + w.isDisplayedLw()
7862 + ", isAnimating=" + w.isAnimating());
7863 if (!w.isDisplayedLw()) {
7864 Log.v(TAG, "Not displayed: s=" + w.mSurface
7865 + " pv=" + w.mPolicyVisibility
7866 + " dp=" + w.mDrawPending
7867 + " cdp=" + w.mCommitDrawPending
7868 + " ah=" + w.mAttachedHidden
7869 + " th=" + atoken.hiddenRequested
7870 + " a=" + w.mAnimating);
7871 }
7872 }
7873 if (w != atoken.startingWindow) {
7874 if (!atoken.freezingScreen || !w.mAppFreezing) {
7875 atoken.numInterestingWindows++;
7876 if (w.isDisplayedLw()) {
7877 atoken.numDrawnWindows++;
7878 if (DEBUG_VISIBILITY || DEBUG_ORIENTATION) Log.v(TAG,
7879 "tokenMayBeDrawn: " + atoken
7880 + " freezingScreen=" + atoken.freezingScreen
7881 + " mAppFreezing=" + w.mAppFreezing);
7882 tokenMayBeDrawn = true;
7883 }
7884 }
7885 } else if (w.isDisplayedLw()) {
7886 atoken.startingDisplayed = true;
7887 }
7888 }
7889 } else if (w.mReadyToShow) {
7890 w.performShowLocked();
7891 }
7892 }
7893
7894 if (mPolicy.finishAnimationLw()) {
7895 restart = true;
7896 }
7897
7898 if (tokenMayBeDrawn) {
7899 // See if any windows have been drawn, so they (and others
7900 // associated with them) can now be shown.
7901 final int NT = mTokenList.size();
7902 for (i=0; i<NT; i++) {
7903 AppWindowToken wtoken = mTokenList.get(i).appWindowToken;
7904 if (wtoken == null) {
7905 continue;
7906 }
7907 if (wtoken.freezingScreen) {
7908 int numInteresting = wtoken.numInterestingWindows;
7909 if (numInteresting > 0 && wtoken.numDrawnWindows >= numInteresting) {
7910 if (DEBUG_VISIBILITY) Log.v(TAG,
7911 "allDrawn: " + wtoken
7912 + " interesting=" + numInteresting
7913 + " drawn=" + wtoken.numDrawnWindows);
7914 wtoken.showAllWindowsLocked();
7915 unsetAppFreezingScreenLocked(wtoken, false, true);
7916 orientationChangeComplete = true;
7917 }
7918 } else if (!wtoken.allDrawn) {
7919 int numInteresting = wtoken.numInterestingWindows;
7920 if (numInteresting > 0 && wtoken.numDrawnWindows >= numInteresting) {
7921 if (DEBUG_VISIBILITY) Log.v(TAG,
7922 "allDrawn: " + wtoken
7923 + " interesting=" + numInteresting
7924 + " drawn=" + wtoken.numDrawnWindows);
7925 wtoken.allDrawn = true;
7926 restart = true;
7927
7928 // We can now show all of the drawn windows!
7929 if (!mOpeningApps.contains(wtoken)) {
7930 wtoken.showAllWindowsLocked();
7931 }
7932 }
7933 }
7934 }
7935 }
7936
7937 // If we are ready to perform an app transition, check through
7938 // all of the app tokens to be shown and see if they are ready
7939 // to go.
7940 if (mAppTransitionReady) {
7941 int NN = mOpeningApps.size();
7942 boolean goodToGo = true;
7943 if (DEBUG_APP_TRANSITIONS) Log.v(TAG,
7944 "Checking " + NN + " opening apps (frozen="
7945 + mDisplayFrozen + " timeout="
7946 + mAppTransitionTimeout + ")...");
7947 if (!mDisplayFrozen && !mAppTransitionTimeout) {
7948 // If the display isn't frozen, wait to do anything until
7949 // all of the apps are ready. Otherwise just go because
7950 // we'll unfreeze the display when everyone is ready.
7951 for (i=0; i<NN && goodToGo; i++) {
7952 AppWindowToken wtoken = mOpeningApps.get(i);
7953 if (DEBUG_APP_TRANSITIONS) Log.v(TAG,
7954 "Check opening app" + wtoken + ": allDrawn="
7955 + wtoken.allDrawn + " startingDisplayed="
7956 + wtoken.startingDisplayed);
7957 if (!wtoken.allDrawn && !wtoken.startingDisplayed
7958 && !wtoken.startingMoved) {
7959 goodToGo = false;
7960 }
7961 }
7962 }
7963 if (goodToGo) {
7964 if (DEBUG_APP_TRANSITIONS) Log.v(TAG, "**** GOOD TO GO");
7965 int transit = mNextAppTransition;
7966 if (mSkipAppTransitionAnimation) {
7967 transit = WindowManagerPolicy.TRANSIT_NONE;
7968 }
7969 mNextAppTransition = WindowManagerPolicy.TRANSIT_NONE;
7970 mAppTransitionReady = false;
7971 mAppTransitionTimeout = false;
7972 mStartingIconInTransition = false;
7973 mSkipAppTransitionAnimation = false;
7974
7975 mH.removeMessages(H.APP_TRANSITION_TIMEOUT);
7976
7977 // We need to figure out which animation to use...
7978 WindowManager.LayoutParams lp = findAnimations(mAppTokens,
7979 mOpeningApps, mClosingApps);
7980
7981 NN = mOpeningApps.size();
7982 for (i=0; i<NN; i++) {
7983 AppWindowToken wtoken = mOpeningApps.get(i);
7984 if (DEBUG_APP_TRANSITIONS) Log.v(TAG,
7985 "Now opening app" + wtoken);
7986 wtoken.reportedVisible = false;
7987 wtoken.inPendingTransaction = false;
7988 setTokenVisibilityLocked(wtoken, lp, true, transit, false);
7989 wtoken.updateReportedVisibilityLocked();
7990 wtoken.showAllWindowsLocked();
7991 }
7992 NN = mClosingApps.size();
7993 for (i=0; i<NN; i++) {
7994 AppWindowToken wtoken = mClosingApps.get(i);
7995 if (DEBUG_APP_TRANSITIONS) Log.v(TAG,
7996 "Now closing app" + wtoken);
7997 wtoken.inPendingTransaction = false;
7998 setTokenVisibilityLocked(wtoken, lp, false, transit, false);
7999 wtoken.updateReportedVisibilityLocked();
8000 // Force the allDrawn flag, because we want to start
8001 // this guy's animations regardless of whether it's
8002 // gotten drawn.
8003 wtoken.allDrawn = true;
8004 }
8005
8006 mOpeningApps.clear();
8007 mClosingApps.clear();
8008
8009 // This has changed the visibility of windows, so perform
8010 // a new layout to get them all up-to-date.
8011 mLayoutNeeded = true;
8012 moveInputMethodWindowsIfNeededLocked(true);
8013 performLayoutLockedInner();
8014 updateFocusedWindowLocked(UPDATE_FOCUS_PLACING_SURFACES);
8015
8016 restart = true;
8017 }
8018 }
8019 } while (restart);
8020
8021 // THIRD LOOP: Update the surfaces of all windows.
8022
8023 final boolean someoneLosingFocus = mLosingFocus.size() != 0;
8024
8025 boolean obscured = false;
8026 boolean blurring = false;
8027 boolean dimming = false;
8028 boolean covered = false;
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07008029 boolean syswin = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008030
8031 for (i=N-1; i>=0; i--) {
8032 WindowState w = (WindowState)mWindows.get(i);
8033
8034 boolean displayed = false;
8035 final WindowManager.LayoutParams attrs = w.mAttrs;
8036 final int attrFlags = attrs.flags;
8037
8038 if (w.mSurface != null) {
8039 w.computeShownFrameLocked();
8040 if (localLOGV) Log.v(
8041 TAG, "Placing surface #" + i + " " + w.mSurface
8042 + ": new=" + w.mShownFrame + ", old="
8043 + w.mLastShownFrame);
8044
8045 boolean resize;
8046 int width, height;
8047 if ((w.mAttrs.flags & w.mAttrs.FLAG_SCALED) != 0) {
8048 resize = w.mLastRequestedWidth != w.mRequestedWidth ||
8049 w.mLastRequestedHeight != w.mRequestedHeight;
8050 // for a scaled surface, we just want to use
8051 // the requested size.
8052 width = w.mRequestedWidth;
8053 height = w.mRequestedHeight;
8054 w.mLastRequestedWidth = width;
8055 w.mLastRequestedHeight = height;
8056 w.mLastShownFrame.set(w.mShownFrame);
8057 try {
8058 w.mSurface.setPosition(w.mShownFrame.left, w.mShownFrame.top);
8059 } catch (RuntimeException e) {
8060 Log.w(TAG, "Error positioning surface in " + w, e);
8061 if (!recoveringMemory) {
8062 reclaimSomeSurfaceMemoryLocked(w, "position");
8063 }
8064 }
8065 } else {
8066 resize = !w.mLastShownFrame.equals(w.mShownFrame);
8067 width = w.mShownFrame.width();
8068 height = w.mShownFrame.height();
8069 w.mLastShownFrame.set(w.mShownFrame);
8070 if (resize) {
8071 if (SHOW_TRANSACTIONS) Log.i(
8072 TAG, " SURFACE " + w.mSurface + ": ("
8073 + w.mShownFrame.left + ","
8074 + w.mShownFrame.top + ") ("
8075 + w.mShownFrame.width() + "x"
8076 + w.mShownFrame.height() + ")");
8077 }
8078 }
8079
8080 if (resize) {
8081 if (width < 1) width = 1;
8082 if (height < 1) height = 1;
8083 if (w.mSurface != null) {
8084 try {
8085 w.mSurface.setSize(width, height);
8086 w.mSurface.setPosition(w.mShownFrame.left,
8087 w.mShownFrame.top);
8088 } catch (RuntimeException e) {
8089 // If something goes wrong with the surface (such
8090 // as running out of memory), don't take down the
8091 // entire system.
8092 Log.e(TAG, "Failure updating surface of " + w
8093 + "size=(" + width + "x" + height
8094 + "), pos=(" + w.mShownFrame.left
8095 + "," + w.mShownFrame.top + ")", e);
8096 if (!recoveringMemory) {
8097 reclaimSomeSurfaceMemoryLocked(w, "size");
8098 }
8099 }
8100 }
8101 }
8102 if (!w.mAppFreezing) {
8103 w.mContentInsetsChanged =
8104 !w.mLastContentInsets.equals(w.mContentInsets);
8105 w.mVisibleInsetsChanged =
8106 !w.mLastVisibleInsets.equals(w.mVisibleInsets);
Romain Guy06882f82009-06-10 13:36:04 -07008107 if (!w.mLastFrame.equals(w.mFrame)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008108 || w.mContentInsetsChanged
8109 || w.mVisibleInsetsChanged) {
8110 w.mLastFrame.set(w.mFrame);
8111 w.mLastContentInsets.set(w.mContentInsets);
8112 w.mLastVisibleInsets.set(w.mVisibleInsets);
8113 // If the orientation is changing, then we need to
8114 // hold off on unfreezing the display until this
8115 // window has been redrawn; to do that, we need
8116 // to go through the process of getting informed
8117 // by the application when it has finished drawing.
8118 if (w.mOrientationChanging) {
8119 if (DEBUG_ORIENTATION) Log.v(TAG,
8120 "Orientation start waiting for draw in "
8121 + w + ", surface " + w.mSurface);
8122 w.mDrawPending = true;
8123 w.mCommitDrawPending = false;
8124 w.mReadyToShow = false;
8125 if (w.mAppToken != null) {
8126 w.mAppToken.allDrawn = false;
8127 }
8128 }
Romain Guy06882f82009-06-10 13:36:04 -07008129 if (DEBUG_ORIENTATION) Log.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008130 "Resizing window " + w + " to " + w.mFrame);
8131 mResizingWindows.add(w);
8132 } else if (w.mOrientationChanging) {
8133 if (!w.mDrawPending && !w.mCommitDrawPending) {
8134 if (DEBUG_ORIENTATION) Log.v(TAG,
8135 "Orientation not waiting for draw in "
8136 + w + ", surface " + w.mSurface);
8137 w.mOrientationChanging = false;
8138 }
8139 }
8140 }
8141
8142 if (w.mAttachedHidden) {
8143 if (!w.mLastHidden) {
8144 //dump();
8145 w.mLastHidden = true;
8146 if (SHOW_TRANSACTIONS) Log.i(
8147 TAG, " SURFACE " + w.mSurface + ": HIDE (performLayout-attached)");
8148 if (w.mSurface != null) {
8149 try {
8150 w.mSurface.hide();
8151 } catch (RuntimeException e) {
8152 Log.w(TAG, "Exception hiding surface in " + w);
8153 }
8154 }
8155 mKeyWaiter.releasePendingPointerLocked(w.mSession);
8156 }
8157 // If we are waiting for this window to handle an
8158 // orientation change, well, it is hidden, so
8159 // doesn't really matter. Note that this does
8160 // introduce a potential glitch if the window
8161 // becomes unhidden before it has drawn for the
8162 // new orientation.
8163 if (w.mOrientationChanging) {
8164 w.mOrientationChanging = false;
8165 if (DEBUG_ORIENTATION) Log.v(TAG,
8166 "Orientation change skips hidden " + w);
8167 }
8168 } else if (!w.isReadyForDisplay()) {
8169 if (!w.mLastHidden) {
8170 //dump();
8171 w.mLastHidden = true;
8172 if (SHOW_TRANSACTIONS) Log.i(
8173 TAG, " SURFACE " + w.mSurface + ": HIDE (performLayout-ready)");
8174 if (w.mSurface != null) {
8175 try {
8176 w.mSurface.hide();
8177 } catch (RuntimeException e) {
8178 Log.w(TAG, "Exception exception hiding surface in " + w);
8179 }
8180 }
8181 mKeyWaiter.releasePendingPointerLocked(w.mSession);
8182 }
8183 // If we are waiting for this window to handle an
8184 // orientation change, well, it is hidden, so
8185 // doesn't really matter. Note that this does
8186 // introduce a potential glitch if the window
8187 // becomes unhidden before it has drawn for the
8188 // new orientation.
8189 if (w.mOrientationChanging) {
8190 w.mOrientationChanging = false;
8191 if (DEBUG_ORIENTATION) Log.v(TAG,
8192 "Orientation change skips hidden " + w);
8193 }
8194 } else if (w.mLastLayer != w.mAnimLayer
8195 || w.mLastAlpha != w.mShownAlpha
8196 || w.mLastDsDx != w.mDsDx
8197 || w.mLastDtDx != w.mDtDx
8198 || w.mLastDsDy != w.mDsDy
8199 || w.mLastDtDy != w.mDtDy
8200 || w.mLastHScale != w.mHScale
8201 || w.mLastVScale != w.mVScale
8202 || w.mLastHidden) {
8203 displayed = true;
8204 w.mLastAlpha = w.mShownAlpha;
8205 w.mLastLayer = w.mAnimLayer;
8206 w.mLastDsDx = w.mDsDx;
8207 w.mLastDtDx = w.mDtDx;
8208 w.mLastDsDy = w.mDsDy;
8209 w.mLastDtDy = w.mDtDy;
8210 w.mLastHScale = w.mHScale;
8211 w.mLastVScale = w.mVScale;
8212 if (SHOW_TRANSACTIONS) Log.i(
8213 TAG, " SURFACE " + w.mSurface + ": alpha="
8214 + w.mShownAlpha + " layer=" + w.mAnimLayer);
8215 if (w.mSurface != null) {
8216 try {
8217 w.mSurface.setAlpha(w.mShownAlpha);
8218 w.mSurface.setLayer(w.mAnimLayer);
8219 w.mSurface.setMatrix(
8220 w.mDsDx*w.mHScale, w.mDtDx*w.mVScale,
8221 w.mDsDy*w.mHScale, w.mDtDy*w.mVScale);
8222 } catch (RuntimeException e) {
8223 Log.w(TAG, "Error updating surface in " + w, e);
8224 if (!recoveringMemory) {
8225 reclaimSomeSurfaceMemoryLocked(w, "update");
8226 }
8227 }
8228 }
8229
8230 if (w.mLastHidden && !w.mDrawPending
8231 && !w.mCommitDrawPending
8232 && !w.mReadyToShow) {
8233 if (SHOW_TRANSACTIONS) Log.i(
8234 TAG, " SURFACE " + w.mSurface + ": SHOW (performLayout)");
8235 if (DEBUG_VISIBILITY) Log.v(TAG, "Showing " + w
8236 + " during relayout");
8237 if (showSurfaceRobustlyLocked(w)) {
8238 w.mHasDrawn = true;
8239 w.mLastHidden = false;
8240 } else {
8241 w.mOrientationChanging = false;
8242 }
8243 }
8244 if (w.mSurface != null) {
8245 w.mToken.hasVisible = true;
8246 }
8247 } else {
8248 displayed = true;
8249 }
8250
8251 if (displayed) {
8252 if (!covered) {
8253 if (attrs.width == LayoutParams.FILL_PARENT
8254 && attrs.height == LayoutParams.FILL_PARENT) {
8255 covered = true;
8256 }
8257 }
8258 if (w.mOrientationChanging) {
8259 if (w.mDrawPending || w.mCommitDrawPending) {
8260 orientationChangeComplete = false;
8261 if (DEBUG_ORIENTATION) Log.v(TAG,
8262 "Orientation continue waiting for draw in " + w);
8263 } else {
8264 w.mOrientationChanging = false;
8265 if (DEBUG_ORIENTATION) Log.v(TAG,
8266 "Orientation change complete in " + w);
8267 }
8268 }
8269 w.mToken.hasVisible = true;
8270 }
8271 } else if (w.mOrientationChanging) {
8272 if (DEBUG_ORIENTATION) Log.v(TAG,
8273 "Orientation change skips hidden " + w);
8274 w.mOrientationChanging = false;
8275 }
8276
8277 final boolean canBeSeen = w.isDisplayedLw();
8278
8279 if (someoneLosingFocus && w == mCurrentFocus && canBeSeen) {
8280 focusDisplayed = true;
8281 }
8282
8283 // Update effect.
8284 if (!obscured) {
8285 if (w.mSurface != null) {
8286 if ((attrFlags&FLAG_KEEP_SCREEN_ON) != 0) {
8287 holdScreen = w.mSession;
8288 }
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07008289 if (!syswin && w.mAttrs.screenBrightness >= 0
8290 && screenBrightness < 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008291 screenBrightness = w.mAttrs.screenBrightness;
8292 }
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07008293 if (attrs.type == WindowManager.LayoutParams.TYPE_SYSTEM_DIALOG
8294 || attrs.type == WindowManager.LayoutParams.TYPE_KEYGUARD
8295 || attrs.type == WindowManager.LayoutParams.TYPE_SYSTEM_ERROR) {
8296 syswin = true;
8297 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008298 }
8299 if (w.isFullscreenOpaque(dw, dh)) {
8300 // This window completely covers everything behind it,
8301 // so we want to leave all of them as unblurred (for
8302 // performance reasons).
8303 obscured = true;
8304 } else if (canBeSeen && !obscured &&
8305 (attrFlags&FLAG_BLUR_BEHIND|FLAG_DIM_BEHIND) != 0) {
8306 if (localLOGV) Log.v(TAG, "Win " + w
8307 + ": blurring=" + blurring
8308 + " obscured=" + obscured
8309 + " displayed=" + displayed);
8310 if ((attrFlags&FLAG_DIM_BEHIND) != 0) {
8311 if (!dimming) {
8312 //Log.i(TAG, "DIM BEHIND: " + w);
8313 dimming = true;
8314 mDimShown = true;
8315 if (mDimSurface == null) {
8316 if (SHOW_TRANSACTIONS) Log.i(TAG, " DIM "
8317 + mDimSurface + ": CREATE");
8318 try {
Romain Guy06882f82009-06-10 13:36:04 -07008319 mDimSurface = new Surface(mFxSession, 0,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008320 -1, 16, 16,
8321 PixelFormat.OPAQUE,
8322 Surface.FX_SURFACE_DIM);
8323 } catch (Exception e) {
8324 Log.e(TAG, "Exception creating Dim surface", e);
8325 }
8326 }
8327 if (SHOW_TRANSACTIONS) Log.i(TAG, " DIM "
8328 + mDimSurface + ": SHOW pos=(0,0) (" +
8329 dw + "x" + dh + "), layer=" + (w.mAnimLayer-1));
8330 if (mDimSurface != null) {
8331 try {
8332 mDimSurface.setPosition(0, 0);
8333 mDimSurface.setSize(dw, dh);
8334 mDimSurface.show();
8335 } catch (RuntimeException e) {
8336 Log.w(TAG, "Failure showing dim surface", e);
8337 }
8338 }
8339 }
8340 mDimSurface.setLayer(w.mAnimLayer-1);
8341 final float target = w.mExiting ? 0 : attrs.dimAmount;
8342 if (mDimTargetAlpha != target) {
8343 // If the desired dim level has changed, then
8344 // start an animation to it.
8345 mLastDimAnimTime = currentTime;
8346 long duration = (w.mAnimating && w.mAnimation != null)
8347 ? w.mAnimation.computeDurationHint()
8348 : DEFAULT_DIM_DURATION;
8349 if (target > mDimTargetAlpha) {
8350 // This is happening behind the activity UI,
8351 // so we can make it run a little longer to
8352 // give a stronger impression without disrupting
8353 // the user.
8354 duration *= DIM_DURATION_MULTIPLIER;
8355 }
8356 if (duration < 1) {
8357 // Don't divide by zero
8358 duration = 1;
8359 }
8360 mDimTargetAlpha = target;
8361 mDimDeltaPerMs = (mDimTargetAlpha-mDimCurrentAlpha)
8362 / duration;
8363 }
8364 }
8365 if ((attrFlags&FLAG_BLUR_BEHIND) != 0) {
8366 if (!blurring) {
8367 //Log.i(TAG, "BLUR BEHIND: " + w);
8368 blurring = true;
8369 mBlurShown = true;
8370 if (mBlurSurface == null) {
8371 if (SHOW_TRANSACTIONS) Log.i(TAG, " BLUR "
8372 + mBlurSurface + ": CREATE");
8373 try {
Romain Guy06882f82009-06-10 13:36:04 -07008374 mBlurSurface = new Surface(mFxSession, 0,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008375 -1, 16, 16,
8376 PixelFormat.OPAQUE,
8377 Surface.FX_SURFACE_BLUR);
8378 } catch (Exception e) {
8379 Log.e(TAG, "Exception creating Blur surface", e);
8380 }
8381 }
8382 if (SHOW_TRANSACTIONS) Log.i(TAG, " BLUR "
8383 + mBlurSurface + ": SHOW pos=(0,0) (" +
8384 dw + "x" + dh + "), layer=" + (w.mAnimLayer-1));
8385 if (mBlurSurface != null) {
8386 mBlurSurface.setPosition(0, 0);
8387 mBlurSurface.setSize(dw, dh);
8388 try {
8389 mBlurSurface.show();
8390 } catch (RuntimeException e) {
8391 Log.w(TAG, "Failure showing blur surface", e);
8392 }
8393 }
8394 }
8395 mBlurSurface.setLayer(w.mAnimLayer-2);
8396 }
8397 }
8398 }
8399 }
8400
8401 if (!dimming && mDimShown) {
8402 // Time to hide the dim surface... start fading.
8403 if (mDimTargetAlpha != 0) {
8404 mLastDimAnimTime = currentTime;
8405 mDimTargetAlpha = 0;
8406 mDimDeltaPerMs = (-mDimCurrentAlpha) / DEFAULT_DIM_DURATION;
8407 }
8408 }
8409
8410 if (mDimShown && mLastDimAnimTime != 0) {
8411 mDimCurrentAlpha += mDimDeltaPerMs
8412 * (currentTime-mLastDimAnimTime);
8413 boolean more = true;
8414 if (mDisplayFrozen) {
8415 // If the display is frozen, there is no reason to animate.
8416 more = false;
8417 } else if (mDimDeltaPerMs > 0) {
8418 if (mDimCurrentAlpha > mDimTargetAlpha) {
8419 more = false;
8420 }
8421 } else if (mDimDeltaPerMs < 0) {
8422 if (mDimCurrentAlpha < mDimTargetAlpha) {
8423 more = false;
8424 }
8425 } else {
8426 more = false;
8427 }
Romain Guy06882f82009-06-10 13:36:04 -07008428
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008429 // Do we need to continue animating?
8430 if (more) {
8431 if (SHOW_TRANSACTIONS) Log.i(TAG, " DIM "
8432 + mDimSurface + ": alpha=" + mDimCurrentAlpha);
8433 mLastDimAnimTime = currentTime;
8434 mDimSurface.setAlpha(mDimCurrentAlpha);
8435 animating = true;
8436 } else {
8437 mDimCurrentAlpha = mDimTargetAlpha;
8438 mLastDimAnimTime = 0;
8439 if (SHOW_TRANSACTIONS) Log.i(TAG, " DIM "
8440 + mDimSurface + ": final alpha=" + mDimCurrentAlpha);
8441 mDimSurface.setAlpha(mDimCurrentAlpha);
8442 if (!dimming) {
8443 if (SHOW_TRANSACTIONS) Log.i(TAG, " DIM " + mDimSurface
8444 + ": HIDE");
8445 try {
8446 mDimSurface.hide();
8447 } catch (RuntimeException e) {
8448 Log.w(TAG, "Illegal argument exception hiding dim surface");
8449 }
8450 mDimShown = false;
8451 }
8452 }
8453 }
Romain Guy06882f82009-06-10 13:36:04 -07008454
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008455 if (!blurring && mBlurShown) {
8456 if (SHOW_TRANSACTIONS) Log.i(TAG, " BLUR " + mBlurSurface
8457 + ": HIDE");
8458 try {
8459 mBlurSurface.hide();
8460 } catch (IllegalArgumentException e) {
8461 Log.w(TAG, "Illegal argument exception hiding blur surface");
8462 }
8463 mBlurShown = false;
8464 }
8465
8466 if (SHOW_TRANSACTIONS) Log.i(TAG, "<<< CLOSE TRANSACTION");
8467 } catch (RuntimeException e) {
8468 Log.e(TAG, "Unhandled exception in Window Manager", e);
8469 }
8470
8471 Surface.closeTransaction();
Romain Guy06882f82009-06-10 13:36:04 -07008472
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008473 if (DEBUG_ORIENTATION && mDisplayFrozen) Log.v(TAG,
8474 "With display frozen, orientationChangeComplete="
8475 + orientationChangeComplete);
8476 if (orientationChangeComplete) {
8477 if (mWindowsFreezingScreen) {
8478 mWindowsFreezingScreen = false;
8479 mH.removeMessages(H.WINDOW_FREEZE_TIMEOUT);
8480 }
8481 if (mAppsFreezingScreen == 0) {
8482 stopFreezingDisplayLocked();
8483 }
8484 }
Romain Guy06882f82009-06-10 13:36:04 -07008485
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008486 i = mResizingWindows.size();
8487 if (i > 0) {
8488 do {
8489 i--;
8490 WindowState win = mResizingWindows.get(i);
8491 try {
8492 win.mClient.resized(win.mFrame.width(),
8493 win.mFrame.height(), win.mLastContentInsets,
8494 win.mLastVisibleInsets, win.mDrawPending);
8495 win.mContentInsetsChanged = false;
8496 win.mVisibleInsetsChanged = false;
8497 } catch (RemoteException e) {
8498 win.mOrientationChanging = false;
8499 }
8500 } while (i > 0);
8501 mResizingWindows.clear();
8502 }
Romain Guy06882f82009-06-10 13:36:04 -07008503
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008504 // Destroy the surface of any windows that are no longer visible.
8505 i = mDestroySurface.size();
8506 if (i > 0) {
8507 do {
8508 i--;
8509 WindowState win = mDestroySurface.get(i);
8510 win.mDestroying = false;
8511 if (mInputMethodWindow == win) {
8512 mInputMethodWindow = null;
8513 }
8514 win.destroySurfaceLocked();
8515 } while (i > 0);
8516 mDestroySurface.clear();
8517 }
8518
8519 // Time to remove any exiting tokens?
8520 for (i=mExitingTokens.size()-1; i>=0; i--) {
8521 WindowToken token = mExitingTokens.get(i);
8522 if (!token.hasVisible) {
8523 mExitingTokens.remove(i);
8524 }
8525 }
8526
8527 // Time to remove any exiting applications?
8528 for (i=mExitingAppTokens.size()-1; i>=0; i--) {
8529 AppWindowToken token = mExitingAppTokens.get(i);
8530 if (!token.hasVisible && !mClosingApps.contains(token)) {
8531 mAppTokens.remove(token);
8532 mExitingAppTokens.remove(i);
8533 }
8534 }
8535
8536 if (focusDisplayed) {
8537 mH.sendEmptyMessage(H.REPORT_LOSING_FOCUS);
8538 }
8539 if (animating) {
8540 requestAnimationLocked(currentTime+(1000/60)-SystemClock.uptimeMillis());
8541 }
8542 mQueue.setHoldScreenLocked(holdScreen != null);
8543 if (screenBrightness < 0 || screenBrightness > 1.0f) {
8544 mPowerManager.setScreenBrightnessOverride(-1);
8545 } else {
8546 mPowerManager.setScreenBrightnessOverride((int)
8547 (screenBrightness * Power.BRIGHTNESS_ON));
8548 }
8549 if (holdScreen != mHoldingScreenOn) {
8550 mHoldingScreenOn = holdScreen;
8551 Message m = mH.obtainMessage(H.HOLD_SCREEN_CHANGED, holdScreen);
8552 mH.sendMessage(m);
8553 }
8554 }
8555
8556 void requestAnimationLocked(long delay) {
8557 if (!mAnimationPending) {
8558 mAnimationPending = true;
8559 mH.sendMessageDelayed(mH.obtainMessage(H.ANIMATE), delay);
8560 }
8561 }
Romain Guy06882f82009-06-10 13:36:04 -07008562
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008563 /**
8564 * Have the surface flinger show a surface, robustly dealing with
8565 * error conditions. In particular, if there is not enough memory
8566 * to show the surface, then we will try to get rid of other surfaces
8567 * in order to succeed.
Romain Guy06882f82009-06-10 13:36:04 -07008568 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008569 * @return Returns true if the surface was successfully shown.
8570 */
8571 boolean showSurfaceRobustlyLocked(WindowState win) {
8572 try {
8573 if (win.mSurface != null) {
8574 win.mSurface.show();
8575 }
8576 return true;
8577 } catch (RuntimeException e) {
8578 Log.w(TAG, "Failure showing surface " + win.mSurface + " in " + win);
8579 }
Romain Guy06882f82009-06-10 13:36:04 -07008580
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008581 reclaimSomeSurfaceMemoryLocked(win, "show");
Romain Guy06882f82009-06-10 13:36:04 -07008582
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008583 return false;
8584 }
Romain Guy06882f82009-06-10 13:36:04 -07008585
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008586 void reclaimSomeSurfaceMemoryLocked(WindowState win, String operation) {
8587 final Surface surface = win.mSurface;
Romain Guy06882f82009-06-10 13:36:04 -07008588
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008589 EventLog.writeEvent(LOG_WM_NO_SURFACE_MEMORY, win.toString(),
8590 win.mSession.mPid, operation);
Romain Guy06882f82009-06-10 13:36:04 -07008591
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008592 if (mForceRemoves == null) {
8593 mForceRemoves = new ArrayList<WindowState>();
8594 }
Romain Guy06882f82009-06-10 13:36:04 -07008595
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008596 long callingIdentity = Binder.clearCallingIdentity();
8597 try {
8598 // There was some problem... first, do a sanity check of the
8599 // window list to make sure we haven't left any dangling surfaces
8600 // around.
8601 int N = mWindows.size();
8602 boolean leakedSurface = false;
8603 Log.i(TAG, "Out of memory for surface! Looking for leaks...");
8604 for (int i=0; i<N; i++) {
8605 WindowState ws = (WindowState)mWindows.get(i);
8606 if (ws.mSurface != null) {
8607 if (!mSessions.contains(ws.mSession)) {
8608 Log.w(TAG, "LEAKED SURFACE (session doesn't exist): "
8609 + ws + " surface=" + ws.mSurface
8610 + " token=" + win.mToken
8611 + " pid=" + ws.mSession.mPid
8612 + " uid=" + ws.mSession.mUid);
8613 ws.mSurface.clear();
8614 ws.mSurface = null;
8615 mForceRemoves.add(ws);
8616 i--;
8617 N--;
8618 leakedSurface = true;
8619 } else if (win.mAppToken != null && win.mAppToken.clientHidden) {
8620 Log.w(TAG, "LEAKED SURFACE (app token hidden): "
8621 + ws + " surface=" + ws.mSurface
8622 + " token=" + win.mAppToken);
8623 ws.mSurface.clear();
8624 ws.mSurface = null;
8625 leakedSurface = true;
8626 }
8627 }
8628 }
Romain Guy06882f82009-06-10 13:36:04 -07008629
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008630 boolean killedApps = false;
8631 if (!leakedSurface) {
8632 Log.w(TAG, "No leaked surfaces; killing applicatons!");
8633 SparseIntArray pidCandidates = new SparseIntArray();
8634 for (int i=0; i<N; i++) {
8635 WindowState ws = (WindowState)mWindows.get(i);
8636 if (ws.mSurface != null) {
8637 pidCandidates.append(ws.mSession.mPid, ws.mSession.mPid);
8638 }
8639 }
8640 if (pidCandidates.size() > 0) {
8641 int[] pids = new int[pidCandidates.size()];
8642 for (int i=0; i<pids.length; i++) {
8643 pids[i] = pidCandidates.keyAt(i);
8644 }
8645 try {
8646 if (mActivityManager.killPidsForMemory(pids)) {
8647 killedApps = true;
8648 }
8649 } catch (RemoteException e) {
8650 }
8651 }
8652 }
Romain Guy06882f82009-06-10 13:36:04 -07008653
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008654 if (leakedSurface || killedApps) {
8655 // We managed to reclaim some memory, so get rid of the trouble
8656 // surface and ask the app to request another one.
8657 Log.w(TAG, "Looks like we have reclaimed some memory, clearing surface for retry.");
8658 if (surface != null) {
8659 surface.clear();
8660 win.mSurface = null;
8661 }
Romain Guy06882f82009-06-10 13:36:04 -07008662
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008663 try {
8664 win.mClient.dispatchGetNewSurface();
8665 } catch (RemoteException e) {
8666 }
8667 }
8668 } finally {
8669 Binder.restoreCallingIdentity(callingIdentity);
8670 }
8671 }
Romain Guy06882f82009-06-10 13:36:04 -07008672
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008673 private boolean updateFocusedWindowLocked(int mode) {
8674 WindowState newFocus = computeFocusedWindowLocked();
8675 if (mCurrentFocus != newFocus) {
8676 // This check makes sure that we don't already have the focus
8677 // change message pending.
8678 mH.removeMessages(H.REPORT_FOCUS_CHANGE);
8679 mH.sendEmptyMessage(H.REPORT_FOCUS_CHANGE);
8680 if (localLOGV) Log.v(
8681 TAG, "Changing focus from " + mCurrentFocus + " to " + newFocus);
8682 final WindowState oldFocus = mCurrentFocus;
8683 mCurrentFocus = newFocus;
8684 mLosingFocus.remove(newFocus);
Romain Guy06882f82009-06-10 13:36:04 -07008685
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008686 final WindowState imWindow = mInputMethodWindow;
8687 if (newFocus != imWindow && oldFocus != imWindow) {
The Android Open Source Projectc474dec2009-03-04 09:49:09 -08008688 if (moveInputMethodWindowsIfNeededLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008689 mode != UPDATE_FOCUS_WILL_ASSIGN_LAYERS &&
The Android Open Source Projectc474dec2009-03-04 09:49:09 -08008690 mode != UPDATE_FOCUS_WILL_PLACE_SURFACES)) {
8691 mLayoutNeeded = true;
8692 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008693 if (mode == UPDATE_FOCUS_PLACING_SURFACES) {
8694 performLayoutLockedInner();
The Android Open Source Projectc474dec2009-03-04 09:49:09 -08008695 } else if (mode == UPDATE_FOCUS_WILL_PLACE_SURFACES) {
8696 // Client will do the layout, but we need to assign layers
8697 // for handleNewWindowLocked() below.
8698 assignLayersLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008699 }
8700 }
Romain Guy06882f82009-06-10 13:36:04 -07008701
The Android Open Source Projectc474dec2009-03-04 09:49:09 -08008702 if (newFocus != null && mode != UPDATE_FOCUS_WILL_ASSIGN_LAYERS) {
8703 mKeyWaiter.handleNewWindowLocked(newFocus);
8704 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008705 return true;
8706 }
8707 return false;
8708 }
8709
8710 private WindowState computeFocusedWindowLocked() {
8711 WindowState result = null;
8712 WindowState win;
8713
8714 int i = mWindows.size() - 1;
8715 int nextAppIndex = mAppTokens.size()-1;
8716 WindowToken nextApp = nextAppIndex >= 0
8717 ? mAppTokens.get(nextAppIndex) : null;
8718
8719 while (i >= 0) {
8720 win = (WindowState)mWindows.get(i);
8721
8722 if (localLOGV || DEBUG_FOCUS) Log.v(
8723 TAG, "Looking for focus: " + i
8724 + " = " + win
8725 + ", flags=" + win.mAttrs.flags
8726 + ", canReceive=" + win.canReceiveKeys());
8727
8728 AppWindowToken thisApp = win.mAppToken;
Romain Guy06882f82009-06-10 13:36:04 -07008729
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008730 // If this window's application has been removed, just skip it.
8731 if (thisApp != null && thisApp.removed) {
8732 i--;
8733 continue;
8734 }
Romain Guy06882f82009-06-10 13:36:04 -07008735
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008736 // If there is a focused app, don't allow focus to go to any
8737 // windows below it. If this is an application window, step
8738 // through the app tokens until we find its app.
8739 if (thisApp != null && nextApp != null && thisApp != nextApp
8740 && win.mAttrs.type != TYPE_APPLICATION_STARTING) {
8741 int origAppIndex = nextAppIndex;
8742 while (nextAppIndex > 0) {
8743 if (nextApp == mFocusedApp) {
8744 // Whoops, we are below the focused app... no focus
8745 // for you!
8746 if (localLOGV || DEBUG_FOCUS) Log.v(
8747 TAG, "Reached focused app: " + mFocusedApp);
8748 return null;
8749 }
8750 nextAppIndex--;
8751 nextApp = mAppTokens.get(nextAppIndex);
8752 if (nextApp == thisApp) {
8753 break;
8754 }
8755 }
8756 if (thisApp != nextApp) {
8757 // Uh oh, the app token doesn't exist! This shouldn't
8758 // happen, but if it does we can get totally hosed...
8759 // so restart at the original app.
8760 nextAppIndex = origAppIndex;
8761 nextApp = mAppTokens.get(nextAppIndex);
8762 }
8763 }
8764
8765 // Dispatch to this window if it is wants key events.
8766 if (win.canReceiveKeys()) {
8767 if (DEBUG_FOCUS) Log.v(
8768 TAG, "Found focus @ " + i + " = " + win);
8769 result = win;
8770 break;
8771 }
8772
8773 i--;
8774 }
8775
8776 return result;
8777 }
8778
8779 private void startFreezingDisplayLocked() {
8780 if (mDisplayFrozen) {
Chris Tate2ad63a92009-03-25 17:36:48 -07008781 // Freezing the display also suspends key event delivery, to
8782 // keep events from going astray while the display is reconfigured.
8783 // If someone has changed orientation again while the screen is
8784 // still frozen, the events will continue to be blocked while the
8785 // successive orientation change is processed. To prevent spurious
8786 // ANRs, we reset the event dispatch timeout in this case.
8787 synchronized (mKeyWaiter) {
8788 mKeyWaiter.mWasFrozen = true;
8789 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008790 return;
8791 }
Romain Guy06882f82009-06-10 13:36:04 -07008792
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008793 mScreenFrozenLock.acquire();
Romain Guy06882f82009-06-10 13:36:04 -07008794
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008795 long now = SystemClock.uptimeMillis();
8796 //Log.i(TAG, "Freezing, gc pending: " + mFreezeGcPending + ", now " + now);
8797 if (mFreezeGcPending != 0) {
8798 if (now > (mFreezeGcPending+1000)) {
8799 //Log.i(TAG, "Gc! " + now + " > " + (mFreezeGcPending+1000));
8800 mH.removeMessages(H.FORCE_GC);
8801 Runtime.getRuntime().gc();
8802 mFreezeGcPending = now;
8803 }
8804 } else {
8805 mFreezeGcPending = now;
8806 }
Romain Guy06882f82009-06-10 13:36:04 -07008807
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008808 mDisplayFrozen = true;
8809 if (mNextAppTransition != WindowManagerPolicy.TRANSIT_NONE) {
8810 mNextAppTransition = WindowManagerPolicy.TRANSIT_NONE;
8811 mAppTransitionReady = true;
8812 }
Romain Guy06882f82009-06-10 13:36:04 -07008813
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008814 if (PROFILE_ORIENTATION) {
8815 File file = new File("/data/system/frozen");
8816 Debug.startMethodTracing(file.toString(), 8 * 1024 * 1024);
8817 }
8818 Surface.freezeDisplay(0);
8819 }
Romain Guy06882f82009-06-10 13:36:04 -07008820
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008821 private void stopFreezingDisplayLocked() {
8822 if (!mDisplayFrozen) {
8823 return;
8824 }
Romain Guy06882f82009-06-10 13:36:04 -07008825
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008826 mDisplayFrozen = false;
8827 mH.removeMessages(H.APP_FREEZE_TIMEOUT);
8828 if (PROFILE_ORIENTATION) {
8829 Debug.stopMethodTracing();
8830 }
8831 Surface.unfreezeDisplay(0);
Romain Guy06882f82009-06-10 13:36:04 -07008832
Chris Tate2ad63a92009-03-25 17:36:48 -07008833 // Reset the key delivery timeout on unfreeze, too. We force a wakeup here
8834 // too because regular key delivery processing should resume immediately.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008835 synchronized (mKeyWaiter) {
8836 mKeyWaiter.mWasFrozen = true;
8837 mKeyWaiter.notifyAll();
8838 }
8839
8840 // A little kludge: a lot could have happened while the
8841 // display was frozen, so now that we are coming back we
8842 // do a gc so that any remote references the system
8843 // processes holds on others can be released if they are
8844 // no longer needed.
8845 mH.removeMessages(H.FORCE_GC);
8846 mH.sendMessageDelayed(mH.obtainMessage(H.FORCE_GC),
8847 2000);
Romain Guy06882f82009-06-10 13:36:04 -07008848
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008849 mScreenFrozenLock.release();
8850 }
Romain Guy06882f82009-06-10 13:36:04 -07008851
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008852 @Override
8853 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
8854 if (mContext.checkCallingOrSelfPermission("android.permission.DUMP")
8855 != PackageManager.PERMISSION_GRANTED) {
8856 pw.println("Permission Denial: can't dump WindowManager from from pid="
8857 + Binder.getCallingPid()
8858 + ", uid=" + Binder.getCallingUid());
8859 return;
8860 }
Romain Guy06882f82009-06-10 13:36:04 -07008861
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008862 synchronized(mWindowMap) {
8863 pw.println("Current Window Manager state:");
8864 for (int i=mWindows.size()-1; i>=0; i--) {
8865 WindowState w = (WindowState)mWindows.get(i);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008866 pw.print(" Window #"); pw.print(i); pw.print(' ');
8867 pw.print(w); pw.println(":");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008868 w.dump(pw, " ");
8869 }
8870 if (mInputMethodDialogs.size() > 0) {
8871 pw.println(" ");
8872 pw.println(" Input method dialogs:");
8873 for (int i=mInputMethodDialogs.size()-1; i>=0; i--) {
8874 WindowState w = mInputMethodDialogs.get(i);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008875 pw.print(" IM Dialog #"); pw.print(i); pw.print(": "); pw.println(w);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008876 }
8877 }
8878 if (mPendingRemove.size() > 0) {
8879 pw.println(" ");
8880 pw.println(" Remove pending for:");
8881 for (int i=mPendingRemove.size()-1; i>=0; i--) {
8882 WindowState w = mPendingRemove.get(i);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008883 pw.print(" Remove #"); pw.print(i); pw.print(' ');
8884 pw.print(w); pw.println(":");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008885 w.dump(pw, " ");
8886 }
8887 }
8888 if (mForceRemoves != null && mForceRemoves.size() > 0) {
8889 pw.println(" ");
8890 pw.println(" Windows force removing:");
8891 for (int i=mForceRemoves.size()-1; i>=0; i--) {
8892 WindowState w = mForceRemoves.get(i);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008893 pw.print(" Removing #"); pw.print(i); pw.print(' ');
8894 pw.print(w); pw.println(":");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008895 w.dump(pw, " ");
8896 }
8897 }
8898 if (mDestroySurface.size() > 0) {
8899 pw.println(" ");
8900 pw.println(" Windows waiting to destroy their surface:");
8901 for (int i=mDestroySurface.size()-1; i>=0; i--) {
8902 WindowState w = mDestroySurface.get(i);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008903 pw.print(" Destroy #"); pw.print(i); pw.print(' ');
8904 pw.print(w); pw.println(":");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008905 w.dump(pw, " ");
8906 }
8907 }
8908 if (mLosingFocus.size() > 0) {
8909 pw.println(" ");
8910 pw.println(" Windows losing focus:");
8911 for (int i=mLosingFocus.size()-1; i>=0; i--) {
8912 WindowState w = mLosingFocus.get(i);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008913 pw.print(" Losing #"); pw.print(i); pw.print(' ');
8914 pw.print(w); pw.println(":");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008915 w.dump(pw, " ");
8916 }
8917 }
8918 if (mSessions.size() > 0) {
8919 pw.println(" ");
8920 pw.println(" All active sessions:");
8921 Iterator<Session> it = mSessions.iterator();
8922 while (it.hasNext()) {
8923 Session s = it.next();
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008924 pw.print(" Session "); pw.print(s); pw.println(':');
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008925 s.dump(pw, " ");
8926 }
8927 }
8928 if (mTokenMap.size() > 0) {
8929 pw.println(" ");
8930 pw.println(" All tokens:");
8931 Iterator<WindowToken> it = mTokenMap.values().iterator();
8932 while (it.hasNext()) {
8933 WindowToken token = it.next();
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008934 pw.print(" Token "); pw.print(token.token); pw.println(':');
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008935 token.dump(pw, " ");
8936 }
8937 }
8938 if (mTokenList.size() > 0) {
8939 pw.println(" ");
8940 pw.println(" Window token list:");
8941 for (int i=0; i<mTokenList.size(); i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008942 pw.print(" #"); pw.print(i); pw.print(": ");
8943 pw.println(mTokenList.get(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008944 }
8945 }
8946 if (mAppTokens.size() > 0) {
8947 pw.println(" ");
8948 pw.println(" Application tokens in Z order:");
8949 for (int i=mAppTokens.size()-1; i>=0; i--) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008950 pw.print(" App #"); pw.print(i); pw.print(": ");
8951 pw.println(mAppTokens.get(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008952 }
8953 }
8954 if (mFinishedStarting.size() > 0) {
8955 pw.println(" ");
8956 pw.println(" Finishing start of application tokens:");
8957 for (int i=mFinishedStarting.size()-1; i>=0; i--) {
8958 WindowToken token = mFinishedStarting.get(i);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008959 pw.print(" Finished Starting #"); pw.print(i);
8960 pw.print(' '); pw.print(token); pw.println(':');
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008961 token.dump(pw, " ");
8962 }
8963 }
8964 if (mExitingTokens.size() > 0) {
8965 pw.println(" ");
8966 pw.println(" Exiting tokens:");
8967 for (int i=mExitingTokens.size()-1; i>=0; i--) {
8968 WindowToken token = mExitingTokens.get(i);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008969 pw.print(" Exiting #"); pw.print(i);
8970 pw.print(' '); pw.print(token); pw.println(':');
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008971 token.dump(pw, " ");
8972 }
8973 }
8974 if (mExitingAppTokens.size() > 0) {
8975 pw.println(" ");
8976 pw.println(" Exiting application tokens:");
8977 for (int i=mExitingAppTokens.size()-1; i>=0; i--) {
8978 WindowToken token = mExitingAppTokens.get(i);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008979 pw.print(" Exiting App #"); pw.print(i);
8980 pw.print(' '); pw.print(token); pw.println(':');
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008981 token.dump(pw, " ");
8982 }
8983 }
8984 pw.println(" ");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008985 pw.print(" mCurrentFocus="); pw.println(mCurrentFocus);
8986 pw.print(" mLastFocus="); pw.println(mLastFocus);
8987 pw.print(" mFocusedApp="); pw.println(mFocusedApp);
8988 pw.print(" mInputMethodTarget="); pw.println(mInputMethodTarget);
8989 pw.print(" mInputMethodWindow="); pw.println(mInputMethodWindow);
8990 pw.print(" mInTouchMode="); pw.println(mInTouchMode);
8991 pw.print(" mSystemBooted="); pw.print(mSystemBooted);
8992 pw.print(" mDisplayEnabled="); pw.println(mDisplayEnabled);
8993 pw.print(" mLayoutNeeded="); pw.print(mLayoutNeeded);
8994 pw.print(" mBlurShown="); pw.println(mBlurShown);
8995 pw.print(" mDimShown="); pw.print(mDimShown);
8996 pw.print(" current="); pw.print(mDimCurrentAlpha);
8997 pw.print(" target="); pw.print(mDimTargetAlpha);
8998 pw.print(" delta="); pw.print(mDimDeltaPerMs);
8999 pw.print(" lastAnimTime="); pw.println(mLastDimAnimTime);
9000 pw.print(" mInputMethodAnimLayerAdjustment=");
9001 pw.println(mInputMethodAnimLayerAdjustment);
9002 pw.print(" mDisplayFrozen="); pw.print(mDisplayFrozen);
9003 pw.print(" mWindowsFreezingScreen="); pw.print(mWindowsFreezingScreen);
9004 pw.print(" mAppsFreezingScreen="); pw.println(mAppsFreezingScreen);
9005 pw.print(" mRotation="); pw.print(mRotation);
9006 pw.print(", mForcedAppOrientation="); pw.print(mForcedAppOrientation);
9007 pw.print(", mRequestedRotation="); pw.println(mRequestedRotation);
9008 pw.print(" mAnimationPending="); pw.print(mAnimationPending);
9009 pw.print(" mWindowAnimationScale="); pw.print(mWindowAnimationScale);
9010 pw.print(" mTransitionWindowAnimationScale="); pw.println(mTransitionAnimationScale);
9011 pw.print(" mNextAppTransition=0x");
9012 pw.print(Integer.toHexString(mNextAppTransition));
9013 pw.print(", mAppTransitionReady="); pw.print(mAppTransitionReady);
9014 pw.print(", mAppTransitionTimeout="); pw.println( mAppTransitionTimeout);
9015 pw.print(" mStartingIconInTransition="); pw.print(mStartingIconInTransition);
9016 pw.print(", mSkipAppTransitionAnimation="); pw.println(mSkipAppTransitionAnimation);
9017 if (mOpeningApps.size() > 0) {
9018 pw.print(" mOpeningApps="); pw.println(mOpeningApps);
9019 }
9020 if (mClosingApps.size() > 0) {
9021 pw.print(" mClosingApps="); pw.println(mClosingApps);
9022 }
9023 pw.print(" DisplayWidth="); pw.print(mDisplay.getWidth());
9024 pw.print(" DisplayHeight="); pw.println(mDisplay.getHeight());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009025 pw.println(" KeyWaiter state:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009026 pw.print(" mLastWin="); pw.print(mKeyWaiter.mLastWin);
9027 pw.print(" mLastBinder="); pw.println(mKeyWaiter.mLastBinder);
9028 pw.print(" mFinished="); pw.print(mKeyWaiter.mFinished);
9029 pw.print(" mGotFirstWindow="); pw.print(mKeyWaiter.mGotFirstWindow);
9030 pw.print(" mEventDispatching="); pw.print(mKeyWaiter.mEventDispatching);
9031 pw.print(" mTimeToSwitch="); pw.println(mKeyWaiter.mTimeToSwitch);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009032 }
9033 }
9034
9035 public void monitor() {
9036 synchronized (mWindowMap) { }
9037 synchronized (mKeyguardDisabled) { }
9038 synchronized (mKeyWaiter) { }
9039 }
9040}