blob: 99e008cef4392295fc5192c5fe48e55ad954f8c6 [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 com.android.internal.app.IBatteryStats;
20import com.android.server.am.BatteryStatsService;
21
22import android.app.ActivityManagerNative;
23import android.app.IActivityManager;
24import android.content.BroadcastReceiver;
25import android.content.ContentQueryMap;
26import android.content.ContentResolver;
27import android.content.Context;
28import android.content.Intent;
29import android.content.IntentFilter;
30import android.content.pm.PackageManager;
31import android.database.Cursor;
Mike Lockwoodbc706a02009-07-27 13:50:57 -070032import android.hardware.Sensor;
33import android.hardware.SensorEvent;
34import android.hardware.SensorEventListener;
35import android.hardware.SensorManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080036import android.os.BatteryStats;
37import android.os.Binder;
38import android.os.Handler;
39import android.os.HandlerThread;
40import android.os.IBinder;
41import android.os.IPowerManager;
42import android.os.LocalPowerManager;
43import android.os.Power;
44import android.os.PowerManager;
45import android.os.Process;
46import android.os.RemoteException;
47import android.os.SystemClock;
48import android.provider.Settings.SettingNotFoundException;
49import android.provider.Settings;
50import android.util.EventLog;
51import android.util.Log;
52import android.view.WindowManagerPolicy;
53import static android.provider.Settings.System.DIM_SCREEN;
54import static android.provider.Settings.System.SCREEN_BRIGHTNESS;
Dan Murphy951764b2009-08-27 14:59:03 -050055import static android.provider.Settings.System.SCREEN_BRIGHTNESS_MODE;
Mike Lockwooddc3494e2009-10-14 21:17:09 -070056import static android.provider.Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080057import static android.provider.Settings.System.SCREEN_OFF_TIMEOUT;
58import static android.provider.Settings.System.STAY_ON_WHILE_PLUGGED_IN;
59
60import java.io.FileDescriptor;
61import java.io.PrintWriter;
62import java.util.ArrayList;
63import java.util.HashMap;
64import java.util.Observable;
65import java.util.Observer;
66
Mike Lockwoodbc706a02009-07-27 13:50:57 -070067class PowerManagerService extends IPowerManager.Stub
Mike Lockwood8738e0c2009-10-04 08:44:47 -040068 implements LocalPowerManager, Watchdog.Monitor {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080069
70 private static final String TAG = "PowerManagerService";
71 static final String PARTIAL_NAME = "PowerManagerService";
72
73 private static final boolean LOG_PARTIAL_WL = false;
74
75 // Indicates whether touch-down cycles should be logged as part of the
76 // LOG_POWER_SCREEN_STATE log events
77 private static final boolean LOG_TOUCH_DOWNS = true;
78
79 private static final int LOCK_MASK = PowerManager.PARTIAL_WAKE_LOCK
80 | PowerManager.SCREEN_DIM_WAKE_LOCK
81 | PowerManager.SCREEN_BRIGHT_WAKE_LOCK
Mike Lockwoodbc706a02009-07-27 13:50:57 -070082 | PowerManager.FULL_WAKE_LOCK
83 | PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080084
85 // time since last state: time since last event:
86 // The short keylight delay comes from Gservices; this is the default.
87 private static final int SHORT_KEYLIGHT_DELAY_DEFAULT = 6000; // t+6 sec
88 private static final int MEDIUM_KEYLIGHT_DELAY = 15000; // t+15 sec
89 private static final int LONG_KEYLIGHT_DELAY = 6000; // t+6 sec
90 private static final int LONG_DIM_TIME = 7000; // t+N-5 sec
91
Mike Lockwoodd20ea362009-09-15 00:13:38 -040092 // trigger proximity if distance is less than 5 cm
93 private static final float PROXIMITY_THRESHOLD = 5.0f;
94
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080095 // Cached Gservices settings; see updateGservicesValues()
96 private int mShortKeylightDelay = SHORT_KEYLIGHT_DELAY_DEFAULT;
97
98 // flags for setPowerState
99 private static final int SCREEN_ON_BIT = 0x00000001;
100 private static final int SCREEN_BRIGHT_BIT = 0x00000002;
101 private static final int BUTTON_BRIGHT_BIT = 0x00000004;
102 private static final int KEYBOARD_BRIGHT_BIT = 0x00000008;
103 private static final int BATTERY_LOW_BIT = 0x00000010;
104
105 // values for setPowerState
106
107 // SCREEN_OFF == everything off
108 private static final int SCREEN_OFF = 0x00000000;
109
110 // SCREEN_DIM == screen on, screen backlight dim
111 private static final int SCREEN_DIM = SCREEN_ON_BIT;
112
113 // SCREEN_BRIGHT == screen on, screen backlight bright
114 private static final int SCREEN_BRIGHT = SCREEN_ON_BIT | SCREEN_BRIGHT_BIT;
115
116 // SCREEN_BUTTON_BRIGHT == screen on, screen and button backlights bright
117 private static final int SCREEN_BUTTON_BRIGHT = SCREEN_BRIGHT | BUTTON_BRIGHT_BIT;
118
119 // SCREEN_BUTTON_BRIGHT == screen on, screen, button and keyboard backlights bright
120 private static final int ALL_BRIGHT = SCREEN_BUTTON_BRIGHT | KEYBOARD_BRIGHT_BIT;
121
122 // used for noChangeLights in setPowerState()
123 private static final int LIGHTS_MASK = SCREEN_BRIGHT_BIT | BUTTON_BRIGHT_BIT | KEYBOARD_BRIGHT_BIT;
124
125 static final boolean ANIMATE_SCREEN_LIGHTS = true;
126 static final boolean ANIMATE_BUTTON_LIGHTS = false;
127 static final boolean ANIMATE_KEYBOARD_LIGHTS = false;
128
129 static final int ANIM_STEPS = 60/4;
130
131 // These magic numbers are the initial state of the LEDs at boot. Ideally
132 // we should read them from the driver, but our current hardware returns 0
133 // for the initial value. Oops!
134 static final int INITIAL_SCREEN_BRIGHTNESS = 255;
135 static final int INITIAL_BUTTON_BRIGHTNESS = Power.BRIGHTNESS_OFF;
136 static final int INITIAL_KEYBOARD_BRIGHTNESS = Power.BRIGHTNESS_OFF;
137
138 static final int LOG_POWER_SLEEP_REQUESTED = 2724;
139 static final int LOG_POWER_SCREEN_BROADCAST_SEND = 2725;
140 static final int LOG_POWER_SCREEN_BROADCAST_DONE = 2726;
141 static final int LOG_POWER_SCREEN_BROADCAST_STOP = 2727;
142 static final int LOG_POWER_SCREEN_STATE = 2728;
143 static final int LOG_POWER_PARTIAL_WAKE_STATE = 2729;
144
145 private final int MY_UID;
146
147 private boolean mDoneBooting = false;
148 private int mStayOnConditions = 0;
Joe Onorato128e7292009-03-24 18:41:31 -0700149 private int[] mBroadcastQueue = new int[] { -1, -1, -1 };
150 private int[] mBroadcastWhy = new int[3];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800151 private int mPartialCount = 0;
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700152 private int mProximityCount = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800153 private int mPowerState;
154 private boolean mOffBecauseOfUser;
155 private int mUserState;
156 private boolean mKeyboardVisible = false;
157 private boolean mUserActivityAllowed = true;
Mike Lockwood36fc3022009-08-25 16:49:06 -0700158 private boolean mProximitySensorActive = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800159 private int mTotalDelaySetting;
160 private int mKeylightDelay;
161 private int mDimDelay;
162 private int mScreenOffDelay;
163 private int mWakeLockState;
164 private long mLastEventTime = 0;
165 private long mScreenOffTime;
166 private volatile WindowManagerPolicy mPolicy;
167 private final LockList mLocks = new LockList();
168 private Intent mScreenOffIntent;
169 private Intent mScreenOnIntent;
The Android Open Source Project10592532009-03-18 17:39:46 -0700170 private HardwareService mHardware;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800171 private Context mContext;
172 private UnsynchronizedWakeLock mBroadcastWakeLock;
173 private UnsynchronizedWakeLock mStayOnWhilePluggedInScreenDimLock;
174 private UnsynchronizedWakeLock mStayOnWhilePluggedInPartialLock;
175 private UnsynchronizedWakeLock mPreventScreenOnPartialLock;
176 private HandlerThread mHandlerThread;
177 private Handler mHandler;
178 private TimeoutTask mTimeoutTask = new TimeoutTask();
179 private LightAnimator mLightAnimator = new LightAnimator();
180 private final BrightnessState mScreenBrightness
The Android Open Source Project10592532009-03-18 17:39:46 -0700181 = new BrightnessState(SCREEN_BRIGHT_BIT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800182 private final BrightnessState mKeyboardBrightness
The Android Open Source Project10592532009-03-18 17:39:46 -0700183 = new BrightnessState(KEYBOARD_BRIGHT_BIT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800184 private final BrightnessState mButtonBrightness
The Android Open Source Project10592532009-03-18 17:39:46 -0700185 = new BrightnessState(BUTTON_BRIGHT_BIT);
Joe Onorato128e7292009-03-24 18:41:31 -0700186 private boolean mStillNeedSleepNotification;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800187 private boolean mIsPowered = false;
188 private IActivityManager mActivityService;
189 private IBatteryStats mBatteryStats;
190 private BatteryService mBatteryService;
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700191 private SensorManager mSensorManager;
192 private Sensor mProximitySensor;
Mike Lockwood8738e0c2009-10-04 08:44:47 -0400193 private Sensor mLightSensor;
194 private boolean mLightSensorEnabled;
195 private float mLightSensorValue = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800196 private boolean mDimScreen = true;
197 private long mNextTimeout;
198 private volatile int mPokey = 0;
199 private volatile boolean mPokeAwakeOnSet = false;
200 private volatile boolean mInitComplete = false;
201 private HashMap<IBinder,PokeLock> mPokeLocks = new HashMap<IBinder,PokeLock>();
202 private long mScreenOnTime;
203 private long mScreenOnStartTime;
204 private boolean mPreventScreenOn;
205 private int mScreenBrightnessOverride = -1;
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700206 private boolean mHasHardwareAutoBrightness;
207 private boolean mAutoBrightessEnabled;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800208
209 // Used when logging number and duration of touch-down cycles
210 private long mTotalTouchDownTime;
211 private long mLastTouchDown;
212 private int mTouchCycles;
213
214 // could be either static or controllable at runtime
215 private static final boolean mSpew = false;
Mike Lockwood8738e0c2009-10-04 08:44:47 -0400216 private static final boolean mDebugLightSensor = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800217
218 /*
219 static PrintStream mLog;
220 static {
221 try {
222 mLog = new PrintStream("/data/power.log");
223 }
224 catch (FileNotFoundException e) {
225 android.util.Log.e(TAG, "Life is hard", e);
226 }
227 }
228 static class Log {
229 static void d(String tag, String s) {
230 mLog.println(s);
231 android.util.Log.d(tag, s);
232 }
233 static void i(String tag, String s) {
234 mLog.println(s);
235 android.util.Log.i(tag, s);
236 }
237 static void w(String tag, String s) {
238 mLog.println(s);
239 android.util.Log.w(tag, s);
240 }
241 static void e(String tag, String s) {
242 mLog.println(s);
243 android.util.Log.e(tag, s);
244 }
245 }
246 */
247
248 /**
249 * This class works around a deadlock between the lock in PowerManager.WakeLock
250 * and our synchronizing on mLocks. PowerManager.WakeLock synchronizes on its
251 * mToken object so it can be accessed from any thread, but it calls into here
252 * with its lock held. This class is essentially a reimplementation of
253 * PowerManager.WakeLock, but without that extra synchronized block, because we'll
254 * only call it with our own locks held.
255 */
256 private class UnsynchronizedWakeLock {
257 int mFlags;
258 String mTag;
259 IBinder mToken;
260 int mCount = 0;
261 boolean mRefCounted;
262
263 UnsynchronizedWakeLock(int flags, String tag, boolean refCounted) {
264 mFlags = flags;
265 mTag = tag;
266 mToken = new Binder();
267 mRefCounted = refCounted;
268 }
269
270 public void acquire() {
271 if (!mRefCounted || mCount++ == 0) {
272 long ident = Binder.clearCallingIdentity();
273 try {
274 PowerManagerService.this.acquireWakeLockLocked(mFlags, mToken,
275 MY_UID, mTag);
276 } finally {
277 Binder.restoreCallingIdentity(ident);
278 }
279 }
280 }
281
282 public void release() {
283 if (!mRefCounted || --mCount == 0) {
284 PowerManagerService.this.releaseWakeLockLocked(mToken, false);
285 }
286 if (mCount < 0) {
287 throw new RuntimeException("WakeLock under-locked " + mTag);
288 }
289 }
290
291 public String toString() {
292 return "UnsynchronizedWakeLock(mFlags=0x" + Integer.toHexString(mFlags)
293 + " mCount=" + mCount + ")";
294 }
295 }
296
297 private final class BatteryReceiver extends BroadcastReceiver {
298 @Override
299 public void onReceive(Context context, Intent intent) {
300 synchronized (mLocks) {
301 boolean wasPowered = mIsPowered;
302 mIsPowered = mBatteryService.isPowered();
303
304 if (mIsPowered != wasPowered) {
305 // update mStayOnWhilePluggedIn wake lock
306 updateWakeLockLocked();
307
308 // treat plugging and unplugging the devices as a user activity.
309 // users find it disconcerting when they unplug the device
310 // and it shuts off right away.
311 // temporarily set mUserActivityAllowed to true so this will work
312 // even when the keyguard is on.
313 synchronized (mLocks) {
Mike Lockwood200b30b2009-09-20 00:23:59 -0400314 forceUserActivityLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800315 }
316 }
317 }
318 }
319 }
320
321 /**
322 * Set the setting that determines whether the device stays on when plugged in.
323 * The argument is a bit string, with each bit specifying a power source that,
324 * when the device is connected to that source, causes the device to stay on.
325 * See {@link android.os.BatteryManager} for the list of power sources that
326 * can be specified. Current values include {@link android.os.BatteryManager#BATTERY_PLUGGED_AC}
327 * and {@link android.os.BatteryManager#BATTERY_PLUGGED_USB}
328 * @param val an {@code int} containing the bits that specify which power sources
329 * should cause the device to stay on.
330 */
331 public void setStayOnSetting(int val) {
332 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SETTINGS, null);
333 Settings.System.putInt(mContext.getContentResolver(),
334 Settings.System.STAY_ON_WHILE_PLUGGED_IN, val);
335 }
336
337 private class SettingsObserver implements Observer {
338 private int getInt(String name) {
339 return mSettings.getValues(name).getAsInteger(Settings.System.VALUE);
340 }
341
342 public void update(Observable o, Object arg) {
343 synchronized (mLocks) {
344 // STAY_ON_WHILE_PLUGGED_IN
345 mStayOnConditions = getInt(STAY_ON_WHILE_PLUGGED_IN);
346 updateWakeLockLocked();
347
348 // SCREEN_OFF_TIMEOUT
349 mTotalDelaySetting = getInt(SCREEN_OFF_TIMEOUT);
350
351 // DIM_SCREEN
352 //mDimScreen = getInt(DIM_SCREEN) != 0;
353
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700354 // SCREEN_BRIGHTNESS_MODE
355 setScreenBrightnessMode(getInt(SCREEN_BRIGHTNESS_MODE));
356
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800357 // recalculate everything
358 setScreenOffTimeoutsLocked();
359 }
360 }
361 }
362
363 PowerManagerService()
364 {
365 // Hack to get our uid... should have a func for this.
366 long token = Binder.clearCallingIdentity();
367 MY_UID = Binder.getCallingUid();
368 Binder.restoreCallingIdentity(token);
369
370 // XXX remove this when the kernel doesn't timeout wake locks
371 Power.setLastUserActivityTimeout(7*24*3600*1000); // one week
372
373 // assume nothing is on yet
374 mUserState = mPowerState = 0;
375
376 // Add ourself to the Watchdog monitors.
377 Watchdog.getInstance().addMonitor(this);
378 mScreenOnStartTime = SystemClock.elapsedRealtime();
379 }
380
381 private ContentQueryMap mSettings;
382
The Android Open Source Project10592532009-03-18 17:39:46 -0700383 void init(Context context, HardwareService hardware, IActivityManager activity,
384 BatteryService battery) {
385 mHardware = hardware;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800386 mContext = context;
387 mActivityService = activity;
388 mBatteryStats = BatteryStatsService.getService();
389 mBatteryService = battery;
390
391 mHandlerThread = new HandlerThread("PowerManagerService") {
392 @Override
393 protected void onLooperPrepared() {
394 super.onLooperPrepared();
395 initInThread();
396 }
397 };
398 mHandlerThread.start();
399
400 synchronized (mHandlerThread) {
401 while (!mInitComplete) {
402 try {
403 mHandlerThread.wait();
404 } catch (InterruptedException e) {
405 // Ignore
406 }
407 }
408 }
409 }
410
411 void initInThread() {
412 mHandler = new Handler();
413
414 mBroadcastWakeLock = new UnsynchronizedWakeLock(
Joe Onorato128e7292009-03-24 18:41:31 -0700415 PowerManager.PARTIAL_WAKE_LOCK, "sleep_broadcast", true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800416 mStayOnWhilePluggedInScreenDimLock = new UnsynchronizedWakeLock(
417 PowerManager.SCREEN_DIM_WAKE_LOCK, "StayOnWhilePluggedIn Screen Dim", false);
418 mStayOnWhilePluggedInPartialLock = new UnsynchronizedWakeLock(
419 PowerManager.PARTIAL_WAKE_LOCK, "StayOnWhilePluggedIn Partial", false);
420 mPreventScreenOnPartialLock = new UnsynchronizedWakeLock(
421 PowerManager.PARTIAL_WAKE_LOCK, "PreventScreenOn Partial", false);
422
423 mScreenOnIntent = new Intent(Intent.ACTION_SCREEN_ON);
424 mScreenOnIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
425 mScreenOffIntent = new Intent(Intent.ACTION_SCREEN_OFF);
426 mScreenOffIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
427
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700428 mHasHardwareAutoBrightness = mContext.getResources().getBoolean(
429 com.android.internal.R.bool.config_hardware_automatic_brightness_available);
430
431 ContentResolver resolver = mContext.getContentResolver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800432 Cursor settingsCursor = resolver.query(Settings.System.CONTENT_URI, null,
433 "(" + Settings.System.NAME + "=?) or ("
434 + Settings.System.NAME + "=?) or ("
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700435 + Settings.System.NAME + "=?) or ("
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800436 + Settings.System.NAME + "=?)",
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700437 new String[]{STAY_ON_WHILE_PLUGGED_IN, SCREEN_OFF_TIMEOUT, DIM_SCREEN,
438 SCREEN_BRIGHTNESS_MODE},
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800439 null);
440 mSettings = new ContentQueryMap(settingsCursor, Settings.System.NAME, true, mHandler);
441 SettingsObserver settingsObserver = new SettingsObserver();
442 mSettings.addObserver(settingsObserver);
443
444 // pretend that the settings changed so we will get their initial state
445 settingsObserver.update(mSettings, null);
446
447 // register for the battery changed notifications
448 IntentFilter filter = new IntentFilter();
449 filter.addAction(Intent.ACTION_BATTERY_CHANGED);
450 mContext.registerReceiver(new BatteryReceiver(), filter);
451
452 // Listen for Gservices changes
453 IntentFilter gservicesChangedFilter =
454 new IntentFilter(Settings.Gservices.CHANGED_ACTION);
455 mContext.registerReceiver(new GservicesChangedReceiver(), gservicesChangedFilter);
456 // And explicitly do the initial update of our cached settings
457 updateGservicesValues();
458
459 // turn everything on
460 setPowerState(ALL_BRIGHT);
Dan Murphy951764b2009-08-27 14:59:03 -0500461
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800462 synchronized (mHandlerThread) {
463 mInitComplete = true;
464 mHandlerThread.notifyAll();
465 }
466 }
467
468 private class WakeLock implements IBinder.DeathRecipient
469 {
470 WakeLock(int f, IBinder b, String t, int u) {
471 super();
472 flags = f;
473 binder = b;
474 tag = t;
475 uid = u == MY_UID ? Process.SYSTEM_UID : u;
476 if (u != MY_UID || (
477 !"KEEP_SCREEN_ON_FLAG".equals(tag)
478 && !"KeyInputQueue".equals(tag))) {
479 monitorType = (f & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK
480 ? BatteryStats.WAKE_TYPE_PARTIAL
481 : BatteryStats.WAKE_TYPE_FULL;
482 } else {
483 monitorType = -1;
484 }
485 try {
486 b.linkToDeath(this, 0);
487 } catch (RemoteException e) {
488 binderDied();
489 }
490 }
491 public void binderDied() {
492 synchronized (mLocks) {
493 releaseWakeLockLocked(this.binder, true);
494 }
495 }
496 final int flags;
497 final IBinder binder;
498 final String tag;
499 final int uid;
500 final int monitorType;
501 boolean activated = true;
502 int minState;
503 }
504
505 private void updateWakeLockLocked() {
506 if (mStayOnConditions != 0 && mBatteryService.isPowered(mStayOnConditions)) {
507 // keep the device on if we're plugged in and mStayOnWhilePluggedIn is set.
508 mStayOnWhilePluggedInScreenDimLock.acquire();
509 mStayOnWhilePluggedInPartialLock.acquire();
510 } else {
511 mStayOnWhilePluggedInScreenDimLock.release();
512 mStayOnWhilePluggedInPartialLock.release();
513 }
514 }
515
516 private boolean isScreenLock(int flags)
517 {
518 int n = flags & LOCK_MASK;
519 return n == PowerManager.FULL_WAKE_LOCK
520 || n == PowerManager.SCREEN_BRIGHT_WAKE_LOCK
521 || n == PowerManager.SCREEN_DIM_WAKE_LOCK;
522 }
523
524 public void acquireWakeLock(int flags, IBinder lock, String tag) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800525 int uid = Binder.getCallingUid();
Michael Chane96440f2009-05-06 10:27:36 -0700526 if (uid != Process.myUid()) {
527 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
528 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800529 long ident = Binder.clearCallingIdentity();
530 try {
531 synchronized (mLocks) {
532 acquireWakeLockLocked(flags, lock, uid, tag);
533 }
534 } finally {
535 Binder.restoreCallingIdentity(ident);
536 }
537 }
538
539 public void acquireWakeLockLocked(int flags, IBinder lock, int uid, String tag) {
540 int acquireUid = -1;
541 String acquireName = null;
542 int acquireType = -1;
543
544 if (mSpew) {
545 Log.d(TAG, "acquireWakeLock flags=0x" + Integer.toHexString(flags) + " tag=" + tag);
546 }
547
548 int index = mLocks.getIndex(lock);
549 WakeLock wl;
550 boolean newlock;
551 if (index < 0) {
552 wl = new WakeLock(flags, lock, tag, uid);
553 switch (wl.flags & LOCK_MASK)
554 {
555 case PowerManager.FULL_WAKE_LOCK:
556 wl.minState = (mKeyboardVisible ? ALL_BRIGHT : SCREEN_BUTTON_BRIGHT);
557 break;
558 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
559 wl.minState = SCREEN_BRIGHT;
560 break;
561 case PowerManager.SCREEN_DIM_WAKE_LOCK:
562 wl.minState = SCREEN_DIM;
563 break;
564 case PowerManager.PARTIAL_WAKE_LOCK:
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700565 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800566 break;
567 default:
568 // just log and bail. we're in the server, so don't
569 // throw an exception.
570 Log.e(TAG, "bad wakelock type for lock '" + tag + "' "
571 + " flags=" + flags);
572 return;
573 }
574 mLocks.addLock(wl);
575 newlock = true;
576 } else {
577 wl = mLocks.get(index);
578 newlock = false;
579 }
580 if (isScreenLock(flags)) {
581 // if this causes a wakeup, we reactivate all of the locks and
582 // set it to whatever they want. otherwise, we modulate that
583 // by the current state so we never turn it more on than
584 // it already is.
585 if ((wl.flags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) {
Michael Chane96440f2009-05-06 10:27:36 -0700586 int oldWakeLockState = mWakeLockState;
587 mWakeLockState = mLocks.reactivateScreenLocksLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800588 if (mSpew) {
589 Log.d(TAG, "wakeup here mUserState=0x" + Integer.toHexString(mUserState)
Michael Chane96440f2009-05-06 10:27:36 -0700590 + " mWakeLockState=0x"
591 + Integer.toHexString(mWakeLockState)
592 + " previous wakeLockState=0x" + Integer.toHexString(oldWakeLockState));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800593 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800594 } else {
595 if (mSpew) {
596 Log.d(TAG, "here mUserState=0x" + Integer.toHexString(mUserState)
597 + " mLocks.gatherState()=0x"
598 + Integer.toHexString(mLocks.gatherState())
599 + " mWakeLockState=0x" + Integer.toHexString(mWakeLockState));
600 }
601 mWakeLockState = (mUserState | mWakeLockState) & mLocks.gatherState();
602 }
603 setPowerState(mWakeLockState | mUserState);
604 }
605 else if ((flags & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK) {
606 if (newlock) {
607 mPartialCount++;
608 if (mPartialCount == 1) {
609 if (LOG_PARTIAL_WL) EventLog.writeEvent(LOG_POWER_PARTIAL_WAKE_STATE, 1, tag);
610 }
611 }
612 Power.acquireWakeLock(Power.PARTIAL_WAKE_LOCK,PARTIAL_NAME);
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700613 } else if ((flags & LOCK_MASK) == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK) {
614 mProximityCount++;
615 if (mProximityCount == 1) {
616 enableProximityLockLocked();
617 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800618 }
619 if (newlock) {
620 acquireUid = wl.uid;
621 acquireName = wl.tag;
622 acquireType = wl.monitorType;
623 }
624
625 if (acquireType >= 0) {
626 try {
627 mBatteryStats.noteStartWakelock(acquireUid, acquireName, acquireType);
628 } catch (RemoteException e) {
629 // Ignore
630 }
631 }
632 }
633
634 public void releaseWakeLock(IBinder lock) {
Michael Chane96440f2009-05-06 10:27:36 -0700635 int uid = Binder.getCallingUid();
636 if (uid != Process.myUid()) {
637 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
638 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800639
640 synchronized (mLocks) {
641 releaseWakeLockLocked(lock, false);
642 }
643 }
644
645 private void releaseWakeLockLocked(IBinder lock, boolean death) {
646 int releaseUid;
647 String releaseName;
648 int releaseType;
649
650 WakeLock wl = mLocks.removeLock(lock);
651 if (wl == null) {
652 return;
653 }
654
655 if (mSpew) {
656 Log.d(TAG, "releaseWakeLock flags=0x"
657 + Integer.toHexString(wl.flags) + " tag=" + wl.tag);
658 }
659
660 if (isScreenLock(wl.flags)) {
661 mWakeLockState = mLocks.gatherState();
662 // goes in the middle to reduce flicker
663 if ((wl.flags & PowerManager.ON_AFTER_RELEASE) != 0) {
664 userActivity(SystemClock.uptimeMillis(), false);
665 }
666 setPowerState(mWakeLockState | mUserState);
667 }
668 else if ((wl.flags & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK) {
669 mPartialCount--;
670 if (mPartialCount == 0) {
671 if (LOG_PARTIAL_WL) EventLog.writeEvent(LOG_POWER_PARTIAL_WAKE_STATE, 0, wl.tag);
672 Power.releaseWakeLock(PARTIAL_NAME);
673 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700674 } else if ((wl.flags & LOCK_MASK) == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK) {
675 mProximityCount--;
676 if (mProximityCount == 0) {
677 disableProximityLockLocked();
678 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800679 }
680 // Unlink the lock from the binder.
681 wl.binder.unlinkToDeath(wl, 0);
682 releaseUid = wl.uid;
683 releaseName = wl.tag;
684 releaseType = wl.monitorType;
685
686 if (releaseType >= 0) {
687 long origId = Binder.clearCallingIdentity();
688 try {
689 mBatteryStats.noteStopWakelock(releaseUid, releaseName, releaseType);
690 } catch (RemoteException e) {
691 // Ignore
692 } finally {
693 Binder.restoreCallingIdentity(origId);
694 }
695 }
696 }
697
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800698 private class PokeLock implements IBinder.DeathRecipient
699 {
700 PokeLock(int p, IBinder b, String t) {
701 super();
702 this.pokey = p;
703 this.binder = b;
704 this.tag = t;
705 try {
706 b.linkToDeath(this, 0);
707 } catch (RemoteException e) {
708 binderDied();
709 }
710 }
711 public void binderDied() {
712 setPokeLock(0, this.binder, this.tag);
713 }
714 int pokey;
715 IBinder binder;
716 String tag;
717 boolean awakeOnSet;
718 }
719
720 public void setPokeLock(int pokey, IBinder token, String tag) {
721 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
722 if (token == null) {
723 Log.e(TAG, "setPokeLock got null token for tag='" + tag + "'");
724 return;
725 }
726
727 if ((pokey & POKE_LOCK_TIMEOUT_MASK) == POKE_LOCK_TIMEOUT_MASK) {
728 throw new IllegalArgumentException("setPokeLock can't have both POKE_LOCK_SHORT_TIMEOUT"
729 + " and POKE_LOCK_MEDIUM_TIMEOUT");
730 }
731
732 synchronized (mLocks) {
733 if (pokey != 0) {
734 PokeLock p = mPokeLocks.get(token);
735 int oldPokey = 0;
736 if (p != null) {
737 oldPokey = p.pokey;
738 p.pokey = pokey;
739 } else {
740 p = new PokeLock(pokey, token, tag);
741 mPokeLocks.put(token, p);
742 }
743 int oldTimeout = oldPokey & POKE_LOCK_TIMEOUT_MASK;
744 int newTimeout = pokey & POKE_LOCK_TIMEOUT_MASK;
745 if (((mPowerState & SCREEN_ON_BIT) == 0) && (oldTimeout != newTimeout)) {
746 p.awakeOnSet = true;
747 }
748 } else {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -0700749 PokeLock rLock = mPokeLocks.remove(token);
750 if (rLock != null) {
751 token.unlinkToDeath(rLock, 0);
752 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800753 }
754
755 int oldPokey = mPokey;
756 int cumulative = 0;
757 boolean oldAwakeOnSet = mPokeAwakeOnSet;
758 boolean awakeOnSet = false;
759 for (PokeLock p: mPokeLocks.values()) {
760 cumulative |= p.pokey;
761 if (p.awakeOnSet) {
762 awakeOnSet = true;
763 }
764 }
765 mPokey = cumulative;
766 mPokeAwakeOnSet = awakeOnSet;
767
768 int oldCumulativeTimeout = oldPokey & POKE_LOCK_TIMEOUT_MASK;
769 int newCumulativeTimeout = pokey & POKE_LOCK_TIMEOUT_MASK;
770
771 if (oldCumulativeTimeout != newCumulativeTimeout) {
772 setScreenOffTimeoutsLocked();
773 // reset the countdown timer, but use the existing nextState so it doesn't
774 // change anything
775 setTimeoutLocked(SystemClock.uptimeMillis(), mTimeoutTask.nextState);
776 }
777 }
778 }
779
780 private static String lockType(int type)
781 {
782 switch (type)
783 {
784 case PowerManager.FULL_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -0700785 return "FULL_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800786 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -0700787 return "SCREEN_BRIGHT_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800788 case PowerManager.SCREEN_DIM_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -0700789 return "SCREEN_DIM_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800790 case PowerManager.PARTIAL_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -0700791 return "PARTIAL_WAKE_LOCK ";
792 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
793 return "PROXIMITY_SCREEN_OFF_WAKE_LOCK";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800794 default:
David Brown251faa62009-08-02 22:04:36 -0700795 return "??? ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800796 }
797 }
798
799 private static String dumpPowerState(int state) {
800 return (((state & KEYBOARD_BRIGHT_BIT) != 0)
801 ? "KEYBOARD_BRIGHT_BIT " : "")
802 + (((state & SCREEN_BRIGHT_BIT) != 0)
803 ? "SCREEN_BRIGHT_BIT " : "")
804 + (((state & SCREEN_ON_BIT) != 0)
805 ? "SCREEN_ON_BIT " : "")
806 + (((state & BATTERY_LOW_BIT) != 0)
807 ? "BATTERY_LOW_BIT " : "");
808 }
809
810 @Override
811 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
812 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
813 != PackageManager.PERMISSION_GRANTED) {
814 pw.println("Permission Denial: can't dump PowerManager from from pid="
815 + Binder.getCallingPid()
816 + ", uid=" + Binder.getCallingUid());
817 return;
818 }
819
820 long now = SystemClock.uptimeMillis();
821
822 pw.println("Power Manager State:");
823 pw.println(" mIsPowered=" + mIsPowered
824 + " mPowerState=" + mPowerState
825 + " mScreenOffTime=" + (SystemClock.elapsedRealtime()-mScreenOffTime)
826 + " ms");
827 pw.println(" mPartialCount=" + mPartialCount);
828 pw.println(" mWakeLockState=" + dumpPowerState(mWakeLockState));
829 pw.println(" mUserState=" + dumpPowerState(mUserState));
830 pw.println(" mPowerState=" + dumpPowerState(mPowerState));
831 pw.println(" mLocks.gather=" + dumpPowerState(mLocks.gatherState()));
832 pw.println(" mNextTimeout=" + mNextTimeout + " now=" + now
833 + " " + ((mNextTimeout-now)/1000) + "s from now");
834 pw.println(" mDimScreen=" + mDimScreen
835 + " mStayOnConditions=" + mStayOnConditions);
836 pw.println(" mOffBecauseOfUser=" + mOffBecauseOfUser
837 + " mUserState=" + mUserState);
Joe Onorato128e7292009-03-24 18:41:31 -0700838 pw.println(" mBroadcastQueue={" + mBroadcastQueue[0] + ',' + mBroadcastQueue[1]
839 + ',' + mBroadcastQueue[2] + "}");
840 pw.println(" mBroadcastWhy={" + mBroadcastWhy[0] + ',' + mBroadcastWhy[1]
841 + ',' + mBroadcastWhy[2] + "}");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800842 pw.println(" mPokey=" + mPokey + " mPokeAwakeonSet=" + mPokeAwakeOnSet);
843 pw.println(" mKeyboardVisible=" + mKeyboardVisible
844 + " mUserActivityAllowed=" + mUserActivityAllowed);
845 pw.println(" mKeylightDelay=" + mKeylightDelay + " mDimDelay=" + mDimDelay
846 + " mScreenOffDelay=" + mScreenOffDelay);
847 pw.println(" mPreventScreenOn=" + mPreventScreenOn
848 + " mScreenBrightnessOverride=" + mScreenBrightnessOverride);
849 pw.println(" mTotalDelaySetting=" + mTotalDelaySetting);
850 pw.println(" mBroadcastWakeLock=" + mBroadcastWakeLock);
851 pw.println(" mStayOnWhilePluggedInScreenDimLock=" + mStayOnWhilePluggedInScreenDimLock);
852 pw.println(" mStayOnWhilePluggedInPartialLock=" + mStayOnWhilePluggedInPartialLock);
853 pw.println(" mPreventScreenOnPartialLock=" + mPreventScreenOnPartialLock);
854 mScreenBrightness.dump(pw, " mScreenBrightness: ");
855 mKeyboardBrightness.dump(pw, " mKeyboardBrightness: ");
856 mButtonBrightness.dump(pw, " mButtonBrightness: ");
857
858 int N = mLocks.size();
859 pw.println();
860 pw.println("mLocks.size=" + N + ":");
861 for (int i=0; i<N; i++) {
862 WakeLock wl = mLocks.get(i);
863 String type = lockType(wl.flags & LOCK_MASK);
864 String acquireCausesWakeup = "";
865 if ((wl.flags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) {
866 acquireCausesWakeup = "ACQUIRE_CAUSES_WAKEUP ";
867 }
868 String activated = "";
869 if (wl.activated) {
870 activated = " activated";
871 }
872 pw.println(" " + type + " '" + wl.tag + "'" + acquireCausesWakeup
873 + activated + " (minState=" + wl.minState + ")");
874 }
875
876 pw.println();
877 pw.println("mPokeLocks.size=" + mPokeLocks.size() + ":");
878 for (PokeLock p: mPokeLocks.values()) {
879 pw.println(" poke lock '" + p.tag + "':"
880 + ((p.pokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0
881 ? " POKE_LOCK_IGNORE_CHEEK_EVENTS" : "")
Joe Onoratoe68ffcb2009-03-24 19:11:13 -0700882 + ((p.pokey & POKE_LOCK_IGNORE_TOUCH_AND_CHEEK_EVENTS) != 0
883 ? " POKE_LOCK_IGNORE_TOUCH_AND_CHEEK_EVENTS" : "")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800884 + ((p.pokey & POKE_LOCK_SHORT_TIMEOUT) != 0
885 ? " POKE_LOCK_SHORT_TIMEOUT" : "")
886 + ((p.pokey & POKE_LOCK_MEDIUM_TIMEOUT) != 0
887 ? " POKE_LOCK_MEDIUM_TIMEOUT" : ""));
888 }
889
890 pw.println();
891 }
892
893 private void setTimeoutLocked(long now, int nextState)
894 {
895 if (mDoneBooting) {
896 mHandler.removeCallbacks(mTimeoutTask);
897 mTimeoutTask.nextState = nextState;
898 long when = now;
899 switch (nextState)
900 {
901 case SCREEN_BRIGHT:
902 when += mKeylightDelay;
903 break;
904 case SCREEN_DIM:
905 if (mDimDelay >= 0) {
906 when += mDimDelay;
907 break;
908 } else {
909 Log.w(TAG, "mDimDelay=" + mDimDelay + " while trying to dim");
910 }
911 case SCREEN_OFF:
912 synchronized (mLocks) {
913 when += mScreenOffDelay;
914 }
915 break;
916 }
917 if (mSpew) {
918 Log.d(TAG, "setTimeoutLocked now=" + now + " nextState=" + nextState
919 + " when=" + when);
920 }
921 mHandler.postAtTime(mTimeoutTask, when);
922 mNextTimeout = when; // for debugging
923 }
924 }
925
926 private void cancelTimerLocked()
927 {
928 mHandler.removeCallbacks(mTimeoutTask);
929 mTimeoutTask.nextState = -1;
930 }
931
932 private class TimeoutTask implements Runnable
933 {
934 int nextState; // access should be synchronized on mLocks
935 public void run()
936 {
937 synchronized (mLocks) {
938 if (mSpew) {
939 Log.d(TAG, "user activity timeout timed out nextState=" + this.nextState);
940 }
941
942 if (nextState == -1) {
943 return;
944 }
945
946 mUserState = this.nextState;
947 setPowerState(this.nextState | mWakeLockState);
948
949 long now = SystemClock.uptimeMillis();
950
951 switch (this.nextState)
952 {
953 case SCREEN_BRIGHT:
954 if (mDimDelay >= 0) {
955 setTimeoutLocked(now, SCREEN_DIM);
956 break;
957 }
958 case SCREEN_DIM:
959 setTimeoutLocked(now, SCREEN_OFF);
960 break;
961 }
962 }
963 }
964 }
965
966 private void sendNotificationLocked(boolean on, int why)
967 {
Joe Onorato64c62ba2009-03-24 20:13:57 -0700968 if (!on) {
969 mStillNeedSleepNotification = false;
970 }
971
Joe Onorato128e7292009-03-24 18:41:31 -0700972 // Add to the queue.
973 int index = 0;
974 while (mBroadcastQueue[index] != -1) {
975 index++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800976 }
Joe Onorato128e7292009-03-24 18:41:31 -0700977 mBroadcastQueue[index] = on ? 1 : 0;
978 mBroadcastWhy[index] = why;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800979
Joe Onorato128e7292009-03-24 18:41:31 -0700980 // If we added it position 2, then there is a pair that can be stripped.
981 // If we added it position 1 and we're turning the screen off, we can strip
982 // the pair and do nothing, because the screen is already off, and therefore
983 // keyguard has already been enabled.
984 // However, if we added it at position 1 and we're turning it on, then position
985 // 0 was to turn it off, and we can't strip that, because keyguard needs to come
986 // on, so have to run the queue then.
987 if (index == 2) {
988 // Also, while we're collapsing them, if it's going to be an "off," and one
989 // is off because of user, then use that, regardless of whether it's the first
990 // or second one.
991 if (!on && why == WindowManagerPolicy.OFF_BECAUSE_OF_USER) {
992 mBroadcastWhy[0] = WindowManagerPolicy.OFF_BECAUSE_OF_USER;
993 }
994 mBroadcastQueue[0] = on ? 1 : 0;
995 mBroadcastQueue[1] = -1;
996 mBroadcastQueue[2] = -1;
997 index = 0;
998 }
999 if (index == 1 && !on) {
1000 mBroadcastQueue[0] = -1;
1001 mBroadcastQueue[1] = -1;
1002 index = -1;
1003 // The wake lock was being held, but we're not actually going to do any
1004 // broadcasts, so release the wake lock.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001005 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_STOP, 1, mBroadcastWakeLock.mCount);
1006 mBroadcastWakeLock.release();
Joe Onorato128e7292009-03-24 18:41:31 -07001007 }
1008
1009 // Now send the message.
1010 if (index >= 0) {
1011 // Acquire the broadcast wake lock before changing the power
1012 // state. It will be release after the broadcast is sent.
1013 // We always increment the ref count for each notification in the queue
1014 // and always decrement when that notification is handled.
1015 mBroadcastWakeLock.acquire();
1016 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_SEND, mBroadcastWakeLock.mCount);
1017 mHandler.post(mNotificationTask);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001018 }
1019 }
1020
1021 private Runnable mNotificationTask = new Runnable()
1022 {
1023 public void run()
1024 {
Joe Onorato128e7292009-03-24 18:41:31 -07001025 while (true) {
1026 int value;
1027 int why;
1028 WindowManagerPolicy policy;
1029 synchronized (mLocks) {
1030 value = mBroadcastQueue[0];
1031 why = mBroadcastWhy[0];
1032 for (int i=0; i<2; i++) {
1033 mBroadcastQueue[i] = mBroadcastQueue[i+1];
1034 mBroadcastWhy[i] = mBroadcastWhy[i+1];
1035 }
1036 policy = getPolicyLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001037 }
Joe Onorato128e7292009-03-24 18:41:31 -07001038 if (value == 1) {
1039 mScreenOnStart = SystemClock.uptimeMillis();
1040
1041 policy.screenTurnedOn();
1042 try {
1043 ActivityManagerNative.getDefault().wakingUp();
1044 } catch (RemoteException e) {
1045 // ignore it
1046 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001047
Joe Onorato128e7292009-03-24 18:41:31 -07001048 if (mSpew) {
1049 Log.d(TAG, "mBroadcastWakeLock=" + mBroadcastWakeLock);
1050 }
1051 if (mContext != null && ActivityManagerNative.isSystemReady()) {
1052 mContext.sendOrderedBroadcast(mScreenOnIntent, null,
1053 mScreenOnBroadcastDone, mHandler, 0, null, null);
1054 } else {
1055 synchronized (mLocks) {
1056 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_STOP, 2,
1057 mBroadcastWakeLock.mCount);
1058 mBroadcastWakeLock.release();
1059 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001060 }
1061 }
Joe Onorato128e7292009-03-24 18:41:31 -07001062 else if (value == 0) {
1063 mScreenOffStart = SystemClock.uptimeMillis();
1064
1065 policy.screenTurnedOff(why);
1066 try {
1067 ActivityManagerNative.getDefault().goingToSleep();
1068 } catch (RemoteException e) {
1069 // ignore it.
1070 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001071
Joe Onorato128e7292009-03-24 18:41:31 -07001072 if (mContext != null && ActivityManagerNative.isSystemReady()) {
1073 mContext.sendOrderedBroadcast(mScreenOffIntent, null,
1074 mScreenOffBroadcastDone, mHandler, 0, null, null);
1075 } else {
1076 synchronized (mLocks) {
1077 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_STOP, 3,
1078 mBroadcastWakeLock.mCount);
1079 mBroadcastWakeLock.release();
1080 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001081 }
1082 }
Joe Onorato128e7292009-03-24 18:41:31 -07001083 else {
1084 // If we're in this case, then this handler is running for a previous
1085 // paired transaction. mBroadcastWakeLock will already have been released.
1086 break;
1087 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001088 }
1089 }
1090 };
1091
1092 long mScreenOnStart;
1093 private BroadcastReceiver mScreenOnBroadcastDone = new BroadcastReceiver() {
1094 public void onReceive(Context context, Intent intent) {
1095 synchronized (mLocks) {
1096 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_DONE, 1,
1097 SystemClock.uptimeMillis() - mScreenOnStart, mBroadcastWakeLock.mCount);
1098 mBroadcastWakeLock.release();
1099 }
1100 }
1101 };
1102
1103 long mScreenOffStart;
1104 private BroadcastReceiver mScreenOffBroadcastDone = new BroadcastReceiver() {
1105 public void onReceive(Context context, Intent intent) {
1106 synchronized (mLocks) {
1107 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_DONE, 0,
1108 SystemClock.uptimeMillis() - mScreenOffStart, mBroadcastWakeLock.mCount);
1109 mBroadcastWakeLock.release();
1110 }
1111 }
1112 };
1113
1114 void logPointerUpEvent() {
1115 if (LOG_TOUCH_DOWNS) {
1116 mTotalTouchDownTime += SystemClock.elapsedRealtime() - mLastTouchDown;
1117 mLastTouchDown = 0;
1118 }
1119 }
1120
1121 void logPointerDownEvent() {
1122 if (LOG_TOUCH_DOWNS) {
1123 // If we are not already timing a down/up sequence
1124 if (mLastTouchDown == 0) {
1125 mLastTouchDown = SystemClock.elapsedRealtime();
1126 mTouchCycles++;
1127 }
1128 }
1129 }
1130
1131 /**
1132 * Prevents the screen from turning on even if it *should* turn on due
1133 * to a subsequent full wake lock being acquired.
1134 * <p>
1135 * This is a temporary hack that allows an activity to "cover up" any
1136 * display glitches that happen during the activity's startup
1137 * sequence. (Specifically, this API was added to work around a
1138 * cosmetic bug in the "incoming call" sequence, where the lock screen
1139 * would flicker briefly before the incoming call UI became visible.)
1140 * TODO: There ought to be a more elegant way of doing this,
1141 * probably by having the PowerManager and ActivityManager
1142 * work together to let apps specify that the screen on/off
1143 * state should be synchronized with the Activity lifecycle.
1144 * <p>
1145 * Note that calling preventScreenOn(true) will NOT turn the screen
1146 * off if it's currently on. (This API only affects *future*
1147 * acquisitions of full wake locks.)
1148 * But calling preventScreenOn(false) WILL turn the screen on if
1149 * it's currently off because of a prior preventScreenOn(true) call.
1150 * <p>
1151 * Any call to preventScreenOn(true) MUST be followed promptly by a call
1152 * to preventScreenOn(false). In fact, if the preventScreenOn(false)
1153 * call doesn't occur within 5 seconds, we'll turn the screen back on
1154 * ourselves (and log a warning about it); this prevents a buggy app
1155 * from disabling the screen forever.)
1156 * <p>
1157 * TODO: this feature should really be controlled by a new type of poke
1158 * lock (rather than an IPowerManager call).
1159 */
1160 public void preventScreenOn(boolean prevent) {
1161 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1162
1163 synchronized (mLocks) {
1164 if (prevent) {
1165 // First of all, grab a partial wake lock to
1166 // make sure the CPU stays on during the entire
1167 // preventScreenOn(true) -> preventScreenOn(false) sequence.
1168 mPreventScreenOnPartialLock.acquire();
1169
1170 // Post a forceReenableScreen() call (for 5 seconds in the
1171 // future) to make sure the matching preventScreenOn(false) call
1172 // has happened by then.
1173 mHandler.removeCallbacks(mForceReenableScreenTask);
1174 mHandler.postDelayed(mForceReenableScreenTask, 5000);
1175
1176 // Finally, set the flag that prevents the screen from turning on.
1177 // (Below, in setPowerState(), we'll check mPreventScreenOn and
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001178 // we *won't* call setScreenStateLocked(true) if it's set.)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001179 mPreventScreenOn = true;
1180 } else {
1181 // (Re)enable the screen.
1182 mPreventScreenOn = false;
1183
1184 // We're "undoing" a the prior preventScreenOn(true) call, so we
1185 // no longer need the 5-second safeguard.
1186 mHandler.removeCallbacks(mForceReenableScreenTask);
1187
1188 // Forcibly turn on the screen if it's supposed to be on. (This
1189 // handles the case where the screen is currently off because of
1190 // a prior preventScreenOn(true) call.)
1191 if ((mPowerState & SCREEN_ON_BIT) != 0) {
1192 if (mSpew) {
1193 Log.d(TAG,
1194 "preventScreenOn: turning on after a prior preventScreenOn(true)!");
1195 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001196 int err = setScreenStateLocked(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001197 if (err != 0) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001198 Log.w(TAG, "preventScreenOn: error from setScreenStateLocked(): " + err);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001199 }
1200 }
1201
1202 // Release the partial wake lock that we held during the
1203 // preventScreenOn(true) -> preventScreenOn(false) sequence.
1204 mPreventScreenOnPartialLock.release();
1205 }
1206 }
1207 }
1208
1209 public void setScreenBrightnessOverride(int brightness) {
1210 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1211
1212 synchronized (mLocks) {
1213 if (mScreenBrightnessOverride != brightness) {
1214 mScreenBrightnessOverride = brightness;
1215 updateLightsLocked(mPowerState, SCREEN_ON_BIT);
1216 }
1217 }
1218 }
1219
1220 /**
1221 * Sanity-check that gets called 5 seconds after any call to
1222 * preventScreenOn(true). This ensures that the original call
1223 * is followed promptly by a call to preventScreenOn(false).
1224 */
1225 private void forceReenableScreen() {
1226 // We shouldn't get here at all if mPreventScreenOn is false, since
1227 // we should have already removed any existing
1228 // mForceReenableScreenTask messages...
1229 if (!mPreventScreenOn) {
1230 Log.w(TAG, "forceReenableScreen: mPreventScreenOn is false, nothing to do");
1231 return;
1232 }
1233
1234 // Uh oh. It's been 5 seconds since a call to
1235 // preventScreenOn(true) and we haven't re-enabled the screen yet.
1236 // This means the app that called preventScreenOn(true) is either
1237 // slow (i.e. it took more than 5 seconds to call preventScreenOn(false)),
1238 // or buggy (i.e. it forgot to call preventScreenOn(false), or
1239 // crashed before doing so.)
1240
1241 // Log a warning, and forcibly turn the screen back on.
1242 Log.w(TAG, "App called preventScreenOn(true) but didn't promptly reenable the screen! "
1243 + "Forcing the screen back on...");
1244 preventScreenOn(false);
1245 }
1246
1247 private Runnable mForceReenableScreenTask = new Runnable() {
1248 public void run() {
1249 forceReenableScreen();
1250 }
1251 };
1252
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001253 private int setScreenStateLocked(boolean on) {
1254 int err = Power.setScreenState(on);
1255 if (err == 0) {
1256 enableLightSensor(on && mAutoBrightessEnabled);
1257 }
1258 return err;
1259 }
1260
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001261 private void setPowerState(int state)
1262 {
1263 setPowerState(state, false, false);
1264 }
1265
1266 private void setPowerState(int newState, boolean noChangeLights, boolean becauseOfUser)
1267 {
1268 synchronized (mLocks) {
1269 int err;
1270
1271 if (mSpew) {
1272 Log.d(TAG, "setPowerState: mPowerState=0x" + Integer.toHexString(mPowerState)
1273 + " newState=0x" + Integer.toHexString(newState)
1274 + " noChangeLights=" + noChangeLights);
1275 }
1276
1277 if (noChangeLights) {
1278 newState = (newState & ~LIGHTS_MASK) | (mPowerState & LIGHTS_MASK);
1279 }
Mike Lockwood36fc3022009-08-25 16:49:06 -07001280 if (mProximitySensorActive) {
1281 // don't turn on the screen when the proximity sensor lock is held
1282 newState = (newState & ~SCREEN_BRIGHT);
1283 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001284
1285 if (batteryIsLow()) {
1286 newState |= BATTERY_LOW_BIT;
1287 } else {
1288 newState &= ~BATTERY_LOW_BIT;
1289 }
1290 if (newState == mPowerState) {
1291 return;
1292 }
1293
1294 if (!mDoneBooting) {
1295 newState |= ALL_BRIGHT;
1296 }
1297
1298 boolean oldScreenOn = (mPowerState & SCREEN_ON_BIT) != 0;
1299 boolean newScreenOn = (newState & SCREEN_ON_BIT) != 0;
1300
1301 if (mSpew) {
1302 Log.d(TAG, "setPowerState: mPowerState=" + mPowerState
1303 + " newState=" + newState + " noChangeLights=" + noChangeLights);
1304 Log.d(TAG, " oldKeyboardBright=" + ((mPowerState & KEYBOARD_BRIGHT_BIT) != 0)
1305 + " newKeyboardBright=" + ((newState & KEYBOARD_BRIGHT_BIT) != 0));
1306 Log.d(TAG, " oldScreenBright=" + ((mPowerState & SCREEN_BRIGHT_BIT) != 0)
1307 + " newScreenBright=" + ((newState & SCREEN_BRIGHT_BIT) != 0));
1308 Log.d(TAG, " oldButtonBright=" + ((mPowerState & BUTTON_BRIGHT_BIT) != 0)
1309 + " newButtonBright=" + ((newState & BUTTON_BRIGHT_BIT) != 0));
1310 Log.d(TAG, " oldScreenOn=" + oldScreenOn
1311 + " newScreenOn=" + newScreenOn);
1312 Log.d(TAG, " oldBatteryLow=" + ((mPowerState & BATTERY_LOW_BIT) != 0)
1313 + " newBatteryLow=" + ((newState & BATTERY_LOW_BIT) != 0));
1314 }
1315
1316 if (mPowerState != newState) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001317 updateLightsLocked(newState, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001318 mPowerState = (mPowerState & ~LIGHTS_MASK) | (newState & LIGHTS_MASK);
1319 }
1320
1321 if (oldScreenOn != newScreenOn) {
1322 if (newScreenOn) {
Joe Onorato128e7292009-03-24 18:41:31 -07001323 // When the user presses the power button, we need to always send out the
1324 // notification that it's going to sleep so the keyguard goes on. But
1325 // we can't do that until the screen fades out, so we don't show the keyguard
1326 // too early.
1327 if (mStillNeedSleepNotification) {
1328 sendNotificationLocked(false, WindowManagerPolicy.OFF_BECAUSE_OF_USER);
1329 }
1330
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001331 // Turn on the screen UNLESS there was a prior
1332 // preventScreenOn(true) request. (Note that the lifetime
1333 // of a single preventScreenOn() request is limited to 5
1334 // seconds to prevent a buggy app from disabling the
1335 // screen forever; see forceReenableScreen().)
1336 boolean reallyTurnScreenOn = true;
1337 if (mSpew) {
1338 Log.d(TAG, "- turning screen on... mPreventScreenOn = "
1339 + mPreventScreenOn);
1340 }
1341
1342 if (mPreventScreenOn) {
1343 if (mSpew) {
1344 Log.d(TAG, "- PREVENTING screen from really turning on!");
1345 }
1346 reallyTurnScreenOn = false;
1347 }
1348 if (reallyTurnScreenOn) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001349 err = setScreenStateLocked(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001350 long identity = Binder.clearCallingIdentity();
1351 try {
Dianne Hackborn617f8772009-03-31 15:04:46 -07001352 mBatteryStats.noteScreenBrightness(
1353 getPreferredBrightness());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001354 mBatteryStats.noteScreenOn();
1355 } catch (RemoteException e) {
1356 Log.w(TAG, "RemoteException calling noteScreenOn on BatteryStatsService", e);
1357 } finally {
1358 Binder.restoreCallingIdentity(identity);
1359 }
1360 } else {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001361 setScreenStateLocked(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001362 // But continue as if we really did turn the screen on...
1363 err = 0;
1364 }
1365
1366 mScreenOnStartTime = SystemClock.elapsedRealtime();
1367 mLastTouchDown = 0;
1368 mTotalTouchDownTime = 0;
1369 mTouchCycles = 0;
1370 EventLog.writeEvent(LOG_POWER_SCREEN_STATE, 1, becauseOfUser ? 1 : 0,
1371 mTotalTouchDownTime, mTouchCycles);
1372 if (err == 0) {
1373 mPowerState |= SCREEN_ON_BIT;
1374 sendNotificationLocked(true, -1);
1375 }
1376 } else {
1377 mScreenOffTime = SystemClock.elapsedRealtime();
1378 long identity = Binder.clearCallingIdentity();
1379 try {
1380 mBatteryStats.noteScreenOff();
1381 } catch (RemoteException e) {
1382 Log.w(TAG, "RemoteException calling noteScreenOff on BatteryStatsService", e);
1383 } finally {
1384 Binder.restoreCallingIdentity(identity);
1385 }
1386 mPowerState &= ~SCREEN_ON_BIT;
1387 if (!mScreenBrightness.animating) {
Joe Onorato128e7292009-03-24 18:41:31 -07001388 err = screenOffFinishedAnimatingLocked(becauseOfUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001389 } else {
1390 mOffBecauseOfUser = becauseOfUser;
1391 err = 0;
1392 mLastTouchDown = 0;
1393 }
1394 }
1395 }
1396 }
1397 }
1398
Joe Onorato128e7292009-03-24 18:41:31 -07001399 private int screenOffFinishedAnimatingLocked(boolean becauseOfUser) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001400 // I don't think we need to check the current state here because all of these
1401 // Power.setScreenState and sendNotificationLocked can both handle being
1402 // called multiple times in the same state. -joeo
1403 EventLog.writeEvent(LOG_POWER_SCREEN_STATE, 0, becauseOfUser ? 1 : 0,
1404 mTotalTouchDownTime, mTouchCycles);
1405 mLastTouchDown = 0;
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001406 int err = setScreenStateLocked(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001407 if (mScreenOnStartTime != 0) {
1408 mScreenOnTime += SystemClock.elapsedRealtime() - mScreenOnStartTime;
1409 mScreenOnStartTime = 0;
1410 }
1411 if (err == 0) {
1412 int why = becauseOfUser
1413 ? WindowManagerPolicy.OFF_BECAUSE_OF_USER
1414 : WindowManagerPolicy.OFF_BECAUSE_OF_TIMEOUT;
1415 sendNotificationLocked(false, why);
1416 }
1417 return err;
1418 }
1419
1420 private boolean batteryIsLow() {
1421 return (!mIsPowered &&
1422 mBatteryService.getBatteryLevel() <= Power.LOW_BATTERY_THRESHOLD);
1423 }
1424
The Android Open Source Project10592532009-03-18 17:39:46 -07001425 private void updateLightsLocked(int newState, int forceState) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001426 final int oldState = mPowerState;
1427 final int realDifference = (newState ^ oldState);
1428 final int difference = realDifference | forceState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001429 if (difference == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001430 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001431 }
1432
1433 int offMask = 0;
1434 int dimMask = 0;
1435 int onMask = 0;
1436
1437 int preferredBrightness = getPreferredBrightness();
1438 boolean startAnimation = false;
1439
1440 if ((difference & KEYBOARD_BRIGHT_BIT) != 0) {
1441 if (ANIMATE_KEYBOARD_LIGHTS) {
1442 if ((newState & KEYBOARD_BRIGHT_BIT) == 0) {
1443 mKeyboardBrightness.setTargetLocked(Power.BRIGHTNESS_OFF,
Joe Onorato128e7292009-03-24 18:41:31 -07001444 ANIM_STEPS, INITIAL_KEYBOARD_BRIGHTNESS,
1445 preferredBrightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001446 } else {
1447 mKeyboardBrightness.setTargetLocked(preferredBrightness,
Joe Onorato128e7292009-03-24 18:41:31 -07001448 ANIM_STEPS, INITIAL_KEYBOARD_BRIGHTNESS,
1449 Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001450 }
1451 startAnimation = true;
1452 } else {
1453 if ((newState & KEYBOARD_BRIGHT_BIT) == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001454 offMask |= KEYBOARD_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001455 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001456 onMask |= KEYBOARD_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001457 }
1458 }
1459 }
1460
1461 if ((difference & BUTTON_BRIGHT_BIT) != 0) {
1462 if (ANIMATE_BUTTON_LIGHTS) {
1463 if ((newState & BUTTON_BRIGHT_BIT) == 0) {
1464 mButtonBrightness.setTargetLocked(Power.BRIGHTNESS_OFF,
Joe Onorato128e7292009-03-24 18:41:31 -07001465 ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
1466 preferredBrightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001467 } else {
1468 mButtonBrightness.setTargetLocked(preferredBrightness,
Joe Onorato128e7292009-03-24 18:41:31 -07001469 ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
1470 Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001471 }
1472 startAnimation = true;
1473 } else {
1474 if ((newState & BUTTON_BRIGHT_BIT) == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001475 offMask |= BUTTON_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001476 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001477 onMask |= BUTTON_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001478 }
1479 }
1480 }
1481
1482 if ((difference & (SCREEN_ON_BIT | SCREEN_BRIGHT_BIT)) != 0) {
1483 if (ANIMATE_SCREEN_LIGHTS) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001484 int nominalCurrentValue = -1;
1485 // If there was an actual difference in the light state, then
1486 // figure out the "ideal" current value based on the previous
1487 // state. Otherwise, this is a change due to the brightness
1488 // override, so we want to animate from whatever the current
1489 // value is.
1490 if ((realDifference & (SCREEN_ON_BIT | SCREEN_BRIGHT_BIT)) != 0) {
1491 switch (oldState & (SCREEN_BRIGHT_BIT|SCREEN_ON_BIT)) {
1492 case SCREEN_BRIGHT_BIT | SCREEN_ON_BIT:
1493 nominalCurrentValue = preferredBrightness;
1494 break;
1495 case SCREEN_ON_BIT:
1496 nominalCurrentValue = Power.BRIGHTNESS_DIM;
1497 break;
1498 case 0:
1499 nominalCurrentValue = Power.BRIGHTNESS_OFF;
1500 break;
1501 case SCREEN_BRIGHT_BIT:
1502 default:
1503 // not possible
1504 nominalCurrentValue = (int)mScreenBrightness.curValue;
1505 break;
1506 }
Joe Onorato128e7292009-03-24 18:41:31 -07001507 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001508 int brightness = preferredBrightness;
1509 int steps = ANIM_STEPS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001510 if ((newState & SCREEN_BRIGHT_BIT) == 0) {
1511 // dim or turn off backlight, depending on if the screen is on
1512 // the scale is because the brightness ramp isn't linear and this biases
1513 // it so the later parts take longer.
1514 final float scale = 1.5f;
1515 float ratio = (((float)Power.BRIGHTNESS_DIM)/preferredBrightness);
1516 if (ratio > 1.0f) ratio = 1.0f;
1517 if ((newState & SCREEN_ON_BIT) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001518 if ((oldState & SCREEN_BRIGHT_BIT) != 0) {
1519 // was bright
1520 steps = ANIM_STEPS;
1521 } else {
1522 // was dim
1523 steps = (int)(ANIM_STEPS*ratio*scale);
1524 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001525 brightness = Power.BRIGHTNESS_OFF;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001526 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001527 if ((oldState & SCREEN_ON_BIT) != 0) {
1528 // was bright
1529 steps = (int)(ANIM_STEPS*(1.0f-ratio)*scale);
1530 } else {
1531 // was dim
1532 steps = (int)(ANIM_STEPS*ratio);
1533 }
1534 if (mStayOnConditions != 0 && mBatteryService.isPowered(mStayOnConditions)) {
1535 // If the "stay on while plugged in" option is
1536 // turned on, then the screen will often not
1537 // automatically turn off while plugged in. To
1538 // still have a sense of when it is inactive, we
1539 // will then count going dim as turning off.
1540 mScreenOffTime = SystemClock.elapsedRealtime();
1541 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001542 brightness = Power.BRIGHTNESS_DIM;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001543 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001544 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001545 long identity = Binder.clearCallingIdentity();
1546 try {
1547 mBatteryStats.noteScreenBrightness(brightness);
1548 } catch (RemoteException e) {
1549 // Nothing interesting to do.
1550 } finally {
1551 Binder.restoreCallingIdentity(identity);
1552 }
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001553 if (mScreenBrightness.setTargetLocked(brightness,
1554 steps, INITIAL_SCREEN_BRIGHTNESS, nominalCurrentValue)) {
1555 startAnimation = true;
1556 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001557 } else {
1558 if ((newState & SCREEN_BRIGHT_BIT) == 0) {
1559 // dim or turn off backlight, depending on if the screen is on
1560 if ((newState & SCREEN_ON_BIT) == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001561 offMask |= SCREEN_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001562 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001563 dimMask |= SCREEN_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001564 }
1565 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001566 onMask |= SCREEN_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001567 }
1568 }
1569 }
1570
1571 if (startAnimation) {
1572 if (mSpew) {
1573 Log.i(TAG, "Scheduling light animator!");
1574 }
1575 mHandler.removeCallbacks(mLightAnimator);
1576 mHandler.post(mLightAnimator);
1577 }
1578
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001579 if (offMask != 0) {
1580 //Log.i(TAG, "Setting brightess off: " + offMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001581 setLightBrightness(offMask, Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001582 }
1583 if (dimMask != 0) {
1584 int brightness = Power.BRIGHTNESS_DIM;
1585 if ((newState & BATTERY_LOW_BIT) != 0 &&
1586 brightness > Power.BRIGHTNESS_LOW_BATTERY) {
1587 brightness = Power.BRIGHTNESS_LOW_BATTERY;
1588 }
1589 //Log.i(TAG, "Setting brightess dim " + brightness + ": " + offMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001590 setLightBrightness(dimMask, brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001591 }
1592 if (onMask != 0) {
1593 int brightness = getPreferredBrightness();
1594 if ((newState & BATTERY_LOW_BIT) != 0 &&
1595 brightness > Power.BRIGHTNESS_LOW_BATTERY) {
1596 brightness = Power.BRIGHTNESS_LOW_BATTERY;
1597 }
1598 //Log.i(TAG, "Setting brightess on " + brightness + ": " + onMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001599 setLightBrightness(onMask, brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001600 }
The Android Open Source Project10592532009-03-18 17:39:46 -07001601 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001602
The Android Open Source Project10592532009-03-18 17:39:46 -07001603 private void setLightBrightness(int mask, int value) {
1604 if ((mask & SCREEN_BRIGHT_BIT) != 0) {
1605 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_BACKLIGHT, value);
1606 }
1607 if ((mask & BUTTON_BRIGHT_BIT) != 0) {
1608 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_BUTTONS, value);
1609 }
1610 if ((mask & KEYBOARD_BRIGHT_BIT) != 0) {
1611 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_KEYBOARD, value);
1612 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001613 }
1614
1615 class BrightnessState {
1616 final int mask;
1617
1618 boolean initialized;
1619 int targetValue;
1620 float curValue;
1621 float delta;
1622 boolean animating;
1623
1624 BrightnessState(int m) {
1625 mask = m;
1626 }
1627
1628 public void dump(PrintWriter pw, String prefix) {
1629 pw.println(prefix + "animating=" + animating
1630 + " targetValue=" + targetValue
1631 + " curValue=" + curValue
1632 + " delta=" + delta);
1633 }
1634
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001635 boolean setTargetLocked(int target, int stepsToTarget, int initialValue,
Joe Onorato128e7292009-03-24 18:41:31 -07001636 int nominalCurrentValue) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001637 if (!initialized) {
1638 initialized = true;
1639 curValue = (float)initialValue;
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001640 } else if (targetValue == target) {
1641 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001642 }
1643 targetValue = target;
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001644 delta = (targetValue -
1645 (nominalCurrentValue >= 0 ? nominalCurrentValue : curValue))
1646 / stepsToTarget;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001647 if (mSpew) {
Joe Onorato128e7292009-03-24 18:41:31 -07001648 String noticeMe = nominalCurrentValue == curValue ? "" : " ******************";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001649 Log.i(TAG, "Setting target " + mask + ": cur=" + curValue
Joe Onorato128e7292009-03-24 18:41:31 -07001650 + " target=" + targetValue + " delta=" + delta
1651 + " nominalCurrentValue=" + nominalCurrentValue
1652 + noticeMe);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001653 }
1654 animating = true;
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001655 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001656 }
1657
1658 boolean stepLocked() {
1659 if (!animating) return false;
1660 if (false && mSpew) {
1661 Log.i(TAG, "Step target " + mask + ": cur=" + curValue
1662 + " target=" + targetValue + " delta=" + delta);
1663 }
1664 curValue += delta;
1665 int curIntValue = (int)curValue;
1666 boolean more = true;
1667 if (delta == 0) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001668 curValue = curIntValue = targetValue;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001669 more = false;
1670 } else if (delta > 0) {
1671 if (curIntValue >= targetValue) {
1672 curValue = curIntValue = targetValue;
1673 more = false;
1674 }
1675 } else {
1676 if (curIntValue <= targetValue) {
1677 curValue = curIntValue = targetValue;
1678 more = false;
1679 }
1680 }
1681 //Log.i(TAG, "Animating brightess " + curIntValue + ": " + mask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001682 setLightBrightness(mask, curIntValue);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001683 animating = more;
1684 if (!more) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001685 if (mask == SCREEN_BRIGHT_BIT && curIntValue == Power.BRIGHTNESS_OFF) {
Joe Onorato128e7292009-03-24 18:41:31 -07001686 screenOffFinishedAnimatingLocked(mOffBecauseOfUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001687 }
1688 }
1689 return more;
1690 }
1691 }
1692
1693 private class LightAnimator implements Runnable {
1694 public void run() {
1695 synchronized (mLocks) {
1696 long now = SystemClock.uptimeMillis();
1697 boolean more = mScreenBrightness.stepLocked();
1698 if (mKeyboardBrightness.stepLocked()) {
1699 more = true;
1700 }
1701 if (mButtonBrightness.stepLocked()) {
1702 more = true;
1703 }
1704 if (more) {
1705 mHandler.postAtTime(mLightAnimator, now+(1000/60));
1706 }
1707 }
1708 }
1709 }
1710
1711 private int getPreferredBrightness() {
1712 try {
1713 if (mScreenBrightnessOverride >= 0) {
1714 return mScreenBrightnessOverride;
1715 }
1716 final int brightness = Settings.System.getInt(mContext.getContentResolver(),
1717 SCREEN_BRIGHTNESS);
1718 // Don't let applications turn the screen all the way off
1719 return Math.max(brightness, Power.BRIGHTNESS_DIM);
1720 } catch (SettingNotFoundException snfe) {
1721 return Power.BRIGHTNESS_ON;
1722 }
1723 }
1724
1725 boolean screenIsOn() {
1726 synchronized (mLocks) {
1727 return (mPowerState & SCREEN_ON_BIT) != 0;
1728 }
1729 }
1730
1731 boolean screenIsBright() {
1732 synchronized (mLocks) {
1733 return (mPowerState & SCREEN_BRIGHT) == SCREEN_BRIGHT;
1734 }
1735 }
1736
Mike Lockwood200b30b2009-09-20 00:23:59 -04001737 private void forceUserActivityLocked() {
1738 boolean savedActivityAllowed = mUserActivityAllowed;
1739 mUserActivityAllowed = true;
1740 userActivity(SystemClock.uptimeMillis(), false);
1741 mUserActivityAllowed = savedActivityAllowed;
1742 }
1743
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001744 public void userActivityWithForce(long time, boolean noChangeLights, boolean force) {
1745 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1746 userActivity(time, noChangeLights, OTHER_EVENT, force);
1747 }
1748
1749 public void userActivity(long time, boolean noChangeLights) {
1750 userActivity(time, noChangeLights, OTHER_EVENT, false);
1751 }
1752
1753 public void userActivity(long time, boolean noChangeLights, int eventType) {
1754 userActivity(time, noChangeLights, eventType, false);
1755 }
1756
1757 public void userActivity(long time, boolean noChangeLights, int eventType, boolean force) {
1758 //mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1759
1760 if (((mPokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0)
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07001761 && (eventType == CHEEK_EVENT || eventType == TOUCH_EVENT)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001762 if (false) {
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07001763 Log.d(TAG, "dropping cheek or short event mPokey=0x" + Integer.toHexString(mPokey));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001764 }
1765 return;
1766 }
1767
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07001768 if (((mPokey & POKE_LOCK_IGNORE_TOUCH_AND_CHEEK_EVENTS) != 0)
1769 && (eventType == TOUCH_EVENT || eventType == TOUCH_UP_EVENT
1770 || eventType == LONG_TOUCH_EVENT || eventType == CHEEK_EVENT)) {
1771 if (false) {
1772 Log.d(TAG, "dropping touch mPokey=0x" + Integer.toHexString(mPokey));
1773 }
1774 return;
1775 }
1776
1777
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001778 if (false) {
1779 if (((mPokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0)) {
1780 Log.d(TAG, "userActivity !!!");//, new RuntimeException());
1781 } else {
1782 Log.d(TAG, "mPokey=0x" + Integer.toHexString(mPokey));
1783 }
1784 }
1785
1786 synchronized (mLocks) {
1787 if (mSpew) {
1788 Log.d(TAG, "userActivity mLastEventTime=" + mLastEventTime + " time=" + time
1789 + " mUserActivityAllowed=" + mUserActivityAllowed
1790 + " mUserState=0x" + Integer.toHexString(mUserState)
Mike Lockwood36fc3022009-08-25 16:49:06 -07001791 + " mWakeLockState=0x" + Integer.toHexString(mWakeLockState)
1792 + " mProximitySensorActive=" + mProximitySensorActive
1793 + " force=" + force);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001794 }
1795 if (mLastEventTime <= time || force) {
1796 mLastEventTime = time;
Mike Lockwood36fc3022009-08-25 16:49:06 -07001797 if ((mUserActivityAllowed && !mProximitySensorActive) || force) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001798 // Only turn on button backlights if a button was pressed.
1799 if (eventType == BUTTON_EVENT) {
1800 mUserState = (mKeyboardVisible ? ALL_BRIGHT : SCREEN_BUTTON_BRIGHT);
1801 } else {
1802 // don't clear button/keyboard backlights when the screen is touched.
1803 mUserState |= SCREEN_BRIGHT;
1804 }
1805
Dianne Hackborn617f8772009-03-31 15:04:46 -07001806 int uid = Binder.getCallingUid();
1807 long ident = Binder.clearCallingIdentity();
1808 try {
1809 mBatteryStats.noteUserActivity(uid, eventType);
1810 } catch (RemoteException e) {
1811 // Ignore
1812 } finally {
1813 Binder.restoreCallingIdentity(ident);
1814 }
1815
Michael Chane96440f2009-05-06 10:27:36 -07001816 mWakeLockState = mLocks.reactivateScreenLocksLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001817 setPowerState(mUserState | mWakeLockState, noChangeLights, true);
1818 setTimeoutLocked(time, SCREEN_BRIGHT);
1819 }
1820 }
1821 }
1822 }
1823
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001824 private void lightSensorChangedLocked(float value) {
1825 if (mDebugLightSensor) {
1826 Log.d(TAG, "lightSensorChangedLocked " + value);
1827 }
1828 mLightSensorValue = value;
1829 // more to do here
1830 }
1831
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001832 /**
1833 * The user requested that we go to sleep (probably with the power button).
1834 * This overrides all wake locks that are held.
1835 */
1836 public void goToSleep(long time)
1837 {
1838 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1839 synchronized (mLocks) {
1840 goToSleepLocked(time);
1841 }
1842 }
1843
1844 /**
1845 * Returns the time the screen has been on since boot, in millis.
1846 * @return screen on time
1847 */
1848 public long getScreenOnTime() {
1849 synchronized (mLocks) {
1850 if (mScreenOnStartTime == 0) {
1851 return mScreenOnTime;
1852 } else {
1853 return SystemClock.elapsedRealtime() - mScreenOnStartTime + mScreenOnTime;
1854 }
1855 }
1856 }
1857
1858 private void goToSleepLocked(long time) {
1859
1860 if (mLastEventTime <= time) {
1861 mLastEventTime = time;
1862 // cancel all of the wake locks
1863 mWakeLockState = SCREEN_OFF;
1864 int N = mLocks.size();
1865 int numCleared = 0;
1866 for (int i=0; i<N; i++) {
1867 WakeLock wl = mLocks.get(i);
1868 if (isScreenLock(wl.flags)) {
1869 mLocks.get(i).activated = false;
1870 numCleared++;
1871 }
1872 }
1873 EventLog.writeEvent(LOG_POWER_SLEEP_REQUESTED, numCleared);
Joe Onorato128e7292009-03-24 18:41:31 -07001874 mStillNeedSleepNotification = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001875 mUserState = SCREEN_OFF;
1876 setPowerState(SCREEN_OFF, false, true);
1877 cancelTimerLocked();
1878 }
1879 }
1880
1881 public long timeSinceScreenOn() {
1882 synchronized (mLocks) {
1883 if ((mPowerState & SCREEN_ON_BIT) != 0) {
1884 return 0;
1885 }
1886 return SystemClock.elapsedRealtime() - mScreenOffTime;
1887 }
1888 }
1889
1890 public void setKeyboardVisibility(boolean visible) {
Mike Lockwooda625b382009-09-12 17:36:03 -07001891 synchronized (mLocks) {
1892 if (mSpew) {
1893 Log.d(TAG, "setKeyboardVisibility: " + visible);
1894 }
1895 mKeyboardVisible = visible;
Dianne Hackbornfe2bddf2009-09-20 15:21:10 -07001896 // don't signal user activity if the screen is off; other code
1897 // will take care of turning on due to a true change to the lid
1898 // switch and synchronized with the lock screen.
1899 if ((mPowerState & SCREEN_ON_BIT) != 0) {
Mike Lockwooda625b382009-09-12 17:36:03 -07001900 userActivity(SystemClock.uptimeMillis(), false, BUTTON_EVENT, true);
1901 }
1902 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001903 }
1904
1905 /**
1906 * When the keyguard is up, it manages the power state, and userActivity doesn't do anything.
1907 */
1908 public void enableUserActivity(boolean enabled) {
1909 synchronized (mLocks) {
1910 mUserActivityAllowed = enabled;
1911 mLastEventTime = SystemClock.uptimeMillis(); // we might need to pass this in
1912 }
1913 }
1914
Mike Lockwooddc3494e2009-10-14 21:17:09 -07001915 private void setScreenBrightnessMode(int mode) {
1916 mAutoBrightessEnabled = (mode == SCREEN_BRIGHTNESS_MODE_AUTOMATIC);
1917
1918 if (mHasHardwareAutoBrightness) {
1919 // When setting auto-brightness, must reset the brightness afterwards
1920 mHardware.setAutoBrightness_UNCHECKED(mAutoBrightessEnabled);
1921 setBacklightBrightness((int)mScreenBrightness.curValue);
1922 } else {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001923 enableLightSensor(screenIsOn() && mAutoBrightessEnabled);
Mike Lockwooddc3494e2009-10-14 21:17:09 -07001924 }
1925 }
1926
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001927 /** Sets the screen off timeouts:
1928 * mKeylightDelay
1929 * mDimDelay
1930 * mScreenOffDelay
1931 * */
1932 private void setScreenOffTimeoutsLocked() {
1933 if ((mPokey & POKE_LOCK_SHORT_TIMEOUT) != 0) {
1934 mKeylightDelay = mShortKeylightDelay; // Configurable via Gservices
1935 mDimDelay = -1;
1936 mScreenOffDelay = 0;
1937 } else if ((mPokey & POKE_LOCK_MEDIUM_TIMEOUT) != 0) {
1938 mKeylightDelay = MEDIUM_KEYLIGHT_DELAY;
1939 mDimDelay = -1;
1940 mScreenOffDelay = 0;
1941 } else {
1942 int totalDelay = mTotalDelaySetting;
1943 mKeylightDelay = LONG_KEYLIGHT_DELAY;
1944 if (totalDelay < 0) {
1945 mScreenOffDelay = Integer.MAX_VALUE;
1946 } else if (mKeylightDelay < totalDelay) {
1947 // subtract the time that the keylight delay. This will give us the
1948 // remainder of the time that we need to sleep to get the accurate
1949 // screen off timeout.
1950 mScreenOffDelay = totalDelay - mKeylightDelay;
1951 } else {
1952 mScreenOffDelay = 0;
1953 }
1954 if (mDimScreen && totalDelay >= (LONG_KEYLIGHT_DELAY + LONG_DIM_TIME)) {
1955 mDimDelay = mScreenOffDelay - LONG_DIM_TIME;
1956 mScreenOffDelay = LONG_DIM_TIME;
1957 } else {
1958 mDimDelay = -1;
1959 }
1960 }
1961 if (mSpew) {
1962 Log.d(TAG, "setScreenOffTimeouts mKeylightDelay=" + mKeylightDelay
1963 + " mDimDelay=" + mDimDelay + " mScreenOffDelay=" + mScreenOffDelay
1964 + " mDimScreen=" + mDimScreen);
1965 }
1966 }
1967
1968 /**
1969 * Refreshes cached Gservices settings. Called once on startup, and
1970 * on subsequent Settings.Gservices.CHANGED_ACTION broadcasts (see
1971 * GservicesChangedReceiver).
1972 */
1973 private void updateGservicesValues() {
1974 mShortKeylightDelay = Settings.Gservices.getInt(
1975 mContext.getContentResolver(),
1976 Settings.Gservices.SHORT_KEYLIGHT_DELAY_MS,
1977 SHORT_KEYLIGHT_DELAY_DEFAULT);
1978 // Log.i(TAG, "updateGservicesValues(): mShortKeylightDelay now " + mShortKeylightDelay);
1979 }
1980
1981 /**
1982 * Receiver for the Gservices.CHANGED_ACTION broadcast intent,
1983 * which tells us we need to refresh our cached Gservices settings.
1984 */
1985 private class GservicesChangedReceiver extends BroadcastReceiver {
1986 @Override
1987 public void onReceive(Context context, Intent intent) {
1988 // Log.i(TAG, "GservicesChangedReceiver.onReceive(): " + intent);
1989 updateGservicesValues();
1990 }
1991 }
1992
1993 private class LockList extends ArrayList<WakeLock>
1994 {
1995 void addLock(WakeLock wl)
1996 {
1997 int index = getIndex(wl.binder);
1998 if (index < 0) {
1999 this.add(wl);
2000 }
2001 }
2002
2003 WakeLock removeLock(IBinder binder)
2004 {
2005 int index = getIndex(binder);
2006 if (index >= 0) {
2007 return this.remove(index);
2008 } else {
2009 return null;
2010 }
2011 }
2012
2013 int getIndex(IBinder binder)
2014 {
2015 int N = this.size();
2016 for (int i=0; i<N; i++) {
2017 if (this.get(i).binder == binder) {
2018 return i;
2019 }
2020 }
2021 return -1;
2022 }
2023
2024 int gatherState()
2025 {
2026 int result = 0;
2027 int N = this.size();
2028 for (int i=0; i<N; i++) {
2029 WakeLock wl = this.get(i);
2030 if (wl.activated) {
2031 if (isScreenLock(wl.flags)) {
2032 result |= wl.minState;
2033 }
2034 }
2035 }
2036 return result;
2037 }
Michael Chane96440f2009-05-06 10:27:36 -07002038
2039 int reactivateScreenLocksLocked()
2040 {
2041 int result = 0;
2042 int N = this.size();
2043 for (int i=0; i<N; i++) {
2044 WakeLock wl = this.get(i);
2045 if (isScreenLock(wl.flags)) {
2046 wl.activated = true;
2047 result |= wl.minState;
2048 }
2049 }
2050 return result;
2051 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002052 }
2053
2054 void setPolicy(WindowManagerPolicy p) {
2055 synchronized (mLocks) {
2056 mPolicy = p;
2057 mLocks.notifyAll();
2058 }
2059 }
2060
2061 WindowManagerPolicy getPolicyLocked() {
2062 while (mPolicy == null || !mDoneBooting) {
2063 try {
2064 mLocks.wait();
2065 } catch (InterruptedException e) {
2066 // Ignore
2067 }
2068 }
2069 return mPolicy;
2070 }
2071
2072 void systemReady() {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002073 mSensorManager = new SensorManager(mHandlerThread.getLooper());
2074 mProximitySensor = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
2075 // don't bother with the light sensor if auto brightness is handled in hardware
2076 if (!mHasHardwareAutoBrightness) {
2077 mLightSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
2078 enableLightSensor(mAutoBrightessEnabled);
2079 }
2080
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002081 synchronized (mLocks) {
2082 Log.d(TAG, "system ready!");
2083 mDoneBooting = true;
Dianne Hackborn617f8772009-03-31 15:04:46 -07002084 long identity = Binder.clearCallingIdentity();
2085 try {
2086 mBatteryStats.noteScreenBrightness(getPreferredBrightness());
2087 mBatteryStats.noteScreenOn();
2088 } catch (RemoteException e) {
2089 // Nothing interesting to do.
2090 } finally {
2091 Binder.restoreCallingIdentity(identity);
2092 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002093 userActivity(SystemClock.uptimeMillis(), false, BUTTON_EVENT, true);
2094 updateWakeLockLocked();
2095 mLocks.notifyAll();
2096 }
2097 }
2098
2099 public void monitor() {
2100 synchronized (mLocks) { }
2101 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002102
2103 public int getSupportedWakeLockFlags() {
2104 int result = PowerManager.PARTIAL_WAKE_LOCK
2105 | PowerManager.FULL_WAKE_LOCK
2106 | PowerManager.SCREEN_DIM_WAKE_LOCK;
2107
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002108 if (mProximitySensor != null) {
2109 result |= PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK;
2110 }
2111
2112 return result;
2113 }
2114
Mike Lockwood237a2992009-09-15 14:42:16 -04002115 public void setBacklightBrightness(int brightness) {
2116 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
2117 // Don't let applications turn the screen all the way off
2118 brightness = Math.max(brightness, Power.BRIGHTNESS_DIM);
2119 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_BACKLIGHT, brightness);
2120 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_KEYBOARD, brightness);
2121 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_BUTTONS, brightness);
2122 long identity = Binder.clearCallingIdentity();
2123 try {
2124 mBatteryStats.noteScreenBrightness(brightness);
2125 } catch (RemoteException e) {
2126 Log.w(TAG, "RemoteException calling noteScreenBrightness on BatteryStatsService", e);
2127 } finally {
2128 Binder.restoreCallingIdentity(identity);
2129 }
2130
2131 // update our animation state
2132 if (ANIMATE_SCREEN_LIGHTS) {
2133 mScreenBrightness.curValue = brightness;
2134 mScreenBrightness.animating = false;
2135 }
2136 if (ANIMATE_KEYBOARD_LIGHTS) {
2137 mKeyboardBrightness.curValue = brightness;
2138 mKeyboardBrightness.animating = false;
2139 }
2140 if (ANIMATE_BUTTON_LIGHTS) {
2141 mButtonBrightness.curValue = brightness;
2142 mButtonBrightness.animating = false;
2143 }
2144 }
2145
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002146 private void enableProximityLockLocked() {
Mike Lockwood36fc3022009-08-25 16:49:06 -07002147 if (mSpew) {
2148 Log.d(TAG, "enableProximityLockLocked");
2149 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002150 mSensorManager.registerListener(mProximityListener, mProximitySensor,
2151 SensorManager.SENSOR_DELAY_NORMAL);
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002152 }
2153
2154 private void disableProximityLockLocked() {
Mike Lockwood36fc3022009-08-25 16:49:06 -07002155 if (mSpew) {
2156 Log.d(TAG, "disableProximityLockLocked");
2157 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002158 mSensorManager.unregisterListener(mProximityListener);
Mike Lockwood200b30b2009-09-20 00:23:59 -04002159 synchronized (mLocks) {
2160 if (mProximitySensorActive) {
2161 mProximitySensorActive = false;
2162 forceUserActivityLocked();
2163 }
2164 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002165 }
2166
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002167 private void enableLightSensor(boolean enable) {
2168 if (mDebugLightSensor) {
2169 Log.d(TAG, "enableLightSensor " + enable);
2170 }
2171 if (mSensorManager != null && mLightSensorEnabled != enable) {
2172 mLightSensorEnabled = enable;
2173 if (enable) {
2174 mSensorManager.registerListener(mLightListener, mLightSensor,
2175 SensorManager.SENSOR_DELAY_NORMAL);
Mike Lockwood36fc3022009-08-25 16:49:06 -07002176 } else {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002177 mSensorManager.unregisterListener(mLightListener);
Mike Lockwood06952d92009-08-13 16:05:38 -04002178 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002179 }
2180 }
2181
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002182 SensorEventListener mProximityListener = new SensorEventListener() {
2183 public void onSensorChanged(SensorEvent event) {
2184 long milliseconds = event.timestamp / 1000000;
2185 synchronized (mLocks) {
2186 float distance = event.values[0];
2187 // compare against getMaximumRange to support sensors that only return 0 or 1
2188 if (distance >= 0.0 && distance < PROXIMITY_THRESHOLD &&
2189 distance < mProximitySensor.getMaximumRange()) {
2190 if (mSpew) {
2191 Log.d(TAG, "onSensorChanged: proximity active, distance: " + distance);
2192 }
2193 goToSleepLocked(milliseconds);
2194 mProximitySensorActive = true;
2195 } else {
2196 // proximity sensor negative events trigger as user activity.
2197 // temporarily set mUserActivityAllowed to true so this will work
2198 // even when the keyguard is on.
2199 if (mSpew) {
2200 Log.d(TAG, "onSensorChanged: proximity inactive, distance: " + distance);
2201 }
2202 mProximitySensorActive = false;
2203 forceUserActivityLocked();
2204 }
2205 }
2206 }
2207
2208 public void onAccuracyChanged(Sensor sensor, int accuracy) {
2209 // ignore
2210 }
2211 };
2212
2213 SensorEventListener mLightListener = new SensorEventListener() {
2214 public void onSensorChanged(SensorEvent event) {
2215 synchronized (mLocks) {
2216 int value = (int)event.values[0];
2217 if (mDebugLightSensor) {
2218 Log.d(TAG, "onSensorChanged: light value: " + value);
2219 }
2220 lightSensorChangedLocked(value);
2221 }
2222 }
2223
2224 public void onAccuracyChanged(Sensor sensor, int accuracy) {
2225 // ignore
2226 }
2227 };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002228}