blob: aad576f083e85d71c676a80dfc907b49d9dd4f14 [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;
Mike Lockwoodd7786b42009-10-15 17:09:16 -070031import android.content.res.Resources;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080032import android.database.Cursor;
Mike Lockwoodbc706a02009-07-27 13:50:57 -070033import android.hardware.Sensor;
34import android.hardware.SensorEvent;
35import android.hardware.SensorEventListener;
36import android.hardware.SensorManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080037import android.os.BatteryStats;
38import android.os.Binder;
39import android.os.Handler;
40import android.os.HandlerThread;
41import android.os.IBinder;
42import android.os.IPowerManager;
43import android.os.LocalPowerManager;
44import android.os.Power;
45import android.os.PowerManager;
46import android.os.Process;
47import android.os.RemoteException;
48import android.os.SystemClock;
49import android.provider.Settings.SettingNotFoundException;
50import android.provider.Settings;
51import android.util.EventLog;
52import android.util.Log;
53import android.view.WindowManagerPolicy;
54import static android.provider.Settings.System.DIM_SCREEN;
55import static android.provider.Settings.System.SCREEN_BRIGHTNESS;
Dan Murphy951764b2009-08-27 14:59:03 -050056import static android.provider.Settings.System.SCREEN_BRIGHTNESS_MODE;
Mike Lockwooddc3494e2009-10-14 21:17:09 -070057import static android.provider.Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080058import static android.provider.Settings.System.SCREEN_OFF_TIMEOUT;
59import static android.provider.Settings.System.STAY_ON_WHILE_PLUGGED_IN;
60
61import java.io.FileDescriptor;
62import java.io.PrintWriter;
63import java.util.ArrayList;
64import java.util.HashMap;
65import java.util.Observable;
66import java.util.Observer;
67
Mike Lockwoodbc706a02009-07-27 13:50:57 -070068class PowerManagerService extends IPowerManager.Stub
Mike Lockwood8738e0c2009-10-04 08:44:47 -040069 implements LocalPowerManager, Watchdog.Monitor {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080070
71 private static final String TAG = "PowerManagerService";
72 static final String PARTIAL_NAME = "PowerManagerService";
73
74 private static final boolean LOG_PARTIAL_WL = false;
75
76 // Indicates whether touch-down cycles should be logged as part of the
77 // LOG_POWER_SCREEN_STATE log events
78 private static final boolean LOG_TOUCH_DOWNS = true;
79
80 private static final int LOCK_MASK = PowerManager.PARTIAL_WAKE_LOCK
81 | PowerManager.SCREEN_DIM_WAKE_LOCK
82 | PowerManager.SCREEN_BRIGHT_WAKE_LOCK
Mike Lockwoodbc706a02009-07-27 13:50:57 -070083 | PowerManager.FULL_WAKE_LOCK
84 | PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080085
86 // time since last state: time since last event:
87 // The short keylight delay comes from Gservices; this is the default.
88 private static final int SHORT_KEYLIGHT_DELAY_DEFAULT = 6000; // t+6 sec
89 private static final int MEDIUM_KEYLIGHT_DELAY = 15000; // t+15 sec
90 private static final int LONG_KEYLIGHT_DELAY = 6000; // t+6 sec
91 private static final int LONG_DIM_TIME = 7000; // t+N-5 sec
92
Mike Lockwoodd7786b42009-10-15 17:09:16 -070093 // How long to wait to debounce light sensor changes.
94 private static final int LIGHT_SENSOR_DELAY = 1000;
95
Mike Lockwoodd20ea362009-09-15 00:13:38 -040096 // trigger proximity if distance is less than 5 cm
97 private static final float PROXIMITY_THRESHOLD = 5.0f;
98
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080099 // Cached Gservices settings; see updateGservicesValues()
100 private int mShortKeylightDelay = SHORT_KEYLIGHT_DELAY_DEFAULT;
101
102 // flags for setPowerState
103 private static final int SCREEN_ON_BIT = 0x00000001;
104 private static final int SCREEN_BRIGHT_BIT = 0x00000002;
105 private static final int BUTTON_BRIGHT_BIT = 0x00000004;
106 private static final int KEYBOARD_BRIGHT_BIT = 0x00000008;
107 private static final int BATTERY_LOW_BIT = 0x00000010;
108
109 // values for setPowerState
110
111 // SCREEN_OFF == everything off
112 private static final int SCREEN_OFF = 0x00000000;
113
114 // SCREEN_DIM == screen on, screen backlight dim
115 private static final int SCREEN_DIM = SCREEN_ON_BIT;
116
117 // SCREEN_BRIGHT == screen on, screen backlight bright
118 private static final int SCREEN_BRIGHT = SCREEN_ON_BIT | SCREEN_BRIGHT_BIT;
119
120 // SCREEN_BUTTON_BRIGHT == screen on, screen and button backlights bright
121 private static final int SCREEN_BUTTON_BRIGHT = SCREEN_BRIGHT | BUTTON_BRIGHT_BIT;
122
123 // SCREEN_BUTTON_BRIGHT == screen on, screen, button and keyboard backlights bright
124 private static final int ALL_BRIGHT = SCREEN_BUTTON_BRIGHT | KEYBOARD_BRIGHT_BIT;
125
126 // used for noChangeLights in setPowerState()
127 private static final int LIGHTS_MASK = SCREEN_BRIGHT_BIT | BUTTON_BRIGHT_BIT | KEYBOARD_BRIGHT_BIT;
128
129 static final boolean ANIMATE_SCREEN_LIGHTS = true;
130 static final boolean ANIMATE_BUTTON_LIGHTS = false;
131 static final boolean ANIMATE_KEYBOARD_LIGHTS = false;
132
133 static final int ANIM_STEPS = 60/4;
134
135 // These magic numbers are the initial state of the LEDs at boot. Ideally
136 // we should read them from the driver, but our current hardware returns 0
137 // for the initial value. Oops!
138 static final int INITIAL_SCREEN_BRIGHTNESS = 255;
139 static final int INITIAL_BUTTON_BRIGHTNESS = Power.BRIGHTNESS_OFF;
140 static final int INITIAL_KEYBOARD_BRIGHTNESS = Power.BRIGHTNESS_OFF;
141
142 static final int LOG_POWER_SLEEP_REQUESTED = 2724;
143 static final int LOG_POWER_SCREEN_BROADCAST_SEND = 2725;
144 static final int LOG_POWER_SCREEN_BROADCAST_DONE = 2726;
145 static final int LOG_POWER_SCREEN_BROADCAST_STOP = 2727;
146 static final int LOG_POWER_SCREEN_STATE = 2728;
147 static final int LOG_POWER_PARTIAL_WAKE_STATE = 2729;
148
149 private final int MY_UID;
150
151 private boolean mDoneBooting = false;
152 private int mStayOnConditions = 0;
Joe Onorato128e7292009-03-24 18:41:31 -0700153 private int[] mBroadcastQueue = new int[] { -1, -1, -1 };
154 private int[] mBroadcastWhy = new int[3];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800155 private int mPartialCount = 0;
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700156 private int mProximityCount = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800157 private int mPowerState;
158 private boolean mOffBecauseOfUser;
Mike Lockwoodf003c0c2009-10-21 16:03:18 -0400159 private boolean mAnimatingScreenOff;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800160 private int mUserState;
161 private boolean mKeyboardVisible = false;
162 private boolean mUserActivityAllowed = true;
Mike Lockwood36fc3022009-08-25 16:49:06 -0700163 private boolean mProximitySensorActive = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800164 private int mTotalDelaySetting;
165 private int mKeylightDelay;
166 private int mDimDelay;
167 private int mScreenOffDelay;
168 private int mWakeLockState;
169 private long mLastEventTime = 0;
170 private long mScreenOffTime;
171 private volatile WindowManagerPolicy mPolicy;
172 private final LockList mLocks = new LockList();
173 private Intent mScreenOffIntent;
174 private Intent mScreenOnIntent;
The Android Open Source Project10592532009-03-18 17:39:46 -0700175 private HardwareService mHardware;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800176 private Context mContext;
177 private UnsynchronizedWakeLock mBroadcastWakeLock;
178 private UnsynchronizedWakeLock mStayOnWhilePluggedInScreenDimLock;
179 private UnsynchronizedWakeLock mStayOnWhilePluggedInPartialLock;
180 private UnsynchronizedWakeLock mPreventScreenOnPartialLock;
181 private HandlerThread mHandlerThread;
182 private Handler mHandler;
183 private TimeoutTask mTimeoutTask = new TimeoutTask();
184 private LightAnimator mLightAnimator = new LightAnimator();
185 private final BrightnessState mScreenBrightness
The Android Open Source Project10592532009-03-18 17:39:46 -0700186 = new BrightnessState(SCREEN_BRIGHT_BIT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800187 private final BrightnessState mKeyboardBrightness
The Android Open Source Project10592532009-03-18 17:39:46 -0700188 = new BrightnessState(KEYBOARD_BRIGHT_BIT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800189 private final BrightnessState mButtonBrightness
The Android Open Source Project10592532009-03-18 17:39:46 -0700190 = new BrightnessState(BUTTON_BRIGHT_BIT);
Joe Onorato128e7292009-03-24 18:41:31 -0700191 private boolean mStillNeedSleepNotification;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800192 private boolean mIsPowered = false;
193 private IActivityManager mActivityService;
194 private IBatteryStats mBatteryStats;
195 private BatteryService mBatteryService;
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700196 private SensorManager mSensorManager;
197 private Sensor mProximitySensor;
Mike Lockwood8738e0c2009-10-04 08:44:47 -0400198 private Sensor mLightSensor;
199 private boolean mLightSensorEnabled;
200 private float mLightSensorValue = -1;
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700201 private float mLightSensorPendingValue = -1;
202 private int mLightSensorBrightness = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800203 private boolean mDimScreen = true;
204 private long mNextTimeout;
205 private volatile int mPokey = 0;
206 private volatile boolean mPokeAwakeOnSet = false;
207 private volatile boolean mInitComplete = false;
208 private HashMap<IBinder,PokeLock> mPokeLocks = new HashMap<IBinder,PokeLock>();
209 private long mScreenOnTime;
210 private long mScreenOnStartTime;
211 private boolean mPreventScreenOn;
212 private int mScreenBrightnessOverride = -1;
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700213 private boolean mHasHardwareAutoBrightness;
214 private boolean mAutoBrightessEnabled;
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700215 private int[] mAutoBrightnessLevels;
216 private int[] mLcdBacklightValues;
217 private int[] mButtonBacklightValues;
218 private int[] mKeyboardBacklightValues;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800219
220 // Used when logging number and duration of touch-down cycles
221 private long mTotalTouchDownTime;
222 private long mLastTouchDown;
223 private int mTouchCycles;
224
225 // could be either static or controllable at runtime
226 private static final boolean mSpew = false;
Mike Lockwood8738e0c2009-10-04 08:44:47 -0400227 private static final boolean mDebugLightSensor = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800228
229 /*
230 static PrintStream mLog;
231 static {
232 try {
233 mLog = new PrintStream("/data/power.log");
234 }
235 catch (FileNotFoundException e) {
236 android.util.Log.e(TAG, "Life is hard", e);
237 }
238 }
239 static class Log {
240 static void d(String tag, String s) {
241 mLog.println(s);
242 android.util.Log.d(tag, s);
243 }
244 static void i(String tag, String s) {
245 mLog.println(s);
246 android.util.Log.i(tag, s);
247 }
248 static void w(String tag, String s) {
249 mLog.println(s);
250 android.util.Log.w(tag, s);
251 }
252 static void e(String tag, String s) {
253 mLog.println(s);
254 android.util.Log.e(tag, s);
255 }
256 }
257 */
258
259 /**
260 * This class works around a deadlock between the lock in PowerManager.WakeLock
261 * and our synchronizing on mLocks. PowerManager.WakeLock synchronizes on its
262 * mToken object so it can be accessed from any thread, but it calls into here
263 * with its lock held. This class is essentially a reimplementation of
264 * PowerManager.WakeLock, but without that extra synchronized block, because we'll
265 * only call it with our own locks held.
266 */
267 private class UnsynchronizedWakeLock {
268 int mFlags;
269 String mTag;
270 IBinder mToken;
271 int mCount = 0;
272 boolean mRefCounted;
273
274 UnsynchronizedWakeLock(int flags, String tag, boolean refCounted) {
275 mFlags = flags;
276 mTag = tag;
277 mToken = new Binder();
278 mRefCounted = refCounted;
279 }
280
281 public void acquire() {
282 if (!mRefCounted || mCount++ == 0) {
283 long ident = Binder.clearCallingIdentity();
284 try {
285 PowerManagerService.this.acquireWakeLockLocked(mFlags, mToken,
286 MY_UID, mTag);
287 } finally {
288 Binder.restoreCallingIdentity(ident);
289 }
290 }
291 }
292
293 public void release() {
294 if (!mRefCounted || --mCount == 0) {
295 PowerManagerService.this.releaseWakeLockLocked(mToken, false);
296 }
297 if (mCount < 0) {
298 throw new RuntimeException("WakeLock under-locked " + mTag);
299 }
300 }
301
302 public String toString() {
303 return "UnsynchronizedWakeLock(mFlags=0x" + Integer.toHexString(mFlags)
304 + " mCount=" + mCount + ")";
305 }
306 }
307
308 private final class BatteryReceiver extends BroadcastReceiver {
309 @Override
310 public void onReceive(Context context, Intent intent) {
311 synchronized (mLocks) {
312 boolean wasPowered = mIsPowered;
313 mIsPowered = mBatteryService.isPowered();
314
315 if (mIsPowered != wasPowered) {
316 // update mStayOnWhilePluggedIn wake lock
317 updateWakeLockLocked();
318
319 // treat plugging and unplugging the devices as a user activity.
320 // users find it disconcerting when they unplug the device
321 // and it shuts off right away.
322 // temporarily set mUserActivityAllowed to true so this will work
323 // even when the keyguard is on.
324 synchronized (mLocks) {
Mike Lockwood200b30b2009-09-20 00:23:59 -0400325 forceUserActivityLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800326 }
327 }
328 }
329 }
330 }
331
332 /**
333 * Set the setting that determines whether the device stays on when plugged in.
334 * The argument is a bit string, with each bit specifying a power source that,
335 * when the device is connected to that source, causes the device to stay on.
336 * See {@link android.os.BatteryManager} for the list of power sources that
337 * can be specified. Current values include {@link android.os.BatteryManager#BATTERY_PLUGGED_AC}
338 * and {@link android.os.BatteryManager#BATTERY_PLUGGED_USB}
339 * @param val an {@code int} containing the bits that specify which power sources
340 * should cause the device to stay on.
341 */
342 public void setStayOnSetting(int val) {
343 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SETTINGS, null);
344 Settings.System.putInt(mContext.getContentResolver(),
345 Settings.System.STAY_ON_WHILE_PLUGGED_IN, val);
346 }
347
348 private class SettingsObserver implements Observer {
349 private int getInt(String name) {
350 return mSettings.getValues(name).getAsInteger(Settings.System.VALUE);
351 }
352
353 public void update(Observable o, Object arg) {
354 synchronized (mLocks) {
355 // STAY_ON_WHILE_PLUGGED_IN
356 mStayOnConditions = getInt(STAY_ON_WHILE_PLUGGED_IN);
357 updateWakeLockLocked();
358
359 // SCREEN_OFF_TIMEOUT
360 mTotalDelaySetting = getInt(SCREEN_OFF_TIMEOUT);
361
362 // DIM_SCREEN
363 //mDimScreen = getInt(DIM_SCREEN) != 0;
364
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700365 // SCREEN_BRIGHTNESS_MODE
366 setScreenBrightnessMode(getInt(SCREEN_BRIGHTNESS_MODE));
367
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800368 // recalculate everything
369 setScreenOffTimeoutsLocked();
370 }
371 }
372 }
373
374 PowerManagerService()
375 {
376 // Hack to get our uid... should have a func for this.
377 long token = Binder.clearCallingIdentity();
378 MY_UID = Binder.getCallingUid();
379 Binder.restoreCallingIdentity(token);
380
381 // XXX remove this when the kernel doesn't timeout wake locks
382 Power.setLastUserActivityTimeout(7*24*3600*1000); // one week
383
384 // assume nothing is on yet
385 mUserState = mPowerState = 0;
386
387 // Add ourself to the Watchdog monitors.
388 Watchdog.getInstance().addMonitor(this);
389 mScreenOnStartTime = SystemClock.elapsedRealtime();
390 }
391
392 private ContentQueryMap mSettings;
393
The Android Open Source Project10592532009-03-18 17:39:46 -0700394 void init(Context context, HardwareService hardware, IActivityManager activity,
395 BatteryService battery) {
396 mHardware = hardware;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800397 mContext = context;
398 mActivityService = activity;
399 mBatteryStats = BatteryStatsService.getService();
400 mBatteryService = battery;
401
402 mHandlerThread = new HandlerThread("PowerManagerService") {
403 @Override
404 protected void onLooperPrepared() {
405 super.onLooperPrepared();
406 initInThread();
407 }
408 };
409 mHandlerThread.start();
410
411 synchronized (mHandlerThread) {
412 while (!mInitComplete) {
413 try {
414 mHandlerThread.wait();
415 } catch (InterruptedException e) {
416 // Ignore
417 }
418 }
419 }
420 }
421
422 void initInThread() {
423 mHandler = new Handler();
424
425 mBroadcastWakeLock = new UnsynchronizedWakeLock(
Joe Onorato128e7292009-03-24 18:41:31 -0700426 PowerManager.PARTIAL_WAKE_LOCK, "sleep_broadcast", true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800427 mStayOnWhilePluggedInScreenDimLock = new UnsynchronizedWakeLock(
428 PowerManager.SCREEN_DIM_WAKE_LOCK, "StayOnWhilePluggedIn Screen Dim", false);
429 mStayOnWhilePluggedInPartialLock = new UnsynchronizedWakeLock(
430 PowerManager.PARTIAL_WAKE_LOCK, "StayOnWhilePluggedIn Partial", false);
431 mPreventScreenOnPartialLock = new UnsynchronizedWakeLock(
432 PowerManager.PARTIAL_WAKE_LOCK, "PreventScreenOn Partial", false);
433
434 mScreenOnIntent = new Intent(Intent.ACTION_SCREEN_ON);
435 mScreenOnIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
436 mScreenOffIntent = new Intent(Intent.ACTION_SCREEN_OFF);
437 mScreenOffIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
438
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700439 Resources resources = mContext.getResources();
440 mHasHardwareAutoBrightness = resources.getBoolean(
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700441 com.android.internal.R.bool.config_hardware_automatic_brightness_available);
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700442 if (!mHasHardwareAutoBrightness) {
443 mAutoBrightnessLevels = resources.getIntArray(
444 com.android.internal.R.array.config_autoBrightnessLevels);
445 mLcdBacklightValues = resources.getIntArray(
446 com.android.internal.R.array.config_autoBrightnessLcdBacklightValues);
447 mButtonBacklightValues = resources.getIntArray(
448 com.android.internal.R.array.config_autoBrightnessButtonBacklightValues);
449 mKeyboardBacklightValues = resources.getIntArray(
450 com.android.internal.R.array.config_autoBrightnessKeyboardBacklightValues);
451 }
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700452
453 ContentResolver resolver = mContext.getContentResolver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800454 Cursor settingsCursor = resolver.query(Settings.System.CONTENT_URI, null,
455 "(" + Settings.System.NAME + "=?) or ("
456 + Settings.System.NAME + "=?) or ("
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700457 + Settings.System.NAME + "=?) or ("
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800458 + Settings.System.NAME + "=?)",
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700459 new String[]{STAY_ON_WHILE_PLUGGED_IN, SCREEN_OFF_TIMEOUT, DIM_SCREEN,
460 SCREEN_BRIGHTNESS_MODE},
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800461 null);
462 mSettings = new ContentQueryMap(settingsCursor, Settings.System.NAME, true, mHandler);
463 SettingsObserver settingsObserver = new SettingsObserver();
464 mSettings.addObserver(settingsObserver);
465
466 // pretend that the settings changed so we will get their initial state
467 settingsObserver.update(mSettings, null);
468
469 // register for the battery changed notifications
470 IntentFilter filter = new IntentFilter();
471 filter.addAction(Intent.ACTION_BATTERY_CHANGED);
472 mContext.registerReceiver(new BatteryReceiver(), filter);
473
474 // Listen for Gservices changes
475 IntentFilter gservicesChangedFilter =
476 new IntentFilter(Settings.Gservices.CHANGED_ACTION);
477 mContext.registerReceiver(new GservicesChangedReceiver(), gservicesChangedFilter);
478 // And explicitly do the initial update of our cached settings
479 updateGservicesValues();
480
Mike Lockwood3333fa42009-10-26 14:50:42 -0400481 if (mAutoBrightessEnabled && !mHasHardwareAutoBrightness) {
Mike Lockwood6c97fca2009-10-20 08:10:00 -0400482 // turn the screen on
483 setPowerState(SCREEN_BRIGHT);
484 } else {
485 // turn everything on
486 setPowerState(ALL_BRIGHT);
487 }
Dan Murphy951764b2009-08-27 14:59:03 -0500488
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800489 synchronized (mHandlerThread) {
490 mInitComplete = true;
491 mHandlerThread.notifyAll();
492 }
493 }
494
495 private class WakeLock implements IBinder.DeathRecipient
496 {
497 WakeLock(int f, IBinder b, String t, int u) {
498 super();
499 flags = f;
500 binder = b;
501 tag = t;
502 uid = u == MY_UID ? Process.SYSTEM_UID : u;
503 if (u != MY_UID || (
504 !"KEEP_SCREEN_ON_FLAG".equals(tag)
505 && !"KeyInputQueue".equals(tag))) {
506 monitorType = (f & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK
507 ? BatteryStats.WAKE_TYPE_PARTIAL
508 : BatteryStats.WAKE_TYPE_FULL;
509 } else {
510 monitorType = -1;
511 }
512 try {
513 b.linkToDeath(this, 0);
514 } catch (RemoteException e) {
515 binderDied();
516 }
517 }
518 public void binderDied() {
519 synchronized (mLocks) {
520 releaseWakeLockLocked(this.binder, true);
521 }
522 }
523 final int flags;
524 final IBinder binder;
525 final String tag;
526 final int uid;
527 final int monitorType;
528 boolean activated = true;
529 int minState;
530 }
531
532 private void updateWakeLockLocked() {
533 if (mStayOnConditions != 0 && mBatteryService.isPowered(mStayOnConditions)) {
534 // keep the device on if we're plugged in and mStayOnWhilePluggedIn is set.
535 mStayOnWhilePluggedInScreenDimLock.acquire();
536 mStayOnWhilePluggedInPartialLock.acquire();
537 } else {
538 mStayOnWhilePluggedInScreenDimLock.release();
539 mStayOnWhilePluggedInPartialLock.release();
540 }
541 }
542
543 private boolean isScreenLock(int flags)
544 {
545 int n = flags & LOCK_MASK;
546 return n == PowerManager.FULL_WAKE_LOCK
547 || n == PowerManager.SCREEN_BRIGHT_WAKE_LOCK
548 || n == PowerManager.SCREEN_DIM_WAKE_LOCK;
549 }
550
551 public void acquireWakeLock(int flags, IBinder lock, String tag) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800552 int uid = Binder.getCallingUid();
Michael Chane96440f2009-05-06 10:27:36 -0700553 if (uid != Process.myUid()) {
554 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
555 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800556 long ident = Binder.clearCallingIdentity();
557 try {
558 synchronized (mLocks) {
559 acquireWakeLockLocked(flags, lock, uid, tag);
560 }
561 } finally {
562 Binder.restoreCallingIdentity(ident);
563 }
564 }
565
566 public void acquireWakeLockLocked(int flags, IBinder lock, int uid, String tag) {
567 int acquireUid = -1;
568 String acquireName = null;
569 int acquireType = -1;
570
571 if (mSpew) {
572 Log.d(TAG, "acquireWakeLock flags=0x" + Integer.toHexString(flags) + " tag=" + tag);
573 }
574
575 int index = mLocks.getIndex(lock);
576 WakeLock wl;
577 boolean newlock;
578 if (index < 0) {
579 wl = new WakeLock(flags, lock, tag, uid);
580 switch (wl.flags & LOCK_MASK)
581 {
582 case PowerManager.FULL_WAKE_LOCK:
Mike Lockwood3333fa42009-10-26 14:50:42 -0400583 if (mAutoBrightessEnabled && !mHasHardwareAutoBrightness) {
584 wl.minState = SCREEN_BRIGHT;
585 } else {
586 wl.minState = (mKeyboardVisible ? ALL_BRIGHT : SCREEN_BUTTON_BRIGHT);
587 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800588 break;
589 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
590 wl.minState = SCREEN_BRIGHT;
591 break;
592 case PowerManager.SCREEN_DIM_WAKE_LOCK:
593 wl.minState = SCREEN_DIM;
594 break;
595 case PowerManager.PARTIAL_WAKE_LOCK:
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700596 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800597 break;
598 default:
599 // just log and bail. we're in the server, so don't
600 // throw an exception.
601 Log.e(TAG, "bad wakelock type for lock '" + tag + "' "
602 + " flags=" + flags);
603 return;
604 }
605 mLocks.addLock(wl);
606 newlock = true;
607 } else {
608 wl = mLocks.get(index);
609 newlock = false;
610 }
611 if (isScreenLock(flags)) {
612 // if this causes a wakeup, we reactivate all of the locks and
613 // set it to whatever they want. otherwise, we modulate that
614 // by the current state so we never turn it more on than
615 // it already is.
616 if ((wl.flags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) {
Michael Chane96440f2009-05-06 10:27:36 -0700617 int oldWakeLockState = mWakeLockState;
618 mWakeLockState = mLocks.reactivateScreenLocksLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800619 if (mSpew) {
620 Log.d(TAG, "wakeup here mUserState=0x" + Integer.toHexString(mUserState)
Michael Chane96440f2009-05-06 10:27:36 -0700621 + " mWakeLockState=0x"
622 + Integer.toHexString(mWakeLockState)
623 + " previous wakeLockState=0x" + Integer.toHexString(oldWakeLockState));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800624 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800625 } else {
626 if (mSpew) {
627 Log.d(TAG, "here mUserState=0x" + Integer.toHexString(mUserState)
628 + " mLocks.gatherState()=0x"
629 + Integer.toHexString(mLocks.gatherState())
630 + " mWakeLockState=0x" + Integer.toHexString(mWakeLockState));
631 }
632 mWakeLockState = (mUserState | mWakeLockState) & mLocks.gatherState();
633 }
634 setPowerState(mWakeLockState | mUserState);
635 }
636 else if ((flags & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK) {
637 if (newlock) {
638 mPartialCount++;
639 if (mPartialCount == 1) {
640 if (LOG_PARTIAL_WL) EventLog.writeEvent(LOG_POWER_PARTIAL_WAKE_STATE, 1, tag);
641 }
642 }
643 Power.acquireWakeLock(Power.PARTIAL_WAKE_LOCK,PARTIAL_NAME);
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700644 } else if ((flags & LOCK_MASK) == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK) {
645 mProximityCount++;
646 if (mProximityCount == 1) {
647 enableProximityLockLocked();
648 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800649 }
650 if (newlock) {
651 acquireUid = wl.uid;
652 acquireName = wl.tag;
653 acquireType = wl.monitorType;
654 }
655
656 if (acquireType >= 0) {
657 try {
658 mBatteryStats.noteStartWakelock(acquireUid, acquireName, acquireType);
659 } catch (RemoteException e) {
660 // Ignore
661 }
662 }
663 }
664
665 public void releaseWakeLock(IBinder lock) {
Michael Chane96440f2009-05-06 10:27:36 -0700666 int uid = Binder.getCallingUid();
667 if (uid != Process.myUid()) {
668 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
669 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800670
671 synchronized (mLocks) {
672 releaseWakeLockLocked(lock, false);
673 }
674 }
675
676 private void releaseWakeLockLocked(IBinder lock, boolean death) {
677 int releaseUid;
678 String releaseName;
679 int releaseType;
680
681 WakeLock wl = mLocks.removeLock(lock);
682 if (wl == null) {
683 return;
684 }
685
686 if (mSpew) {
687 Log.d(TAG, "releaseWakeLock flags=0x"
688 + Integer.toHexString(wl.flags) + " tag=" + wl.tag);
689 }
690
691 if (isScreenLock(wl.flags)) {
692 mWakeLockState = mLocks.gatherState();
693 // goes in the middle to reduce flicker
694 if ((wl.flags & PowerManager.ON_AFTER_RELEASE) != 0) {
695 userActivity(SystemClock.uptimeMillis(), false);
696 }
697 setPowerState(mWakeLockState | mUserState);
698 }
699 else if ((wl.flags & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK) {
700 mPartialCount--;
701 if (mPartialCount == 0) {
702 if (LOG_PARTIAL_WL) EventLog.writeEvent(LOG_POWER_PARTIAL_WAKE_STATE, 0, wl.tag);
703 Power.releaseWakeLock(PARTIAL_NAME);
704 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700705 } else if ((wl.flags & LOCK_MASK) == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK) {
706 mProximityCount--;
707 if (mProximityCount == 0) {
708 disableProximityLockLocked();
709 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800710 }
711 // Unlink the lock from the binder.
712 wl.binder.unlinkToDeath(wl, 0);
713 releaseUid = wl.uid;
714 releaseName = wl.tag;
715 releaseType = wl.monitorType;
716
717 if (releaseType >= 0) {
718 long origId = Binder.clearCallingIdentity();
719 try {
720 mBatteryStats.noteStopWakelock(releaseUid, releaseName, releaseType);
721 } catch (RemoteException e) {
722 // Ignore
723 } finally {
724 Binder.restoreCallingIdentity(origId);
725 }
726 }
727 }
728
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800729 private class PokeLock implements IBinder.DeathRecipient
730 {
731 PokeLock(int p, IBinder b, String t) {
732 super();
733 this.pokey = p;
734 this.binder = b;
735 this.tag = t;
736 try {
737 b.linkToDeath(this, 0);
738 } catch (RemoteException e) {
739 binderDied();
740 }
741 }
742 public void binderDied() {
743 setPokeLock(0, this.binder, this.tag);
744 }
745 int pokey;
746 IBinder binder;
747 String tag;
748 boolean awakeOnSet;
749 }
750
751 public void setPokeLock(int pokey, IBinder token, String tag) {
752 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
753 if (token == null) {
754 Log.e(TAG, "setPokeLock got null token for tag='" + tag + "'");
755 return;
756 }
757
758 if ((pokey & POKE_LOCK_TIMEOUT_MASK) == POKE_LOCK_TIMEOUT_MASK) {
759 throw new IllegalArgumentException("setPokeLock can't have both POKE_LOCK_SHORT_TIMEOUT"
760 + " and POKE_LOCK_MEDIUM_TIMEOUT");
761 }
762
763 synchronized (mLocks) {
764 if (pokey != 0) {
765 PokeLock p = mPokeLocks.get(token);
766 int oldPokey = 0;
767 if (p != null) {
768 oldPokey = p.pokey;
769 p.pokey = pokey;
770 } else {
771 p = new PokeLock(pokey, token, tag);
772 mPokeLocks.put(token, p);
773 }
774 int oldTimeout = oldPokey & POKE_LOCK_TIMEOUT_MASK;
775 int newTimeout = pokey & POKE_LOCK_TIMEOUT_MASK;
776 if (((mPowerState & SCREEN_ON_BIT) == 0) && (oldTimeout != newTimeout)) {
777 p.awakeOnSet = true;
778 }
779 } else {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -0700780 PokeLock rLock = mPokeLocks.remove(token);
781 if (rLock != null) {
782 token.unlinkToDeath(rLock, 0);
783 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800784 }
785
786 int oldPokey = mPokey;
787 int cumulative = 0;
788 boolean oldAwakeOnSet = mPokeAwakeOnSet;
789 boolean awakeOnSet = false;
790 for (PokeLock p: mPokeLocks.values()) {
791 cumulative |= p.pokey;
792 if (p.awakeOnSet) {
793 awakeOnSet = true;
794 }
795 }
796 mPokey = cumulative;
797 mPokeAwakeOnSet = awakeOnSet;
798
799 int oldCumulativeTimeout = oldPokey & POKE_LOCK_TIMEOUT_MASK;
800 int newCumulativeTimeout = pokey & POKE_LOCK_TIMEOUT_MASK;
801
802 if (oldCumulativeTimeout != newCumulativeTimeout) {
803 setScreenOffTimeoutsLocked();
804 // reset the countdown timer, but use the existing nextState so it doesn't
805 // change anything
806 setTimeoutLocked(SystemClock.uptimeMillis(), mTimeoutTask.nextState);
807 }
808 }
809 }
810
811 private static String lockType(int type)
812 {
813 switch (type)
814 {
815 case PowerManager.FULL_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -0700816 return "FULL_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800817 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -0700818 return "SCREEN_BRIGHT_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800819 case PowerManager.SCREEN_DIM_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -0700820 return "SCREEN_DIM_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800821 case PowerManager.PARTIAL_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -0700822 return "PARTIAL_WAKE_LOCK ";
823 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
824 return "PROXIMITY_SCREEN_OFF_WAKE_LOCK";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800825 default:
David Brown251faa62009-08-02 22:04:36 -0700826 return "??? ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800827 }
828 }
829
830 private static String dumpPowerState(int state) {
831 return (((state & KEYBOARD_BRIGHT_BIT) != 0)
832 ? "KEYBOARD_BRIGHT_BIT " : "")
833 + (((state & SCREEN_BRIGHT_BIT) != 0)
834 ? "SCREEN_BRIGHT_BIT " : "")
835 + (((state & SCREEN_ON_BIT) != 0)
836 ? "SCREEN_ON_BIT " : "")
837 + (((state & BATTERY_LOW_BIT) != 0)
838 ? "BATTERY_LOW_BIT " : "");
839 }
840
841 @Override
842 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
843 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
844 != PackageManager.PERMISSION_GRANTED) {
845 pw.println("Permission Denial: can't dump PowerManager from from pid="
846 + Binder.getCallingPid()
847 + ", uid=" + Binder.getCallingUid());
848 return;
849 }
850
851 long now = SystemClock.uptimeMillis();
852
853 pw.println("Power Manager State:");
854 pw.println(" mIsPowered=" + mIsPowered
855 + " mPowerState=" + mPowerState
856 + " mScreenOffTime=" + (SystemClock.elapsedRealtime()-mScreenOffTime)
857 + " ms");
858 pw.println(" mPartialCount=" + mPartialCount);
859 pw.println(" mWakeLockState=" + dumpPowerState(mWakeLockState));
860 pw.println(" mUserState=" + dumpPowerState(mUserState));
861 pw.println(" mPowerState=" + dumpPowerState(mPowerState));
862 pw.println(" mLocks.gather=" + dumpPowerState(mLocks.gatherState()));
863 pw.println(" mNextTimeout=" + mNextTimeout + " now=" + now
864 + " " + ((mNextTimeout-now)/1000) + "s from now");
865 pw.println(" mDimScreen=" + mDimScreen
866 + " mStayOnConditions=" + mStayOnConditions);
867 pw.println(" mOffBecauseOfUser=" + mOffBecauseOfUser
868 + " mUserState=" + mUserState);
Joe Onorato128e7292009-03-24 18:41:31 -0700869 pw.println(" mBroadcastQueue={" + mBroadcastQueue[0] + ',' + mBroadcastQueue[1]
870 + ',' + mBroadcastQueue[2] + "}");
871 pw.println(" mBroadcastWhy={" + mBroadcastWhy[0] + ',' + mBroadcastWhy[1]
872 + ',' + mBroadcastWhy[2] + "}");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800873 pw.println(" mPokey=" + mPokey + " mPokeAwakeonSet=" + mPokeAwakeOnSet);
874 pw.println(" mKeyboardVisible=" + mKeyboardVisible
875 + " mUserActivityAllowed=" + mUserActivityAllowed);
876 pw.println(" mKeylightDelay=" + mKeylightDelay + " mDimDelay=" + mDimDelay
877 + " mScreenOffDelay=" + mScreenOffDelay);
878 pw.println(" mPreventScreenOn=" + mPreventScreenOn
879 + " mScreenBrightnessOverride=" + mScreenBrightnessOverride);
880 pw.println(" mTotalDelaySetting=" + mTotalDelaySetting);
881 pw.println(" mBroadcastWakeLock=" + mBroadcastWakeLock);
882 pw.println(" mStayOnWhilePluggedInScreenDimLock=" + mStayOnWhilePluggedInScreenDimLock);
883 pw.println(" mStayOnWhilePluggedInPartialLock=" + mStayOnWhilePluggedInPartialLock);
884 pw.println(" mPreventScreenOnPartialLock=" + mPreventScreenOnPartialLock);
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700885 pw.println(" mProximitySensorActive=" + mProximitySensorActive);
886 pw.println(" mLightSensorEnabled=" + mLightSensorEnabled);
887 pw.println(" mLightSensorValue=" + mLightSensorValue);
888 pw.println(" mLightSensorPendingValue=" + mLightSensorPendingValue);
889 pw.println(" mHasHardwareAutoBrightness=" + mHasHardwareAutoBrightness);
890 pw.println(" mAutoBrightessEnabled=" + mAutoBrightessEnabled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800891 mScreenBrightness.dump(pw, " mScreenBrightness: ");
892 mKeyboardBrightness.dump(pw, " mKeyboardBrightness: ");
893 mButtonBrightness.dump(pw, " mButtonBrightness: ");
894
895 int N = mLocks.size();
896 pw.println();
897 pw.println("mLocks.size=" + N + ":");
898 for (int i=0; i<N; i++) {
899 WakeLock wl = mLocks.get(i);
900 String type = lockType(wl.flags & LOCK_MASK);
901 String acquireCausesWakeup = "";
902 if ((wl.flags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) {
903 acquireCausesWakeup = "ACQUIRE_CAUSES_WAKEUP ";
904 }
905 String activated = "";
906 if (wl.activated) {
907 activated = " activated";
908 }
909 pw.println(" " + type + " '" + wl.tag + "'" + acquireCausesWakeup
910 + activated + " (minState=" + wl.minState + ")");
911 }
912
913 pw.println();
914 pw.println("mPokeLocks.size=" + mPokeLocks.size() + ":");
915 for (PokeLock p: mPokeLocks.values()) {
916 pw.println(" poke lock '" + p.tag + "':"
917 + ((p.pokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0
918 ? " POKE_LOCK_IGNORE_CHEEK_EVENTS" : "")
Joe Onoratoe68ffcb2009-03-24 19:11:13 -0700919 + ((p.pokey & POKE_LOCK_IGNORE_TOUCH_AND_CHEEK_EVENTS) != 0
920 ? " POKE_LOCK_IGNORE_TOUCH_AND_CHEEK_EVENTS" : "")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800921 + ((p.pokey & POKE_LOCK_SHORT_TIMEOUT) != 0
922 ? " POKE_LOCK_SHORT_TIMEOUT" : "")
923 + ((p.pokey & POKE_LOCK_MEDIUM_TIMEOUT) != 0
924 ? " POKE_LOCK_MEDIUM_TIMEOUT" : ""));
925 }
926
927 pw.println();
928 }
929
930 private void setTimeoutLocked(long now, int nextState)
931 {
932 if (mDoneBooting) {
933 mHandler.removeCallbacks(mTimeoutTask);
934 mTimeoutTask.nextState = nextState;
935 long when = now;
936 switch (nextState)
937 {
938 case SCREEN_BRIGHT:
939 when += mKeylightDelay;
940 break;
941 case SCREEN_DIM:
942 if (mDimDelay >= 0) {
943 when += mDimDelay;
944 break;
945 } else {
946 Log.w(TAG, "mDimDelay=" + mDimDelay + " while trying to dim");
947 }
948 case SCREEN_OFF:
949 synchronized (mLocks) {
950 when += mScreenOffDelay;
951 }
952 break;
953 }
954 if (mSpew) {
955 Log.d(TAG, "setTimeoutLocked now=" + now + " nextState=" + nextState
956 + " when=" + when);
957 }
958 mHandler.postAtTime(mTimeoutTask, when);
959 mNextTimeout = when; // for debugging
960 }
961 }
962
963 private void cancelTimerLocked()
964 {
965 mHandler.removeCallbacks(mTimeoutTask);
966 mTimeoutTask.nextState = -1;
967 }
968
969 private class TimeoutTask implements Runnable
970 {
971 int nextState; // access should be synchronized on mLocks
972 public void run()
973 {
974 synchronized (mLocks) {
975 if (mSpew) {
976 Log.d(TAG, "user activity timeout timed out nextState=" + this.nextState);
977 }
978
979 if (nextState == -1) {
980 return;
981 }
982
983 mUserState = this.nextState;
984 setPowerState(this.nextState | mWakeLockState);
985
986 long now = SystemClock.uptimeMillis();
987
988 switch (this.nextState)
989 {
990 case SCREEN_BRIGHT:
991 if (mDimDelay >= 0) {
992 setTimeoutLocked(now, SCREEN_DIM);
993 break;
994 }
995 case SCREEN_DIM:
996 setTimeoutLocked(now, SCREEN_OFF);
997 break;
998 }
999 }
1000 }
1001 }
1002
1003 private void sendNotificationLocked(boolean on, int why)
1004 {
Joe Onorato64c62ba2009-03-24 20:13:57 -07001005 if (!on) {
1006 mStillNeedSleepNotification = false;
1007 }
1008
Joe Onorato128e7292009-03-24 18:41:31 -07001009 // Add to the queue.
1010 int index = 0;
1011 while (mBroadcastQueue[index] != -1) {
1012 index++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001013 }
Joe Onorato128e7292009-03-24 18:41:31 -07001014 mBroadcastQueue[index] = on ? 1 : 0;
1015 mBroadcastWhy[index] = why;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001016
Joe Onorato128e7292009-03-24 18:41:31 -07001017 // If we added it position 2, then there is a pair that can be stripped.
1018 // If we added it position 1 and we're turning the screen off, we can strip
1019 // the pair and do nothing, because the screen is already off, and therefore
1020 // keyguard has already been enabled.
1021 // However, if we added it at position 1 and we're turning it on, then position
1022 // 0 was to turn it off, and we can't strip that, because keyguard needs to come
1023 // on, so have to run the queue then.
1024 if (index == 2) {
1025 // Also, while we're collapsing them, if it's going to be an "off," and one
1026 // is off because of user, then use that, regardless of whether it's the first
1027 // or second one.
1028 if (!on && why == WindowManagerPolicy.OFF_BECAUSE_OF_USER) {
1029 mBroadcastWhy[0] = WindowManagerPolicy.OFF_BECAUSE_OF_USER;
1030 }
1031 mBroadcastQueue[0] = on ? 1 : 0;
1032 mBroadcastQueue[1] = -1;
1033 mBroadcastQueue[2] = -1;
1034 index = 0;
1035 }
1036 if (index == 1 && !on) {
1037 mBroadcastQueue[0] = -1;
1038 mBroadcastQueue[1] = -1;
1039 index = -1;
1040 // The wake lock was being held, but we're not actually going to do any
1041 // broadcasts, so release the wake lock.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001042 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_STOP, 1, mBroadcastWakeLock.mCount);
1043 mBroadcastWakeLock.release();
Joe Onorato128e7292009-03-24 18:41:31 -07001044 }
1045
1046 // Now send the message.
1047 if (index >= 0) {
1048 // Acquire the broadcast wake lock before changing the power
1049 // state. It will be release after the broadcast is sent.
1050 // We always increment the ref count for each notification in the queue
1051 // and always decrement when that notification is handled.
1052 mBroadcastWakeLock.acquire();
1053 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_SEND, mBroadcastWakeLock.mCount);
1054 mHandler.post(mNotificationTask);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001055 }
1056 }
1057
1058 private Runnable mNotificationTask = new Runnable()
1059 {
1060 public void run()
1061 {
Joe Onorato128e7292009-03-24 18:41:31 -07001062 while (true) {
1063 int value;
1064 int why;
1065 WindowManagerPolicy policy;
1066 synchronized (mLocks) {
1067 value = mBroadcastQueue[0];
1068 why = mBroadcastWhy[0];
1069 for (int i=0; i<2; i++) {
1070 mBroadcastQueue[i] = mBroadcastQueue[i+1];
1071 mBroadcastWhy[i] = mBroadcastWhy[i+1];
1072 }
1073 policy = getPolicyLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001074 }
Joe Onorato128e7292009-03-24 18:41:31 -07001075 if (value == 1) {
1076 mScreenOnStart = SystemClock.uptimeMillis();
1077
1078 policy.screenTurnedOn();
1079 try {
1080 ActivityManagerNative.getDefault().wakingUp();
1081 } catch (RemoteException e) {
1082 // ignore it
1083 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001084
Joe Onorato128e7292009-03-24 18:41:31 -07001085 if (mSpew) {
1086 Log.d(TAG, "mBroadcastWakeLock=" + mBroadcastWakeLock);
1087 }
1088 if (mContext != null && ActivityManagerNative.isSystemReady()) {
1089 mContext.sendOrderedBroadcast(mScreenOnIntent, null,
1090 mScreenOnBroadcastDone, mHandler, 0, null, null);
1091 } else {
1092 synchronized (mLocks) {
1093 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_STOP, 2,
1094 mBroadcastWakeLock.mCount);
1095 mBroadcastWakeLock.release();
1096 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001097 }
1098 }
Joe Onorato128e7292009-03-24 18:41:31 -07001099 else if (value == 0) {
1100 mScreenOffStart = SystemClock.uptimeMillis();
1101
1102 policy.screenTurnedOff(why);
1103 try {
1104 ActivityManagerNative.getDefault().goingToSleep();
1105 } catch (RemoteException e) {
1106 // ignore it.
1107 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001108
Joe Onorato128e7292009-03-24 18:41:31 -07001109 if (mContext != null && ActivityManagerNative.isSystemReady()) {
1110 mContext.sendOrderedBroadcast(mScreenOffIntent, null,
1111 mScreenOffBroadcastDone, mHandler, 0, null, null);
1112 } else {
1113 synchronized (mLocks) {
1114 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_STOP, 3,
1115 mBroadcastWakeLock.mCount);
1116 mBroadcastWakeLock.release();
1117 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001118 }
1119 }
Joe Onorato128e7292009-03-24 18:41:31 -07001120 else {
1121 // If we're in this case, then this handler is running for a previous
1122 // paired transaction. mBroadcastWakeLock will already have been released.
1123 break;
1124 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001125 }
1126 }
1127 };
1128
1129 long mScreenOnStart;
1130 private BroadcastReceiver mScreenOnBroadcastDone = new BroadcastReceiver() {
1131 public void onReceive(Context context, Intent intent) {
1132 synchronized (mLocks) {
1133 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_DONE, 1,
1134 SystemClock.uptimeMillis() - mScreenOnStart, mBroadcastWakeLock.mCount);
1135 mBroadcastWakeLock.release();
1136 }
1137 }
1138 };
1139
1140 long mScreenOffStart;
1141 private BroadcastReceiver mScreenOffBroadcastDone = new BroadcastReceiver() {
1142 public void onReceive(Context context, Intent intent) {
1143 synchronized (mLocks) {
1144 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_DONE, 0,
1145 SystemClock.uptimeMillis() - mScreenOffStart, mBroadcastWakeLock.mCount);
1146 mBroadcastWakeLock.release();
1147 }
1148 }
1149 };
1150
1151 void logPointerUpEvent() {
1152 if (LOG_TOUCH_DOWNS) {
1153 mTotalTouchDownTime += SystemClock.elapsedRealtime() - mLastTouchDown;
1154 mLastTouchDown = 0;
1155 }
1156 }
1157
1158 void logPointerDownEvent() {
1159 if (LOG_TOUCH_DOWNS) {
1160 // If we are not already timing a down/up sequence
1161 if (mLastTouchDown == 0) {
1162 mLastTouchDown = SystemClock.elapsedRealtime();
1163 mTouchCycles++;
1164 }
1165 }
1166 }
1167
1168 /**
1169 * Prevents the screen from turning on even if it *should* turn on due
1170 * to a subsequent full wake lock being acquired.
1171 * <p>
1172 * This is a temporary hack that allows an activity to "cover up" any
1173 * display glitches that happen during the activity's startup
1174 * sequence. (Specifically, this API was added to work around a
1175 * cosmetic bug in the "incoming call" sequence, where the lock screen
1176 * would flicker briefly before the incoming call UI became visible.)
1177 * TODO: There ought to be a more elegant way of doing this,
1178 * probably by having the PowerManager and ActivityManager
1179 * work together to let apps specify that the screen on/off
1180 * state should be synchronized with the Activity lifecycle.
1181 * <p>
1182 * Note that calling preventScreenOn(true) will NOT turn the screen
1183 * off if it's currently on. (This API only affects *future*
1184 * acquisitions of full wake locks.)
1185 * But calling preventScreenOn(false) WILL turn the screen on if
1186 * it's currently off because of a prior preventScreenOn(true) call.
1187 * <p>
1188 * Any call to preventScreenOn(true) MUST be followed promptly by a call
1189 * to preventScreenOn(false). In fact, if the preventScreenOn(false)
1190 * call doesn't occur within 5 seconds, we'll turn the screen back on
1191 * ourselves (and log a warning about it); this prevents a buggy app
1192 * from disabling the screen forever.)
1193 * <p>
1194 * TODO: this feature should really be controlled by a new type of poke
1195 * lock (rather than an IPowerManager call).
1196 */
1197 public void preventScreenOn(boolean prevent) {
1198 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1199
1200 synchronized (mLocks) {
1201 if (prevent) {
1202 // First of all, grab a partial wake lock to
1203 // make sure the CPU stays on during the entire
1204 // preventScreenOn(true) -> preventScreenOn(false) sequence.
1205 mPreventScreenOnPartialLock.acquire();
1206
1207 // Post a forceReenableScreen() call (for 5 seconds in the
1208 // future) to make sure the matching preventScreenOn(false) call
1209 // has happened by then.
1210 mHandler.removeCallbacks(mForceReenableScreenTask);
1211 mHandler.postDelayed(mForceReenableScreenTask, 5000);
1212
1213 // Finally, set the flag that prevents the screen from turning on.
1214 // (Below, in setPowerState(), we'll check mPreventScreenOn and
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001215 // we *won't* call setScreenStateLocked(true) if it's set.)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001216 mPreventScreenOn = true;
1217 } else {
1218 // (Re)enable the screen.
1219 mPreventScreenOn = false;
1220
1221 // We're "undoing" a the prior preventScreenOn(true) call, so we
1222 // no longer need the 5-second safeguard.
1223 mHandler.removeCallbacks(mForceReenableScreenTask);
1224
1225 // Forcibly turn on the screen if it's supposed to be on. (This
1226 // handles the case where the screen is currently off because of
1227 // a prior preventScreenOn(true) call.)
1228 if ((mPowerState & SCREEN_ON_BIT) != 0) {
1229 if (mSpew) {
1230 Log.d(TAG,
1231 "preventScreenOn: turning on after a prior preventScreenOn(true)!");
1232 }
Mike Lockwoodf003c0c2009-10-21 16:03:18 -04001233 mAnimatingScreenOff = false;
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001234 int err = setScreenStateLocked(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001235 if (err != 0) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001236 Log.w(TAG, "preventScreenOn: error from setScreenStateLocked(): " + err);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001237 }
1238 }
1239
1240 // Release the partial wake lock that we held during the
1241 // preventScreenOn(true) -> preventScreenOn(false) sequence.
1242 mPreventScreenOnPartialLock.release();
1243 }
1244 }
1245 }
1246
1247 public void setScreenBrightnessOverride(int brightness) {
1248 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1249
1250 synchronized (mLocks) {
1251 if (mScreenBrightnessOverride != brightness) {
1252 mScreenBrightnessOverride = brightness;
1253 updateLightsLocked(mPowerState, SCREEN_ON_BIT);
1254 }
1255 }
1256 }
1257
1258 /**
1259 * Sanity-check that gets called 5 seconds after any call to
1260 * preventScreenOn(true). This ensures that the original call
1261 * is followed promptly by a call to preventScreenOn(false).
1262 */
1263 private void forceReenableScreen() {
1264 // We shouldn't get here at all if mPreventScreenOn is false, since
1265 // we should have already removed any existing
1266 // mForceReenableScreenTask messages...
1267 if (!mPreventScreenOn) {
1268 Log.w(TAG, "forceReenableScreen: mPreventScreenOn is false, nothing to do");
1269 return;
1270 }
1271
1272 // Uh oh. It's been 5 seconds since a call to
1273 // preventScreenOn(true) and we haven't re-enabled the screen yet.
1274 // This means the app that called preventScreenOn(true) is either
1275 // slow (i.e. it took more than 5 seconds to call preventScreenOn(false)),
1276 // or buggy (i.e. it forgot to call preventScreenOn(false), or
1277 // crashed before doing so.)
1278
1279 // Log a warning, and forcibly turn the screen back on.
1280 Log.w(TAG, "App called preventScreenOn(true) but didn't promptly reenable the screen! "
1281 + "Forcing the screen back on...");
1282 preventScreenOn(false);
1283 }
1284
1285 private Runnable mForceReenableScreenTask = new Runnable() {
1286 public void run() {
1287 forceReenableScreen();
1288 }
1289 };
1290
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001291 private int setScreenStateLocked(boolean on) {
1292 int err = Power.setScreenState(on);
Mike Lockwood6eb14c32009-10-24 19:43:38 -04001293 if (err == 0 && !mHasHardwareAutoBrightness) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001294 enableLightSensor(on && mAutoBrightessEnabled);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001295 if (!on) {
1296 // make sure button and key backlights are off too
1297 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_BUTTONS, 0);
1298 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_KEYBOARD, 0);
Mike Lockwood6c97fca2009-10-20 08:10:00 -04001299 // clear current value so we will update based on the new conditions
1300 // when the sensor is reenabled.
1301 mLightSensorValue = -1;
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001302 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001303 }
1304 return err;
1305 }
1306
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001307 private void setPowerState(int state)
1308 {
1309 setPowerState(state, false, false);
1310 }
1311
1312 private void setPowerState(int newState, boolean noChangeLights, boolean becauseOfUser)
1313 {
1314 synchronized (mLocks) {
1315 int err;
1316
1317 if (mSpew) {
1318 Log.d(TAG, "setPowerState: mPowerState=0x" + Integer.toHexString(mPowerState)
1319 + " newState=0x" + Integer.toHexString(newState)
1320 + " noChangeLights=" + noChangeLights);
1321 }
1322
1323 if (noChangeLights) {
1324 newState = (newState & ~LIGHTS_MASK) | (mPowerState & LIGHTS_MASK);
1325 }
Mike Lockwood36fc3022009-08-25 16:49:06 -07001326 if (mProximitySensorActive) {
1327 // don't turn on the screen when the proximity sensor lock is held
1328 newState = (newState & ~SCREEN_BRIGHT);
1329 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001330
1331 if (batteryIsLow()) {
1332 newState |= BATTERY_LOW_BIT;
1333 } else {
1334 newState &= ~BATTERY_LOW_BIT;
1335 }
1336 if (newState == mPowerState) {
1337 return;
1338 }
Mike Lockwood3333fa42009-10-26 14:50:42 -04001339
1340 if (!mDoneBooting && !(mAutoBrightessEnabled && !mHasHardwareAutoBrightness)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001341 newState |= ALL_BRIGHT;
1342 }
1343
1344 boolean oldScreenOn = (mPowerState & SCREEN_ON_BIT) != 0;
1345 boolean newScreenOn = (newState & SCREEN_ON_BIT) != 0;
1346
1347 if (mSpew) {
1348 Log.d(TAG, "setPowerState: mPowerState=" + mPowerState
1349 + " newState=" + newState + " noChangeLights=" + noChangeLights);
1350 Log.d(TAG, " oldKeyboardBright=" + ((mPowerState & KEYBOARD_BRIGHT_BIT) != 0)
1351 + " newKeyboardBright=" + ((newState & KEYBOARD_BRIGHT_BIT) != 0));
1352 Log.d(TAG, " oldScreenBright=" + ((mPowerState & SCREEN_BRIGHT_BIT) != 0)
1353 + " newScreenBright=" + ((newState & SCREEN_BRIGHT_BIT) != 0));
1354 Log.d(TAG, " oldButtonBright=" + ((mPowerState & BUTTON_BRIGHT_BIT) != 0)
1355 + " newButtonBright=" + ((newState & BUTTON_BRIGHT_BIT) != 0));
1356 Log.d(TAG, " oldScreenOn=" + oldScreenOn
1357 + " newScreenOn=" + newScreenOn);
1358 Log.d(TAG, " oldBatteryLow=" + ((mPowerState & BATTERY_LOW_BIT) != 0)
1359 + " newBatteryLow=" + ((newState & BATTERY_LOW_BIT) != 0));
1360 }
1361
1362 if (mPowerState != newState) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001363 updateLightsLocked(newState, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001364 mPowerState = (mPowerState & ~LIGHTS_MASK) | (newState & LIGHTS_MASK);
1365 }
1366
1367 if (oldScreenOn != newScreenOn) {
1368 if (newScreenOn) {
Joe Onorato128e7292009-03-24 18:41:31 -07001369 // When the user presses the power button, we need to always send out the
1370 // notification that it's going to sleep so the keyguard goes on. But
1371 // we can't do that until the screen fades out, so we don't show the keyguard
1372 // too early.
1373 if (mStillNeedSleepNotification) {
1374 sendNotificationLocked(false, WindowManagerPolicy.OFF_BECAUSE_OF_USER);
1375 }
1376
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001377 // Turn on the screen UNLESS there was a prior
1378 // preventScreenOn(true) request. (Note that the lifetime
1379 // of a single preventScreenOn() request is limited to 5
1380 // seconds to prevent a buggy app from disabling the
1381 // screen forever; see forceReenableScreen().)
1382 boolean reallyTurnScreenOn = true;
1383 if (mSpew) {
1384 Log.d(TAG, "- turning screen on... mPreventScreenOn = "
1385 + mPreventScreenOn);
1386 }
1387
1388 if (mPreventScreenOn) {
1389 if (mSpew) {
1390 Log.d(TAG, "- PREVENTING screen from really turning on!");
1391 }
1392 reallyTurnScreenOn = false;
1393 }
1394 if (reallyTurnScreenOn) {
Mike Lockwoodf003c0c2009-10-21 16:03:18 -04001395 mAnimatingScreenOff = false;
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001396 err = setScreenStateLocked(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001397 long identity = Binder.clearCallingIdentity();
1398 try {
Dianne Hackborn617f8772009-03-31 15:04:46 -07001399 mBatteryStats.noteScreenBrightness(
1400 getPreferredBrightness());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001401 mBatteryStats.noteScreenOn();
1402 } catch (RemoteException e) {
1403 Log.w(TAG, "RemoteException calling noteScreenOn on BatteryStatsService", e);
1404 } finally {
1405 Binder.restoreCallingIdentity(identity);
1406 }
1407 } else {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001408 setScreenStateLocked(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001409 // But continue as if we really did turn the screen on...
1410 err = 0;
1411 }
1412
1413 mScreenOnStartTime = SystemClock.elapsedRealtime();
1414 mLastTouchDown = 0;
1415 mTotalTouchDownTime = 0;
1416 mTouchCycles = 0;
1417 EventLog.writeEvent(LOG_POWER_SCREEN_STATE, 1, becauseOfUser ? 1 : 0,
1418 mTotalTouchDownTime, mTouchCycles);
1419 if (err == 0) {
1420 mPowerState |= SCREEN_ON_BIT;
1421 sendNotificationLocked(true, -1);
1422 }
1423 } else {
1424 mScreenOffTime = SystemClock.elapsedRealtime();
1425 long identity = Binder.clearCallingIdentity();
1426 try {
1427 mBatteryStats.noteScreenOff();
1428 } catch (RemoteException e) {
1429 Log.w(TAG, "RemoteException calling noteScreenOff on BatteryStatsService", e);
1430 } finally {
1431 Binder.restoreCallingIdentity(identity);
1432 }
1433 mPowerState &= ~SCREEN_ON_BIT;
1434 if (!mScreenBrightness.animating) {
Joe Onorato128e7292009-03-24 18:41:31 -07001435 err = screenOffFinishedAnimatingLocked(becauseOfUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001436 } else {
Mike Lockwoodf003c0c2009-10-21 16:03:18 -04001437 mAnimatingScreenOff = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001438 mOffBecauseOfUser = becauseOfUser;
1439 err = 0;
1440 mLastTouchDown = 0;
1441 }
1442 }
1443 }
1444 }
1445 }
1446
Joe Onorato128e7292009-03-24 18:41:31 -07001447 private int screenOffFinishedAnimatingLocked(boolean becauseOfUser) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001448 // I don't think we need to check the current state here because all of these
1449 // Power.setScreenState and sendNotificationLocked can both handle being
1450 // called multiple times in the same state. -joeo
1451 EventLog.writeEvent(LOG_POWER_SCREEN_STATE, 0, becauseOfUser ? 1 : 0,
1452 mTotalTouchDownTime, mTouchCycles);
1453 mLastTouchDown = 0;
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001454 int err = setScreenStateLocked(false);
Mike Lockwoodf003c0c2009-10-21 16:03:18 -04001455 mAnimatingScreenOff = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001456 if (mScreenOnStartTime != 0) {
1457 mScreenOnTime += SystemClock.elapsedRealtime() - mScreenOnStartTime;
1458 mScreenOnStartTime = 0;
1459 }
1460 if (err == 0) {
1461 int why = becauseOfUser
1462 ? WindowManagerPolicy.OFF_BECAUSE_OF_USER
1463 : WindowManagerPolicy.OFF_BECAUSE_OF_TIMEOUT;
1464 sendNotificationLocked(false, why);
1465 }
1466 return err;
1467 }
1468
1469 private boolean batteryIsLow() {
1470 return (!mIsPowered &&
1471 mBatteryService.getBatteryLevel() <= Power.LOW_BATTERY_THRESHOLD);
1472 }
1473
The Android Open Source Project10592532009-03-18 17:39:46 -07001474 private void updateLightsLocked(int newState, int forceState) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001475 final int oldState = mPowerState;
1476 final int realDifference = (newState ^ oldState);
1477 final int difference = realDifference | forceState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001478 if (difference == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001479 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001480 }
1481
1482 int offMask = 0;
1483 int dimMask = 0;
1484 int onMask = 0;
1485
1486 int preferredBrightness = getPreferredBrightness();
1487 boolean startAnimation = false;
1488
1489 if ((difference & KEYBOARD_BRIGHT_BIT) != 0) {
1490 if (ANIMATE_KEYBOARD_LIGHTS) {
1491 if ((newState & KEYBOARD_BRIGHT_BIT) == 0) {
1492 mKeyboardBrightness.setTargetLocked(Power.BRIGHTNESS_OFF,
Joe Onorato128e7292009-03-24 18:41:31 -07001493 ANIM_STEPS, INITIAL_KEYBOARD_BRIGHTNESS,
1494 preferredBrightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001495 } else {
1496 mKeyboardBrightness.setTargetLocked(preferredBrightness,
Joe Onorato128e7292009-03-24 18:41:31 -07001497 ANIM_STEPS, INITIAL_KEYBOARD_BRIGHTNESS,
1498 Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001499 }
1500 startAnimation = true;
1501 } else {
1502 if ((newState & KEYBOARD_BRIGHT_BIT) == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001503 offMask |= KEYBOARD_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001504 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001505 onMask |= KEYBOARD_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001506 }
1507 }
1508 }
1509
1510 if ((difference & BUTTON_BRIGHT_BIT) != 0) {
1511 if (ANIMATE_BUTTON_LIGHTS) {
1512 if ((newState & BUTTON_BRIGHT_BIT) == 0) {
1513 mButtonBrightness.setTargetLocked(Power.BRIGHTNESS_OFF,
Joe Onorato128e7292009-03-24 18:41:31 -07001514 ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
1515 preferredBrightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001516 } else {
1517 mButtonBrightness.setTargetLocked(preferredBrightness,
Joe Onorato128e7292009-03-24 18:41:31 -07001518 ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
1519 Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001520 }
1521 startAnimation = true;
1522 } else {
1523 if ((newState & BUTTON_BRIGHT_BIT) == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001524 offMask |= BUTTON_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001525 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001526 onMask |= BUTTON_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001527 }
1528 }
1529 }
1530
1531 if ((difference & (SCREEN_ON_BIT | SCREEN_BRIGHT_BIT)) != 0) {
1532 if (ANIMATE_SCREEN_LIGHTS) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001533 int nominalCurrentValue = -1;
1534 // If there was an actual difference in the light state, then
1535 // figure out the "ideal" current value based on the previous
1536 // state. Otherwise, this is a change due to the brightness
1537 // override, so we want to animate from whatever the current
1538 // value is.
1539 if ((realDifference & (SCREEN_ON_BIT | SCREEN_BRIGHT_BIT)) != 0) {
1540 switch (oldState & (SCREEN_BRIGHT_BIT|SCREEN_ON_BIT)) {
1541 case SCREEN_BRIGHT_BIT | SCREEN_ON_BIT:
1542 nominalCurrentValue = preferredBrightness;
1543 break;
1544 case SCREEN_ON_BIT:
1545 nominalCurrentValue = Power.BRIGHTNESS_DIM;
1546 break;
1547 case 0:
1548 nominalCurrentValue = Power.BRIGHTNESS_OFF;
1549 break;
1550 case SCREEN_BRIGHT_BIT:
1551 default:
1552 // not possible
1553 nominalCurrentValue = (int)mScreenBrightness.curValue;
1554 break;
1555 }
Joe Onorato128e7292009-03-24 18:41:31 -07001556 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001557 int brightness = preferredBrightness;
1558 int steps = ANIM_STEPS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001559 if ((newState & SCREEN_BRIGHT_BIT) == 0) {
1560 // dim or turn off backlight, depending on if the screen is on
1561 // the scale is because the brightness ramp isn't linear and this biases
1562 // it so the later parts take longer.
1563 final float scale = 1.5f;
1564 float ratio = (((float)Power.BRIGHTNESS_DIM)/preferredBrightness);
1565 if (ratio > 1.0f) ratio = 1.0f;
1566 if ((newState & SCREEN_ON_BIT) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001567 if ((oldState & SCREEN_BRIGHT_BIT) != 0) {
1568 // was bright
1569 steps = ANIM_STEPS;
1570 } else {
1571 // was dim
1572 steps = (int)(ANIM_STEPS*ratio*scale);
1573 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001574 brightness = Power.BRIGHTNESS_OFF;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001575 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001576 if ((oldState & SCREEN_ON_BIT) != 0) {
1577 // was bright
1578 steps = (int)(ANIM_STEPS*(1.0f-ratio)*scale);
1579 } else {
1580 // was dim
1581 steps = (int)(ANIM_STEPS*ratio);
1582 }
1583 if (mStayOnConditions != 0 && mBatteryService.isPowered(mStayOnConditions)) {
1584 // If the "stay on while plugged in" option is
1585 // turned on, then the screen will often not
1586 // automatically turn off while plugged in. To
1587 // still have a sense of when it is inactive, we
1588 // will then count going dim as turning off.
1589 mScreenOffTime = SystemClock.elapsedRealtime();
1590 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001591 brightness = Power.BRIGHTNESS_DIM;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001592 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001593 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001594 long identity = Binder.clearCallingIdentity();
1595 try {
1596 mBatteryStats.noteScreenBrightness(brightness);
1597 } catch (RemoteException e) {
1598 // Nothing interesting to do.
1599 } finally {
1600 Binder.restoreCallingIdentity(identity);
1601 }
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001602 if (mScreenBrightness.setTargetLocked(brightness,
1603 steps, INITIAL_SCREEN_BRIGHTNESS, nominalCurrentValue)) {
1604 startAnimation = true;
1605 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001606 } else {
1607 if ((newState & SCREEN_BRIGHT_BIT) == 0) {
1608 // dim or turn off backlight, depending on if the screen is on
1609 if ((newState & SCREEN_ON_BIT) == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001610 offMask |= SCREEN_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001611 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001612 dimMask |= SCREEN_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001613 }
1614 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001615 onMask |= SCREEN_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001616 }
1617 }
1618 }
1619
1620 if (startAnimation) {
1621 if (mSpew) {
1622 Log.i(TAG, "Scheduling light animator!");
1623 }
1624 mHandler.removeCallbacks(mLightAnimator);
1625 mHandler.post(mLightAnimator);
1626 }
1627
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001628 if (offMask != 0) {
1629 //Log.i(TAG, "Setting brightess off: " + offMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001630 setLightBrightness(offMask, Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001631 }
1632 if (dimMask != 0) {
1633 int brightness = Power.BRIGHTNESS_DIM;
1634 if ((newState & BATTERY_LOW_BIT) != 0 &&
1635 brightness > Power.BRIGHTNESS_LOW_BATTERY) {
1636 brightness = Power.BRIGHTNESS_LOW_BATTERY;
1637 }
1638 //Log.i(TAG, "Setting brightess dim " + brightness + ": " + offMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001639 setLightBrightness(dimMask, brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001640 }
1641 if (onMask != 0) {
1642 int brightness = getPreferredBrightness();
1643 if ((newState & BATTERY_LOW_BIT) != 0 &&
1644 brightness > Power.BRIGHTNESS_LOW_BATTERY) {
1645 brightness = Power.BRIGHTNESS_LOW_BATTERY;
1646 }
1647 //Log.i(TAG, "Setting brightess on " + brightness + ": " + onMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001648 setLightBrightness(onMask, brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001649 }
The Android Open Source Project10592532009-03-18 17:39:46 -07001650 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001651
The Android Open Source Project10592532009-03-18 17:39:46 -07001652 private void setLightBrightness(int mask, int value) {
1653 if ((mask & SCREEN_BRIGHT_BIT) != 0) {
1654 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_BACKLIGHT, value);
1655 }
1656 if ((mask & BUTTON_BRIGHT_BIT) != 0) {
1657 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_BUTTONS, value);
1658 }
1659 if ((mask & KEYBOARD_BRIGHT_BIT) != 0) {
1660 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_KEYBOARD, value);
1661 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001662 }
1663
1664 class BrightnessState {
1665 final int mask;
1666
1667 boolean initialized;
1668 int targetValue;
1669 float curValue;
1670 float delta;
1671 boolean animating;
1672
1673 BrightnessState(int m) {
1674 mask = m;
1675 }
1676
1677 public void dump(PrintWriter pw, String prefix) {
1678 pw.println(prefix + "animating=" + animating
1679 + " targetValue=" + targetValue
1680 + " curValue=" + curValue
1681 + " delta=" + delta);
1682 }
1683
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001684 boolean setTargetLocked(int target, int stepsToTarget, int initialValue,
Joe Onorato128e7292009-03-24 18:41:31 -07001685 int nominalCurrentValue) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001686 if (!initialized) {
1687 initialized = true;
1688 curValue = (float)initialValue;
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001689 } else if (targetValue == target) {
1690 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001691 }
1692 targetValue = target;
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001693 delta = (targetValue -
1694 (nominalCurrentValue >= 0 ? nominalCurrentValue : curValue))
1695 / stepsToTarget;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001696 if (mSpew) {
Joe Onorato128e7292009-03-24 18:41:31 -07001697 String noticeMe = nominalCurrentValue == curValue ? "" : " ******************";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001698 Log.i(TAG, "Setting target " + mask + ": cur=" + curValue
Joe Onorato128e7292009-03-24 18:41:31 -07001699 + " target=" + targetValue + " delta=" + delta
1700 + " nominalCurrentValue=" + nominalCurrentValue
1701 + noticeMe);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001702 }
1703 animating = true;
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001704 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001705 }
1706
1707 boolean stepLocked() {
1708 if (!animating) return false;
1709 if (false && mSpew) {
1710 Log.i(TAG, "Step target " + mask + ": cur=" + curValue
1711 + " target=" + targetValue + " delta=" + delta);
1712 }
1713 curValue += delta;
1714 int curIntValue = (int)curValue;
1715 boolean more = true;
1716 if (delta == 0) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001717 curValue = curIntValue = targetValue;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001718 more = false;
1719 } else if (delta > 0) {
1720 if (curIntValue >= targetValue) {
1721 curValue = curIntValue = targetValue;
1722 more = false;
1723 }
1724 } else {
1725 if (curIntValue <= targetValue) {
1726 curValue = curIntValue = targetValue;
1727 more = false;
1728 }
1729 }
1730 //Log.i(TAG, "Animating brightess " + curIntValue + ": " + mask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001731 setLightBrightness(mask, curIntValue);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001732 animating = more;
1733 if (!more) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001734 if (mask == SCREEN_BRIGHT_BIT && curIntValue == Power.BRIGHTNESS_OFF) {
Joe Onorato128e7292009-03-24 18:41:31 -07001735 screenOffFinishedAnimatingLocked(mOffBecauseOfUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001736 }
1737 }
1738 return more;
1739 }
1740 }
1741
1742 private class LightAnimator implements Runnable {
1743 public void run() {
1744 synchronized (mLocks) {
1745 long now = SystemClock.uptimeMillis();
1746 boolean more = mScreenBrightness.stepLocked();
1747 if (mKeyboardBrightness.stepLocked()) {
1748 more = true;
1749 }
1750 if (mButtonBrightness.stepLocked()) {
1751 more = true;
1752 }
1753 if (more) {
1754 mHandler.postAtTime(mLightAnimator, now+(1000/60));
1755 }
1756 }
1757 }
1758 }
1759
1760 private int getPreferredBrightness() {
1761 try {
1762 if (mScreenBrightnessOverride >= 0) {
1763 return mScreenBrightnessOverride;
Mike Lockwood3333fa42009-10-26 14:50:42 -04001764 } else if (mLightSensorBrightness >= 0 && !mHasHardwareAutoBrightness) {
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001765 return mLightSensorBrightness;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001766 }
1767 final int brightness = Settings.System.getInt(mContext.getContentResolver(),
1768 SCREEN_BRIGHTNESS);
1769 // Don't let applications turn the screen all the way off
1770 return Math.max(brightness, Power.BRIGHTNESS_DIM);
1771 } catch (SettingNotFoundException snfe) {
1772 return Power.BRIGHTNESS_ON;
1773 }
1774 }
1775
1776 boolean screenIsOn() {
1777 synchronized (mLocks) {
1778 return (mPowerState & SCREEN_ON_BIT) != 0;
1779 }
1780 }
1781
1782 boolean screenIsBright() {
1783 synchronized (mLocks) {
1784 return (mPowerState & SCREEN_BRIGHT) == SCREEN_BRIGHT;
1785 }
1786 }
1787
Mike Lockwood200b30b2009-09-20 00:23:59 -04001788 private void forceUserActivityLocked() {
1789 boolean savedActivityAllowed = mUserActivityAllowed;
1790 mUserActivityAllowed = true;
1791 userActivity(SystemClock.uptimeMillis(), false);
1792 mUserActivityAllowed = savedActivityAllowed;
1793 }
1794
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001795 public void userActivityWithForce(long time, boolean noChangeLights, boolean force) {
1796 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1797 userActivity(time, noChangeLights, OTHER_EVENT, force);
1798 }
1799
1800 public void userActivity(long time, boolean noChangeLights) {
1801 userActivity(time, noChangeLights, OTHER_EVENT, false);
1802 }
1803
1804 public void userActivity(long time, boolean noChangeLights, int eventType) {
1805 userActivity(time, noChangeLights, eventType, false);
1806 }
1807
1808 public void userActivity(long time, boolean noChangeLights, int eventType, boolean force) {
1809 //mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1810
1811 if (((mPokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0)
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07001812 && (eventType == CHEEK_EVENT || eventType == TOUCH_EVENT)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001813 if (false) {
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07001814 Log.d(TAG, "dropping cheek or short event mPokey=0x" + Integer.toHexString(mPokey));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001815 }
1816 return;
1817 }
1818
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07001819 if (((mPokey & POKE_LOCK_IGNORE_TOUCH_AND_CHEEK_EVENTS) != 0)
1820 && (eventType == TOUCH_EVENT || eventType == TOUCH_UP_EVENT
1821 || eventType == LONG_TOUCH_EVENT || eventType == CHEEK_EVENT)) {
1822 if (false) {
1823 Log.d(TAG, "dropping touch mPokey=0x" + Integer.toHexString(mPokey));
1824 }
1825 return;
1826 }
1827
Mike Lockwoodf003c0c2009-10-21 16:03:18 -04001828 if (mAnimatingScreenOff) {
1829 return;
1830 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001831 if (false) {
1832 if (((mPokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0)) {
1833 Log.d(TAG, "userActivity !!!");//, new RuntimeException());
1834 } else {
1835 Log.d(TAG, "mPokey=0x" + Integer.toHexString(mPokey));
1836 }
1837 }
1838
1839 synchronized (mLocks) {
1840 if (mSpew) {
1841 Log.d(TAG, "userActivity mLastEventTime=" + mLastEventTime + " time=" + time
1842 + " mUserActivityAllowed=" + mUserActivityAllowed
1843 + " mUserState=0x" + Integer.toHexString(mUserState)
Mike Lockwood36fc3022009-08-25 16:49:06 -07001844 + " mWakeLockState=0x" + Integer.toHexString(mWakeLockState)
1845 + " mProximitySensorActive=" + mProximitySensorActive
1846 + " force=" + force);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001847 }
1848 if (mLastEventTime <= time || force) {
1849 mLastEventTime = time;
Mike Lockwood36fc3022009-08-25 16:49:06 -07001850 if ((mUserActivityAllowed && !mProximitySensorActive) || force) {
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001851 // Only turn on button backlights if a button was pressed
1852 // and auto brightness is disabled
Mike Lockwood3333fa42009-10-26 14:50:42 -04001853 if (eventType == BUTTON_EVENT &&
1854 !(mAutoBrightessEnabled && !mHasHardwareAutoBrightness)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001855 mUserState = (mKeyboardVisible ? ALL_BRIGHT : SCREEN_BUTTON_BRIGHT);
1856 } else {
1857 // don't clear button/keyboard backlights when the screen is touched.
1858 mUserState |= SCREEN_BRIGHT;
1859 }
1860
Dianne Hackborn617f8772009-03-31 15:04:46 -07001861 int uid = Binder.getCallingUid();
1862 long ident = Binder.clearCallingIdentity();
1863 try {
1864 mBatteryStats.noteUserActivity(uid, eventType);
1865 } catch (RemoteException e) {
1866 // Ignore
1867 } finally {
1868 Binder.restoreCallingIdentity(ident);
1869 }
1870
Michael Chane96440f2009-05-06 10:27:36 -07001871 mWakeLockState = mLocks.reactivateScreenLocksLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001872 setPowerState(mUserState | mWakeLockState, noChangeLights, true);
1873 setTimeoutLocked(time, SCREEN_BRIGHT);
1874 }
1875 }
1876 }
1877 }
1878
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001879 private int getAutoBrightnessValue(int sensorValue, int[] values) {
1880 try {
1881 int i;
1882 for (i = 0; i < mAutoBrightnessLevels.length; i++) {
1883 if (sensorValue < mAutoBrightnessLevels[i]) {
1884 break;
1885 }
1886 }
1887 return values[i];
1888 } catch (Exception e) {
1889 // guard against null pointer or index out of bounds errors
1890 Log.e(TAG, "getAutoBrightnessValue", e);
1891 return 255;
1892 }
1893 }
1894
1895 private Runnable mAutoBrightnessTask = new Runnable() {
1896 public void run() {
Mike Lockwoodfa68ab42009-10-20 11:08:49 -04001897 synchronized (mLocks) {
1898 int value = (int)mLightSensorPendingValue;
1899 if (value >= 0) {
1900 mLightSensorPendingValue = -1;
1901 lightSensorChangedLocked(value);
1902 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001903 }
1904 }
1905 };
1906
1907 private void lightSensorChangedLocked(int value) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001908 if (mDebugLightSensor) {
1909 Log.d(TAG, "lightSensorChangedLocked " + value);
1910 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001911
Mike Lockwood3333fa42009-10-26 14:50:42 -04001912 if (mHasHardwareAutoBrightness) return;
1913
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001914 if (mLightSensorValue != value) {
1915 mLightSensorValue = value;
1916 if ((mPowerState & BATTERY_LOW_BIT) == 0) {
1917 int lcdValue = getAutoBrightnessValue(value, mLcdBacklightValues);
1918 int buttonValue = getAutoBrightnessValue(value, mButtonBacklightValues);
1919 int keyboardValue = getAutoBrightnessValue(value, mKeyboardBacklightValues);
1920 mLightSensorBrightness = lcdValue;
1921
1922 if (mDebugLightSensor) {
1923 Log.d(TAG, "lcdValue " + lcdValue);
1924 Log.d(TAG, "buttonValue " + buttonValue);
1925 Log.d(TAG, "keyboardValue " + keyboardValue);
1926 }
1927
1928 if (mScreenBrightnessOverride < 0) {
1929 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_BACKLIGHT,
1930 lcdValue);
1931 }
1932 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_BUTTONS,
1933 buttonValue);
1934 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_KEYBOARD,
1935 keyboardValue);
1936
1937 // update our animation state
1938 if (ANIMATE_SCREEN_LIGHTS) {
1939 mScreenBrightness.curValue = lcdValue;
1940 mScreenBrightness.animating = false;
1941 }
1942 if (ANIMATE_BUTTON_LIGHTS) {
1943 mButtonBrightness.curValue = buttonValue;
1944 mButtonBrightness.animating = false;
1945 }
1946 if (ANIMATE_KEYBOARD_LIGHTS) {
1947 mKeyboardBrightness.curValue = keyboardValue;
1948 mKeyboardBrightness.animating = false;
1949 }
1950 }
1951 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001952 }
1953
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001954 /**
1955 * The user requested that we go to sleep (probably with the power button).
1956 * This overrides all wake locks that are held.
1957 */
1958 public void goToSleep(long time)
1959 {
1960 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1961 synchronized (mLocks) {
1962 goToSleepLocked(time);
1963 }
1964 }
1965
1966 /**
1967 * Returns the time the screen has been on since boot, in millis.
1968 * @return screen on time
1969 */
1970 public long getScreenOnTime() {
1971 synchronized (mLocks) {
1972 if (mScreenOnStartTime == 0) {
1973 return mScreenOnTime;
1974 } else {
1975 return SystemClock.elapsedRealtime() - mScreenOnStartTime + mScreenOnTime;
1976 }
1977 }
1978 }
1979
1980 private void goToSleepLocked(long time) {
1981
1982 if (mLastEventTime <= time) {
1983 mLastEventTime = time;
1984 // cancel all of the wake locks
1985 mWakeLockState = SCREEN_OFF;
1986 int N = mLocks.size();
1987 int numCleared = 0;
1988 for (int i=0; i<N; i++) {
1989 WakeLock wl = mLocks.get(i);
1990 if (isScreenLock(wl.flags)) {
1991 mLocks.get(i).activated = false;
1992 numCleared++;
1993 }
1994 }
1995 EventLog.writeEvent(LOG_POWER_SLEEP_REQUESTED, numCleared);
Joe Onorato128e7292009-03-24 18:41:31 -07001996 mStillNeedSleepNotification = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001997 mUserState = SCREEN_OFF;
1998 setPowerState(SCREEN_OFF, false, true);
1999 cancelTimerLocked();
2000 }
2001 }
2002
2003 public long timeSinceScreenOn() {
2004 synchronized (mLocks) {
2005 if ((mPowerState & SCREEN_ON_BIT) != 0) {
2006 return 0;
2007 }
2008 return SystemClock.elapsedRealtime() - mScreenOffTime;
2009 }
2010 }
2011
2012 public void setKeyboardVisibility(boolean visible) {
Mike Lockwooda625b382009-09-12 17:36:03 -07002013 synchronized (mLocks) {
2014 if (mSpew) {
2015 Log.d(TAG, "setKeyboardVisibility: " + visible);
2016 }
Mike Lockwood3c9435a2009-10-22 15:45:37 -04002017 if (mKeyboardVisible != visible) {
2018 mKeyboardVisible = visible;
2019 // don't signal user activity if the screen is off; other code
2020 // will take care of turning on due to a true change to the lid
2021 // switch and synchronized with the lock screen.
2022 if ((mPowerState & SCREEN_ON_BIT) != 0) {
2023 userActivity(SystemClock.uptimeMillis(), false, BUTTON_EVENT, true);
2024 }
Mike Lockwooda625b382009-09-12 17:36:03 -07002025 }
2026 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002027 }
2028
2029 /**
2030 * When the keyguard is up, it manages the power state, and userActivity doesn't do anything.
2031 */
2032 public void enableUserActivity(boolean enabled) {
2033 synchronized (mLocks) {
2034 mUserActivityAllowed = enabled;
2035 mLastEventTime = SystemClock.uptimeMillis(); // we might need to pass this in
2036 }
2037 }
2038
Mike Lockwooddc3494e2009-10-14 21:17:09 -07002039 private void setScreenBrightnessMode(int mode) {
2040 mAutoBrightessEnabled = (mode == SCREEN_BRIGHTNESS_MODE_AUTOMATIC);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002041 // reset computed brightness
2042 mLightSensorBrightness = -1;
Mike Lockwooddc3494e2009-10-14 21:17:09 -07002043
2044 if (mHasHardwareAutoBrightness) {
2045 // When setting auto-brightness, must reset the brightness afterwards
2046 mHardware.setAutoBrightness_UNCHECKED(mAutoBrightessEnabled);
2047 setBacklightBrightness((int)mScreenBrightness.curValue);
2048 } else {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002049 enableLightSensor(screenIsOn() && mAutoBrightessEnabled);
Mike Lockwooddc3494e2009-10-14 21:17:09 -07002050 }
2051 }
2052
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002053 /** Sets the screen off timeouts:
2054 * mKeylightDelay
2055 * mDimDelay
2056 * mScreenOffDelay
2057 * */
2058 private void setScreenOffTimeoutsLocked() {
2059 if ((mPokey & POKE_LOCK_SHORT_TIMEOUT) != 0) {
2060 mKeylightDelay = mShortKeylightDelay; // Configurable via Gservices
2061 mDimDelay = -1;
2062 mScreenOffDelay = 0;
2063 } else if ((mPokey & POKE_LOCK_MEDIUM_TIMEOUT) != 0) {
2064 mKeylightDelay = MEDIUM_KEYLIGHT_DELAY;
2065 mDimDelay = -1;
2066 mScreenOffDelay = 0;
2067 } else {
2068 int totalDelay = mTotalDelaySetting;
2069 mKeylightDelay = LONG_KEYLIGHT_DELAY;
2070 if (totalDelay < 0) {
2071 mScreenOffDelay = Integer.MAX_VALUE;
2072 } else if (mKeylightDelay < totalDelay) {
2073 // subtract the time that the keylight delay. This will give us the
2074 // remainder of the time that we need to sleep to get the accurate
2075 // screen off timeout.
2076 mScreenOffDelay = totalDelay - mKeylightDelay;
2077 } else {
2078 mScreenOffDelay = 0;
2079 }
2080 if (mDimScreen && totalDelay >= (LONG_KEYLIGHT_DELAY + LONG_DIM_TIME)) {
2081 mDimDelay = mScreenOffDelay - LONG_DIM_TIME;
2082 mScreenOffDelay = LONG_DIM_TIME;
2083 } else {
2084 mDimDelay = -1;
2085 }
2086 }
2087 if (mSpew) {
2088 Log.d(TAG, "setScreenOffTimeouts mKeylightDelay=" + mKeylightDelay
2089 + " mDimDelay=" + mDimDelay + " mScreenOffDelay=" + mScreenOffDelay
2090 + " mDimScreen=" + mDimScreen);
2091 }
2092 }
2093
2094 /**
2095 * Refreshes cached Gservices settings. Called once on startup, and
2096 * on subsequent Settings.Gservices.CHANGED_ACTION broadcasts (see
2097 * GservicesChangedReceiver).
2098 */
2099 private void updateGservicesValues() {
2100 mShortKeylightDelay = Settings.Gservices.getInt(
2101 mContext.getContentResolver(),
2102 Settings.Gservices.SHORT_KEYLIGHT_DELAY_MS,
2103 SHORT_KEYLIGHT_DELAY_DEFAULT);
2104 // Log.i(TAG, "updateGservicesValues(): mShortKeylightDelay now " + mShortKeylightDelay);
2105 }
2106
2107 /**
2108 * Receiver for the Gservices.CHANGED_ACTION broadcast intent,
2109 * which tells us we need to refresh our cached Gservices settings.
2110 */
2111 private class GservicesChangedReceiver extends BroadcastReceiver {
2112 @Override
2113 public void onReceive(Context context, Intent intent) {
2114 // Log.i(TAG, "GservicesChangedReceiver.onReceive(): " + intent);
2115 updateGservicesValues();
2116 }
2117 }
2118
2119 private class LockList extends ArrayList<WakeLock>
2120 {
2121 void addLock(WakeLock wl)
2122 {
2123 int index = getIndex(wl.binder);
2124 if (index < 0) {
2125 this.add(wl);
2126 }
2127 }
2128
2129 WakeLock removeLock(IBinder binder)
2130 {
2131 int index = getIndex(binder);
2132 if (index >= 0) {
2133 return this.remove(index);
2134 } else {
2135 return null;
2136 }
2137 }
2138
2139 int getIndex(IBinder binder)
2140 {
2141 int N = this.size();
2142 for (int i=0; i<N; i++) {
2143 if (this.get(i).binder == binder) {
2144 return i;
2145 }
2146 }
2147 return -1;
2148 }
2149
2150 int gatherState()
2151 {
2152 int result = 0;
2153 int N = this.size();
2154 for (int i=0; i<N; i++) {
2155 WakeLock wl = this.get(i);
2156 if (wl.activated) {
2157 if (isScreenLock(wl.flags)) {
2158 result |= wl.minState;
2159 }
2160 }
2161 }
2162 return result;
2163 }
Michael Chane96440f2009-05-06 10:27:36 -07002164
2165 int reactivateScreenLocksLocked()
2166 {
2167 int result = 0;
2168 int N = this.size();
2169 for (int i=0; i<N; i++) {
2170 WakeLock wl = this.get(i);
2171 if (isScreenLock(wl.flags)) {
2172 wl.activated = true;
2173 result |= wl.minState;
2174 }
2175 }
2176 return result;
2177 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002178 }
2179
2180 void setPolicy(WindowManagerPolicy p) {
2181 synchronized (mLocks) {
2182 mPolicy = p;
2183 mLocks.notifyAll();
2184 }
2185 }
2186
2187 WindowManagerPolicy getPolicyLocked() {
2188 while (mPolicy == null || !mDoneBooting) {
2189 try {
2190 mLocks.wait();
2191 } catch (InterruptedException e) {
2192 // Ignore
2193 }
2194 }
2195 return mPolicy;
2196 }
2197
2198 void systemReady() {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002199 mSensorManager = new SensorManager(mHandlerThread.getLooper());
2200 mProximitySensor = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
2201 // don't bother with the light sensor if auto brightness is handled in hardware
2202 if (!mHasHardwareAutoBrightness) {
2203 mLightSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
2204 enableLightSensor(mAutoBrightessEnabled);
2205 }
2206
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002207 synchronized (mLocks) {
2208 Log.d(TAG, "system ready!");
2209 mDoneBooting = true;
Dianne Hackborn617f8772009-03-31 15:04:46 -07002210 long identity = Binder.clearCallingIdentity();
2211 try {
2212 mBatteryStats.noteScreenBrightness(getPreferredBrightness());
2213 mBatteryStats.noteScreenOn();
2214 } catch (RemoteException e) {
2215 // Nothing interesting to do.
2216 } finally {
2217 Binder.restoreCallingIdentity(identity);
2218 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002219 userActivity(SystemClock.uptimeMillis(), false, BUTTON_EVENT, true);
2220 updateWakeLockLocked();
2221 mLocks.notifyAll();
2222 }
2223 }
2224
2225 public void monitor() {
2226 synchronized (mLocks) { }
2227 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002228
2229 public int getSupportedWakeLockFlags() {
2230 int result = PowerManager.PARTIAL_WAKE_LOCK
2231 | PowerManager.FULL_WAKE_LOCK
2232 | PowerManager.SCREEN_DIM_WAKE_LOCK;
2233
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002234 if (mProximitySensor != null) {
2235 result |= PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK;
2236 }
2237
2238 return result;
2239 }
2240
Mike Lockwood237a2992009-09-15 14:42:16 -04002241 public void setBacklightBrightness(int brightness) {
2242 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
2243 // Don't let applications turn the screen all the way off
2244 brightness = Math.max(brightness, Power.BRIGHTNESS_DIM);
2245 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_BACKLIGHT, brightness);
2246 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_KEYBOARD, brightness);
2247 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_BUTTONS, brightness);
2248 long identity = Binder.clearCallingIdentity();
2249 try {
2250 mBatteryStats.noteScreenBrightness(brightness);
2251 } catch (RemoteException e) {
2252 Log.w(TAG, "RemoteException calling noteScreenBrightness on BatteryStatsService", e);
2253 } finally {
2254 Binder.restoreCallingIdentity(identity);
2255 }
2256
2257 // update our animation state
2258 if (ANIMATE_SCREEN_LIGHTS) {
2259 mScreenBrightness.curValue = brightness;
2260 mScreenBrightness.animating = false;
2261 }
2262 if (ANIMATE_KEYBOARD_LIGHTS) {
2263 mKeyboardBrightness.curValue = brightness;
2264 mKeyboardBrightness.animating = false;
2265 }
2266 if (ANIMATE_BUTTON_LIGHTS) {
2267 mButtonBrightness.curValue = brightness;
2268 mButtonBrightness.animating = false;
2269 }
2270 }
2271
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002272 private void enableProximityLockLocked() {
Mike Lockwood36fc3022009-08-25 16:49:06 -07002273 if (mSpew) {
2274 Log.d(TAG, "enableProximityLockLocked");
2275 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002276 mSensorManager.registerListener(mProximityListener, mProximitySensor,
2277 SensorManager.SENSOR_DELAY_NORMAL);
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002278 }
2279
2280 private void disableProximityLockLocked() {
Mike Lockwood36fc3022009-08-25 16:49:06 -07002281 if (mSpew) {
2282 Log.d(TAG, "disableProximityLockLocked");
2283 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002284 mSensorManager.unregisterListener(mProximityListener);
Mike Lockwood200b30b2009-09-20 00:23:59 -04002285 synchronized (mLocks) {
2286 if (mProximitySensorActive) {
2287 mProximitySensorActive = false;
2288 forceUserActivityLocked();
2289 }
2290 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002291 }
2292
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002293 private void enableLightSensor(boolean enable) {
2294 if (mDebugLightSensor) {
2295 Log.d(TAG, "enableLightSensor " + enable);
2296 }
2297 if (mSensorManager != null && mLightSensorEnabled != enable) {
2298 mLightSensorEnabled = enable;
2299 if (enable) {
2300 mSensorManager.registerListener(mLightListener, mLightSensor,
2301 SensorManager.SENSOR_DELAY_NORMAL);
Mike Lockwood36fc3022009-08-25 16:49:06 -07002302 } else {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002303 mSensorManager.unregisterListener(mLightListener);
Mike Lockwood6c97fca2009-10-20 08:10:00 -04002304 mHandler.removeCallbacks(mAutoBrightnessTask);
Mike Lockwood06952d92009-08-13 16:05:38 -04002305 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002306 }
2307 }
2308
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002309 SensorEventListener mProximityListener = new SensorEventListener() {
2310 public void onSensorChanged(SensorEvent event) {
2311 long milliseconds = event.timestamp / 1000000;
2312 synchronized (mLocks) {
2313 float distance = event.values[0];
2314 // compare against getMaximumRange to support sensors that only return 0 or 1
2315 if (distance >= 0.0 && distance < PROXIMITY_THRESHOLD &&
2316 distance < mProximitySensor.getMaximumRange()) {
2317 if (mSpew) {
2318 Log.d(TAG, "onSensorChanged: proximity active, distance: " + distance);
2319 }
2320 goToSleepLocked(milliseconds);
2321 mProximitySensorActive = true;
2322 } else {
2323 // proximity sensor negative events trigger as user activity.
2324 // temporarily set mUserActivityAllowed to true so this will work
2325 // even when the keyguard is on.
2326 if (mSpew) {
2327 Log.d(TAG, "onSensorChanged: proximity inactive, distance: " + distance);
2328 }
2329 mProximitySensorActive = false;
2330 forceUserActivityLocked();
2331 }
2332 }
2333 }
2334
2335 public void onAccuracyChanged(Sensor sensor, int accuracy) {
2336 // ignore
2337 }
2338 };
2339
2340 SensorEventListener mLightListener = new SensorEventListener() {
2341 public void onSensorChanged(SensorEvent event) {
2342 synchronized (mLocks) {
2343 int value = (int)event.values[0];
2344 if (mDebugLightSensor) {
2345 Log.d(TAG, "onSensorChanged: light value: " + value);
2346 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002347 mHandler.removeCallbacks(mAutoBrightnessTask);
2348 if (mLightSensorValue != value) {
Mike Lockwood6c97fca2009-10-20 08:10:00 -04002349 if (mLightSensorValue == -1) {
2350 // process the value immediately
2351 lightSensorChangedLocked(value);
2352 } else {
2353 // delay processing to debounce the sensor
2354 mLightSensorPendingValue = value;
2355 mHandler.postDelayed(mAutoBrightnessTask, LIGHT_SENSOR_DELAY);
2356 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002357 } else {
2358 mLightSensorPendingValue = -1;
2359 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002360 }
2361 }
2362
2363 public void onAccuracyChanged(Sensor sensor, int accuracy) {
2364 // ignore
2365 }
2366 };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002367}