blob: 8584d74e3590097ea6c3aff226e1d24f01ca1194 [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;
Doug Zongker50a21f42009-11-19 12:49:53 -080062import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080063import java.io.PrintWriter;
64import java.util.ArrayList;
65import java.util.HashMap;
66import java.util.Observable;
67import java.util.Observer;
68
Mike Lockwoodbc706a02009-07-27 13:50:57 -070069class PowerManagerService extends IPowerManager.Stub
Mike Lockwood8738e0c2009-10-04 08:44:47 -040070 implements LocalPowerManager, Watchdog.Monitor {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080071
72 private static final String TAG = "PowerManagerService";
73 static final String PARTIAL_NAME = "PowerManagerService";
74
75 private static final boolean LOG_PARTIAL_WL = false;
76
77 // Indicates whether touch-down cycles should be logged as part of the
78 // LOG_POWER_SCREEN_STATE log events
79 private static final boolean LOG_TOUCH_DOWNS = true;
80
81 private static final int LOCK_MASK = PowerManager.PARTIAL_WAKE_LOCK
82 | PowerManager.SCREEN_DIM_WAKE_LOCK
83 | PowerManager.SCREEN_BRIGHT_WAKE_LOCK
Mike Lockwoodbc706a02009-07-27 13:50:57 -070084 | PowerManager.FULL_WAKE_LOCK
85 | PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080086
87 // time since last state: time since last event:
88 // The short keylight delay comes from Gservices; this is the default.
89 private static final int SHORT_KEYLIGHT_DELAY_DEFAULT = 6000; // t+6 sec
90 private static final int MEDIUM_KEYLIGHT_DELAY = 15000; // t+15 sec
91 private static final int LONG_KEYLIGHT_DELAY = 6000; // t+6 sec
92 private static final int LONG_DIM_TIME = 7000; // t+N-5 sec
93
Mike Lockwoodd7786b42009-10-15 17:09:16 -070094 // How long to wait to debounce light sensor changes.
Mike Lockwood9b8136922009-11-06 15:53:59 -050095 private static final int LIGHT_SENSOR_DELAY = 2000;
Mike Lockwoodd7786b42009-10-15 17:09:16 -070096
Mike Lockwood20f87d72009-11-05 16:08:51 -050097 // For debouncing the proximity sensor.
98 private static final int PROXIMITY_SENSOR_DELAY = 1000;
99
Mike Lockwoodd20ea362009-09-15 00:13:38 -0400100 // trigger proximity if distance is less than 5 cm
101 private static final float PROXIMITY_THRESHOLD = 5.0f;
102
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800103 // Cached Gservices settings; see updateGservicesValues()
104 private int mShortKeylightDelay = SHORT_KEYLIGHT_DELAY_DEFAULT;
105
106 // flags for setPowerState
107 private static final int SCREEN_ON_BIT = 0x00000001;
108 private static final int SCREEN_BRIGHT_BIT = 0x00000002;
109 private static final int BUTTON_BRIGHT_BIT = 0x00000004;
110 private static final int KEYBOARD_BRIGHT_BIT = 0x00000008;
111 private static final int BATTERY_LOW_BIT = 0x00000010;
112
113 // values for setPowerState
114
115 // SCREEN_OFF == everything off
116 private static final int SCREEN_OFF = 0x00000000;
117
118 // SCREEN_DIM == screen on, screen backlight dim
119 private static final int SCREEN_DIM = SCREEN_ON_BIT;
120
121 // SCREEN_BRIGHT == screen on, screen backlight bright
122 private static final int SCREEN_BRIGHT = SCREEN_ON_BIT | SCREEN_BRIGHT_BIT;
123
124 // SCREEN_BUTTON_BRIGHT == screen on, screen and button backlights bright
125 private static final int SCREEN_BUTTON_BRIGHT = SCREEN_BRIGHT | BUTTON_BRIGHT_BIT;
126
127 // SCREEN_BUTTON_BRIGHT == screen on, screen, button and keyboard backlights bright
128 private static final int ALL_BRIGHT = SCREEN_BUTTON_BRIGHT | KEYBOARD_BRIGHT_BIT;
129
130 // used for noChangeLights in setPowerState()
131 private static final int LIGHTS_MASK = SCREEN_BRIGHT_BIT | BUTTON_BRIGHT_BIT | KEYBOARD_BRIGHT_BIT;
132
133 static final boolean ANIMATE_SCREEN_LIGHTS = true;
134 static final boolean ANIMATE_BUTTON_LIGHTS = false;
135 static final boolean ANIMATE_KEYBOARD_LIGHTS = false;
136
137 static final int ANIM_STEPS = 60/4;
Mike Lockwooddd9668e2009-10-27 15:47:02 -0400138 // Slower animation for autobrightness changes
139 static final int AUTOBRIGHTNESS_ANIM_STEPS = 60;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800140
141 // These magic numbers are the initial state of the LEDs at boot. Ideally
142 // we should read them from the driver, but our current hardware returns 0
143 // for the initial value. Oops!
144 static final int INITIAL_SCREEN_BRIGHTNESS = 255;
145 static final int INITIAL_BUTTON_BRIGHTNESS = Power.BRIGHTNESS_OFF;
146 static final int INITIAL_KEYBOARD_BRIGHTNESS = Power.BRIGHTNESS_OFF;
147
148 static final int LOG_POWER_SLEEP_REQUESTED = 2724;
149 static final int LOG_POWER_SCREEN_BROADCAST_SEND = 2725;
150 static final int LOG_POWER_SCREEN_BROADCAST_DONE = 2726;
151 static final int LOG_POWER_SCREEN_BROADCAST_STOP = 2727;
152 static final int LOG_POWER_SCREEN_STATE = 2728;
153 static final int LOG_POWER_PARTIAL_WAKE_STATE = 2729;
154
155 private final int MY_UID;
156
157 private boolean mDoneBooting = false;
Mike Lockwood2d7bb812009-11-15 18:12:22 -0500158 private boolean mBootCompleted = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800159 private int mStayOnConditions = 0;
Joe Onorato128e7292009-03-24 18:41:31 -0700160 private int[] mBroadcastQueue = new int[] { -1, -1, -1 };
161 private int[] mBroadcastWhy = new int[3];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800162 private int mPartialCount = 0;
163 private int mPowerState;
164 private boolean mOffBecauseOfUser;
165 private int mUserState;
166 private boolean mKeyboardVisible = false;
167 private boolean mUserActivityAllowed = true;
Mike Lockwoodee2b0942009-11-09 14:09:02 -0500168 private int mProximityWakeLockCount = 0;
169 private boolean mProximitySensorEnabled = false;
Mike Lockwood36fc3022009-08-25 16:49:06 -0700170 private boolean mProximitySensorActive = false;
Mike Lockwood20f87d72009-11-05 16:08:51 -0500171 private int mProximityPendingValue = -1; // -1 == nothing, 0 == inactive, 1 == active
172 private long mLastProximityEventTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800173 private int mTotalDelaySetting;
174 private int mKeylightDelay;
175 private int mDimDelay;
176 private int mScreenOffDelay;
177 private int mWakeLockState;
178 private long mLastEventTime = 0;
179 private long mScreenOffTime;
180 private volatile WindowManagerPolicy mPolicy;
181 private final LockList mLocks = new LockList();
182 private Intent mScreenOffIntent;
183 private Intent mScreenOnIntent;
Mike Lockwood3a322132009-11-24 00:30:52 -0500184 private LightsService mLightsService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800185 private Context mContext;
Mike Lockwood3cb67a32009-11-27 14:25:58 -0500186 private LightsService.Light mLcdLight;
187 private LightsService.Light mButtonLight;
188 private LightsService.Light mKeyboardLight;
189 private LightsService.Light mAttentionLight;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800190 private UnsynchronizedWakeLock mBroadcastWakeLock;
191 private UnsynchronizedWakeLock mStayOnWhilePluggedInScreenDimLock;
192 private UnsynchronizedWakeLock mStayOnWhilePluggedInPartialLock;
193 private UnsynchronizedWakeLock mPreventScreenOnPartialLock;
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500194 private UnsynchronizedWakeLock mProximityPartialLock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800195 private HandlerThread mHandlerThread;
196 private Handler mHandler;
197 private TimeoutTask mTimeoutTask = new TimeoutTask();
198 private LightAnimator mLightAnimator = new LightAnimator();
199 private final BrightnessState mScreenBrightness
The Android Open Source Project10592532009-03-18 17:39:46 -0700200 = new BrightnessState(SCREEN_BRIGHT_BIT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800201 private final BrightnessState mKeyboardBrightness
The Android Open Source Project10592532009-03-18 17:39:46 -0700202 = new BrightnessState(KEYBOARD_BRIGHT_BIT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800203 private final BrightnessState mButtonBrightness
The Android Open Source Project10592532009-03-18 17:39:46 -0700204 = new BrightnessState(BUTTON_BRIGHT_BIT);
Joe Onorato128e7292009-03-24 18:41:31 -0700205 private boolean mStillNeedSleepNotification;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800206 private boolean mIsPowered = false;
207 private IActivityManager mActivityService;
208 private IBatteryStats mBatteryStats;
209 private BatteryService mBatteryService;
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700210 private SensorManager mSensorManager;
211 private Sensor mProximitySensor;
Mike Lockwood8738e0c2009-10-04 08:44:47 -0400212 private Sensor mLightSensor;
213 private boolean mLightSensorEnabled;
214 private float mLightSensorValue = -1;
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700215 private float mLightSensorPendingValue = -1;
Mike Lockwoodfb73f792009-11-20 11:31:18 -0500216 private int mLightSensorScreenBrightness = -1;
217 private int mLightSensorButtonBrightness = -1;
218 private int mLightSensorKeyboardBrightness = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800219 private boolean mDimScreen = true;
220 private long mNextTimeout;
221 private volatile int mPokey = 0;
222 private volatile boolean mPokeAwakeOnSet = false;
223 private volatile boolean mInitComplete = false;
224 private HashMap<IBinder,PokeLock> mPokeLocks = new HashMap<IBinder,PokeLock>();
Mike Lockwood20ee6f22009-11-07 20:33:47 -0500225 // mLastScreenOnTime is the time the screen was last turned on
226 private long mLastScreenOnTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800227 private boolean mPreventScreenOn;
228 private int mScreenBrightnessOverride = -1;
Mike Lockwoodfb73f792009-11-20 11:31:18 -0500229 private int mButtonBrightnessOverride = -1;
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400230 private boolean mUseSoftwareAutoBrightness;
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700231 private boolean mAutoBrightessEnabled;
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700232 private int[] mAutoBrightnessLevels;
233 private int[] mLcdBacklightValues;
234 private int[] mButtonBacklightValues;
235 private int[] mKeyboardBacklightValues;
Mike Lockwood20ee6f22009-11-07 20:33:47 -0500236 private int mLightSensorWarmupTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800237
238 // Used when logging number and duration of touch-down cycles
239 private long mTotalTouchDownTime;
240 private long mLastTouchDown;
241 private int mTouchCycles;
242
243 // could be either static or controllable at runtime
244 private static final boolean mSpew = false;
Mike Lockwoodee2b0942009-11-09 14:09:02 -0500245 private static final boolean mDebugProximitySensor = (true || mSpew);
Mike Lockwooddd9668e2009-10-27 15:47:02 -0400246 private static final boolean mDebugLightSensor = (false || mSpew);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800247
248 /*
249 static PrintStream mLog;
250 static {
251 try {
252 mLog = new PrintStream("/data/power.log");
253 }
254 catch (FileNotFoundException e) {
255 android.util.Log.e(TAG, "Life is hard", e);
256 }
257 }
258 static class Log {
259 static void d(String tag, String s) {
260 mLog.println(s);
261 android.util.Log.d(tag, s);
262 }
263 static void i(String tag, String s) {
264 mLog.println(s);
265 android.util.Log.i(tag, s);
266 }
267 static void w(String tag, String s) {
268 mLog.println(s);
269 android.util.Log.w(tag, s);
270 }
271 static void e(String tag, String s) {
272 mLog.println(s);
273 android.util.Log.e(tag, s);
274 }
275 }
276 */
277
278 /**
279 * This class works around a deadlock between the lock in PowerManager.WakeLock
280 * and our synchronizing on mLocks. PowerManager.WakeLock synchronizes on its
281 * mToken object so it can be accessed from any thread, but it calls into here
282 * with its lock held. This class is essentially a reimplementation of
283 * PowerManager.WakeLock, but without that extra synchronized block, because we'll
284 * only call it with our own locks held.
285 */
286 private class UnsynchronizedWakeLock {
287 int mFlags;
288 String mTag;
289 IBinder mToken;
290 int mCount = 0;
291 boolean mRefCounted;
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500292 boolean mHeld;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800293
294 UnsynchronizedWakeLock(int flags, String tag, boolean refCounted) {
295 mFlags = flags;
296 mTag = tag;
297 mToken = new Binder();
298 mRefCounted = refCounted;
299 }
300
301 public void acquire() {
302 if (!mRefCounted || mCount++ == 0) {
303 long ident = Binder.clearCallingIdentity();
304 try {
305 PowerManagerService.this.acquireWakeLockLocked(mFlags, mToken,
306 MY_UID, mTag);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500307 mHeld = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800308 } finally {
309 Binder.restoreCallingIdentity(ident);
310 }
311 }
312 }
313
314 public void release() {
315 if (!mRefCounted || --mCount == 0) {
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500316 PowerManagerService.this.releaseWakeLockLocked(mToken, 0, false);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500317 mHeld = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800318 }
319 if (mCount < 0) {
320 throw new RuntimeException("WakeLock under-locked " + mTag);
321 }
322 }
323
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500324 public boolean isHeld()
325 {
326 return mHeld;
327 }
328
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800329 public String toString() {
330 return "UnsynchronizedWakeLock(mFlags=0x" + Integer.toHexString(mFlags)
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500331 + " mCount=" + mCount + " mHeld=" + mHeld + ")";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800332 }
333 }
334
335 private final class BatteryReceiver extends BroadcastReceiver {
336 @Override
337 public void onReceive(Context context, Intent intent) {
338 synchronized (mLocks) {
339 boolean wasPowered = mIsPowered;
340 mIsPowered = mBatteryService.isPowered();
341
342 if (mIsPowered != wasPowered) {
343 // update mStayOnWhilePluggedIn wake lock
344 updateWakeLockLocked();
345
346 // treat plugging and unplugging the devices as a user activity.
347 // users find it disconcerting when they unplug the device
348 // and it shuts off right away.
349 // temporarily set mUserActivityAllowed to true so this will work
350 // even when the keyguard is on.
351 synchronized (mLocks) {
Mike Lockwood200b30b2009-09-20 00:23:59 -0400352 forceUserActivityLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800353 }
354 }
355 }
356 }
357 }
358
Mike Lockwood2d7bb812009-11-15 18:12:22 -0500359 private final class BootCompletedReceiver extends BroadcastReceiver {
360 @Override
361 public void onReceive(Context context, Intent intent) {
362 bootCompleted();
363 }
364 }
365
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800366 /**
367 * Set the setting that determines whether the device stays on when plugged in.
368 * The argument is a bit string, with each bit specifying a power source that,
369 * when the device is connected to that source, causes the device to stay on.
370 * See {@link android.os.BatteryManager} for the list of power sources that
371 * can be specified. Current values include {@link android.os.BatteryManager#BATTERY_PLUGGED_AC}
372 * and {@link android.os.BatteryManager#BATTERY_PLUGGED_USB}
373 * @param val an {@code int} containing the bits that specify which power sources
374 * should cause the device to stay on.
375 */
376 public void setStayOnSetting(int val) {
377 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SETTINGS, null);
378 Settings.System.putInt(mContext.getContentResolver(),
379 Settings.System.STAY_ON_WHILE_PLUGGED_IN, val);
380 }
381
382 private class SettingsObserver implements Observer {
383 private int getInt(String name) {
384 return mSettings.getValues(name).getAsInteger(Settings.System.VALUE);
385 }
386
387 public void update(Observable o, Object arg) {
388 synchronized (mLocks) {
389 // STAY_ON_WHILE_PLUGGED_IN
390 mStayOnConditions = getInt(STAY_ON_WHILE_PLUGGED_IN);
391 updateWakeLockLocked();
392
393 // SCREEN_OFF_TIMEOUT
394 mTotalDelaySetting = getInt(SCREEN_OFF_TIMEOUT);
395
396 // DIM_SCREEN
397 //mDimScreen = getInt(DIM_SCREEN) != 0;
398
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700399 // SCREEN_BRIGHTNESS_MODE
400 setScreenBrightnessMode(getInt(SCREEN_BRIGHTNESS_MODE));
401
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800402 // recalculate everything
403 setScreenOffTimeoutsLocked();
404 }
405 }
406 }
407
408 PowerManagerService()
409 {
410 // Hack to get our uid... should have a func for this.
411 long token = Binder.clearCallingIdentity();
412 MY_UID = Binder.getCallingUid();
413 Binder.restoreCallingIdentity(token);
414
415 // XXX remove this when the kernel doesn't timeout wake locks
416 Power.setLastUserActivityTimeout(7*24*3600*1000); // one week
417
418 // assume nothing is on yet
419 mUserState = mPowerState = 0;
420
421 // Add ourself to the Watchdog monitors.
422 Watchdog.getInstance().addMonitor(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800423 }
424
425 private ContentQueryMap mSettings;
426
Mike Lockwood3a322132009-11-24 00:30:52 -0500427 void init(Context context, LightsService lights, IActivityManager activity,
The Android Open Source Project10592532009-03-18 17:39:46 -0700428 BatteryService battery) {
Mike Lockwood3a322132009-11-24 00:30:52 -0500429 mLightsService = lights;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800430 mContext = context;
431 mActivityService = activity;
432 mBatteryStats = BatteryStatsService.getService();
433 mBatteryService = battery;
434
Mike Lockwood3cb67a32009-11-27 14:25:58 -0500435 mLcdLight = lights.getLight(LightsService.LIGHT_ID_BACKLIGHT);
436 mButtonLight = lights.getLight(LightsService.LIGHT_ID_BUTTONS);
437 mKeyboardLight = lights.getLight(LightsService.LIGHT_ID_KEYBOARD);
438 mAttentionLight = lights.getLight(LightsService.LIGHT_ID_ATTENTION);
439
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800440 mHandlerThread = new HandlerThread("PowerManagerService") {
441 @Override
442 protected void onLooperPrepared() {
443 super.onLooperPrepared();
444 initInThread();
445 }
446 };
447 mHandlerThread.start();
448
449 synchronized (mHandlerThread) {
450 while (!mInitComplete) {
451 try {
452 mHandlerThread.wait();
453 } catch (InterruptedException e) {
454 // Ignore
455 }
456 }
457 }
458 }
459
460 void initInThread() {
461 mHandler = new Handler();
462
463 mBroadcastWakeLock = new UnsynchronizedWakeLock(
Joe Onorato128e7292009-03-24 18:41:31 -0700464 PowerManager.PARTIAL_WAKE_LOCK, "sleep_broadcast", true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800465 mStayOnWhilePluggedInScreenDimLock = new UnsynchronizedWakeLock(
466 PowerManager.SCREEN_DIM_WAKE_LOCK, "StayOnWhilePluggedIn Screen Dim", false);
467 mStayOnWhilePluggedInPartialLock = new UnsynchronizedWakeLock(
468 PowerManager.PARTIAL_WAKE_LOCK, "StayOnWhilePluggedIn Partial", false);
469 mPreventScreenOnPartialLock = new UnsynchronizedWakeLock(
470 PowerManager.PARTIAL_WAKE_LOCK, "PreventScreenOn Partial", false);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500471 mProximityPartialLock = new UnsynchronizedWakeLock(
472 PowerManager.PARTIAL_WAKE_LOCK, "Proximity Partial", false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800473
474 mScreenOnIntent = new Intent(Intent.ACTION_SCREEN_ON);
475 mScreenOnIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
476 mScreenOffIntent = new Intent(Intent.ACTION_SCREEN_OFF);
477 mScreenOffIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
478
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700479 Resources resources = mContext.getResources();
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400480
481 // read settings for auto-brightness
482 mUseSoftwareAutoBrightness = resources.getBoolean(
483 com.android.internal.R.bool.config_automatic_brightness_available);
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400484 if (mUseSoftwareAutoBrightness) {
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700485 mAutoBrightnessLevels = resources.getIntArray(
486 com.android.internal.R.array.config_autoBrightnessLevels);
487 mLcdBacklightValues = resources.getIntArray(
488 com.android.internal.R.array.config_autoBrightnessLcdBacklightValues);
489 mButtonBacklightValues = resources.getIntArray(
490 com.android.internal.R.array.config_autoBrightnessButtonBacklightValues);
491 mKeyboardBacklightValues = resources.getIntArray(
492 com.android.internal.R.array.config_autoBrightnessKeyboardBacklightValues);
Mike Lockwood20ee6f22009-11-07 20:33:47 -0500493 mLightSensorWarmupTime = resources.getInteger(
494 com.android.internal.R.integer.config_lightSensorWarmupTime);
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700495 }
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700496
497 ContentResolver resolver = mContext.getContentResolver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800498 Cursor settingsCursor = resolver.query(Settings.System.CONTENT_URI, null,
499 "(" + Settings.System.NAME + "=?) or ("
500 + Settings.System.NAME + "=?) or ("
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700501 + Settings.System.NAME + "=?) or ("
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800502 + Settings.System.NAME + "=?)",
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700503 new String[]{STAY_ON_WHILE_PLUGGED_IN, SCREEN_OFF_TIMEOUT, DIM_SCREEN,
504 SCREEN_BRIGHTNESS_MODE},
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800505 null);
506 mSettings = new ContentQueryMap(settingsCursor, Settings.System.NAME, true, mHandler);
507 SettingsObserver settingsObserver = new SettingsObserver();
508 mSettings.addObserver(settingsObserver);
509
510 // pretend that the settings changed so we will get their initial state
511 settingsObserver.update(mSettings, null);
512
513 // register for the battery changed notifications
514 IntentFilter filter = new IntentFilter();
515 filter.addAction(Intent.ACTION_BATTERY_CHANGED);
516 mContext.registerReceiver(new BatteryReceiver(), filter);
Mike Lockwood2d7bb812009-11-15 18:12:22 -0500517 filter = new IntentFilter();
518 filter.addAction(Intent.ACTION_BOOT_COMPLETED);
519 mContext.registerReceiver(new BootCompletedReceiver(), filter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800520
521 // Listen for Gservices changes
522 IntentFilter gservicesChangedFilter =
523 new IntentFilter(Settings.Gservices.CHANGED_ACTION);
524 mContext.registerReceiver(new GservicesChangedReceiver(), gservicesChangedFilter);
525 // And explicitly do the initial update of our cached settings
526 updateGservicesValues();
527
Mike Lockwood4984e732009-11-01 08:16:33 -0500528 if (mUseSoftwareAutoBrightness) {
Mike Lockwood6c97fca2009-10-20 08:10:00 -0400529 // turn the screen on
530 setPowerState(SCREEN_BRIGHT);
531 } else {
532 // turn everything on
533 setPowerState(ALL_BRIGHT);
534 }
Dan Murphy951764b2009-08-27 14:59:03 -0500535
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800536 synchronized (mHandlerThread) {
537 mInitComplete = true;
538 mHandlerThread.notifyAll();
539 }
540 }
541
542 private class WakeLock implements IBinder.DeathRecipient
543 {
544 WakeLock(int f, IBinder b, String t, int u) {
545 super();
546 flags = f;
547 binder = b;
548 tag = t;
549 uid = u == MY_UID ? Process.SYSTEM_UID : u;
550 if (u != MY_UID || (
551 !"KEEP_SCREEN_ON_FLAG".equals(tag)
552 && !"KeyInputQueue".equals(tag))) {
553 monitorType = (f & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK
554 ? BatteryStats.WAKE_TYPE_PARTIAL
555 : BatteryStats.WAKE_TYPE_FULL;
556 } else {
557 monitorType = -1;
558 }
559 try {
560 b.linkToDeath(this, 0);
561 } catch (RemoteException e) {
562 binderDied();
563 }
564 }
565 public void binderDied() {
566 synchronized (mLocks) {
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500567 releaseWakeLockLocked(this.binder, 0, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800568 }
569 }
570 final int flags;
571 final IBinder binder;
572 final String tag;
573 final int uid;
574 final int monitorType;
575 boolean activated = true;
576 int minState;
577 }
578
579 private void updateWakeLockLocked() {
580 if (mStayOnConditions != 0 && mBatteryService.isPowered(mStayOnConditions)) {
581 // keep the device on if we're plugged in and mStayOnWhilePluggedIn is set.
582 mStayOnWhilePluggedInScreenDimLock.acquire();
583 mStayOnWhilePluggedInPartialLock.acquire();
584 } else {
585 mStayOnWhilePluggedInScreenDimLock.release();
586 mStayOnWhilePluggedInPartialLock.release();
587 }
588 }
589
590 private boolean isScreenLock(int flags)
591 {
592 int n = flags & LOCK_MASK;
593 return n == PowerManager.FULL_WAKE_LOCK
594 || n == PowerManager.SCREEN_BRIGHT_WAKE_LOCK
595 || n == PowerManager.SCREEN_DIM_WAKE_LOCK;
596 }
597
598 public void acquireWakeLock(int flags, IBinder lock, String tag) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800599 int uid = Binder.getCallingUid();
Michael Chane96440f2009-05-06 10:27:36 -0700600 if (uid != Process.myUid()) {
601 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
602 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800603 long ident = Binder.clearCallingIdentity();
604 try {
605 synchronized (mLocks) {
606 acquireWakeLockLocked(flags, lock, uid, tag);
607 }
608 } finally {
609 Binder.restoreCallingIdentity(ident);
610 }
611 }
612
613 public void acquireWakeLockLocked(int flags, IBinder lock, int uid, String tag) {
614 int acquireUid = -1;
615 String acquireName = null;
616 int acquireType = -1;
617
618 if (mSpew) {
619 Log.d(TAG, "acquireWakeLock flags=0x" + Integer.toHexString(flags) + " tag=" + tag);
620 }
621
622 int index = mLocks.getIndex(lock);
623 WakeLock wl;
624 boolean newlock;
625 if (index < 0) {
626 wl = new WakeLock(flags, lock, tag, uid);
627 switch (wl.flags & LOCK_MASK)
628 {
629 case PowerManager.FULL_WAKE_LOCK:
Mike Lockwood4984e732009-11-01 08:16:33 -0500630 if (mUseSoftwareAutoBrightness) {
Mike Lockwood3333fa42009-10-26 14:50:42 -0400631 wl.minState = SCREEN_BRIGHT;
632 } else {
633 wl.minState = (mKeyboardVisible ? ALL_BRIGHT : SCREEN_BUTTON_BRIGHT);
634 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800635 break;
636 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
637 wl.minState = SCREEN_BRIGHT;
638 break;
639 case PowerManager.SCREEN_DIM_WAKE_LOCK:
640 wl.minState = SCREEN_DIM;
641 break;
642 case PowerManager.PARTIAL_WAKE_LOCK:
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700643 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800644 break;
645 default:
646 // just log and bail. we're in the server, so don't
647 // throw an exception.
648 Log.e(TAG, "bad wakelock type for lock '" + tag + "' "
649 + " flags=" + flags);
650 return;
651 }
652 mLocks.addLock(wl);
653 newlock = true;
654 } else {
655 wl = mLocks.get(index);
656 newlock = false;
657 }
658 if (isScreenLock(flags)) {
659 // if this causes a wakeup, we reactivate all of the locks and
660 // set it to whatever they want. otherwise, we modulate that
661 // by the current state so we never turn it more on than
662 // it already is.
663 if ((wl.flags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) {
Michael Chane96440f2009-05-06 10:27:36 -0700664 int oldWakeLockState = mWakeLockState;
665 mWakeLockState = mLocks.reactivateScreenLocksLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800666 if (mSpew) {
667 Log.d(TAG, "wakeup here mUserState=0x" + Integer.toHexString(mUserState)
Michael Chane96440f2009-05-06 10:27:36 -0700668 + " mWakeLockState=0x"
669 + Integer.toHexString(mWakeLockState)
670 + " previous wakeLockState=0x" + Integer.toHexString(oldWakeLockState));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800671 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800672 } else {
673 if (mSpew) {
674 Log.d(TAG, "here mUserState=0x" + Integer.toHexString(mUserState)
675 + " mLocks.gatherState()=0x"
676 + Integer.toHexString(mLocks.gatherState())
677 + " mWakeLockState=0x" + Integer.toHexString(mWakeLockState));
678 }
679 mWakeLockState = (mUserState | mWakeLockState) & mLocks.gatherState();
680 }
681 setPowerState(mWakeLockState | mUserState);
682 }
683 else if ((flags & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK) {
684 if (newlock) {
685 mPartialCount++;
686 if (mPartialCount == 1) {
687 if (LOG_PARTIAL_WL) EventLog.writeEvent(LOG_POWER_PARTIAL_WAKE_STATE, 1, tag);
688 }
689 }
690 Power.acquireWakeLock(Power.PARTIAL_WAKE_LOCK,PARTIAL_NAME);
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700691 } else if ((flags & LOCK_MASK) == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK) {
Mike Lockwoodee2b0942009-11-09 14:09:02 -0500692 mProximityWakeLockCount++;
693 if (mProximityWakeLockCount == 1) {
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700694 enableProximityLockLocked();
695 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800696 }
697 if (newlock) {
698 acquireUid = wl.uid;
699 acquireName = wl.tag;
700 acquireType = wl.monitorType;
701 }
702
703 if (acquireType >= 0) {
704 try {
705 mBatteryStats.noteStartWakelock(acquireUid, acquireName, acquireType);
706 } catch (RemoteException e) {
707 // Ignore
708 }
709 }
710 }
711
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500712 public void releaseWakeLock(IBinder lock, int flags) {
Michael Chane96440f2009-05-06 10:27:36 -0700713 int uid = Binder.getCallingUid();
714 if (uid != Process.myUid()) {
715 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
716 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800717
718 synchronized (mLocks) {
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500719 releaseWakeLockLocked(lock, flags, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800720 }
721 }
722
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500723 private void releaseWakeLockLocked(IBinder lock, int flags, boolean death) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800724 int releaseUid;
725 String releaseName;
726 int releaseType;
727
728 WakeLock wl = mLocks.removeLock(lock);
729 if (wl == null) {
730 return;
731 }
732
733 if (mSpew) {
734 Log.d(TAG, "releaseWakeLock flags=0x"
735 + Integer.toHexString(wl.flags) + " tag=" + wl.tag);
736 }
737
738 if (isScreenLock(wl.flags)) {
739 mWakeLockState = mLocks.gatherState();
740 // goes in the middle to reduce flicker
741 if ((wl.flags & PowerManager.ON_AFTER_RELEASE) != 0) {
742 userActivity(SystemClock.uptimeMillis(), false);
743 }
744 setPowerState(mWakeLockState | mUserState);
745 }
746 else if ((wl.flags & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK) {
747 mPartialCount--;
748 if (mPartialCount == 0) {
749 if (LOG_PARTIAL_WL) EventLog.writeEvent(LOG_POWER_PARTIAL_WAKE_STATE, 0, wl.tag);
750 Power.releaseWakeLock(PARTIAL_NAME);
751 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700752 } else if ((wl.flags & LOCK_MASK) == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK) {
Mike Lockwoodee2b0942009-11-09 14:09:02 -0500753 mProximityWakeLockCount--;
754 if (mProximityWakeLockCount == 0) {
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500755 if (mProximitySensorActive &&
756 ((flags & PowerManager.WAIT_FOR_PROXIMITY_NEGATIVE) != 0)) {
Mike Lockwoodee2b0942009-11-09 14:09:02 -0500757 // wait for proximity sensor to go negative before disabling sensor
758 if (mDebugProximitySensor) {
759 Log.d(TAG, "waiting for proximity sensor to go negative");
760 }
761 } else {
762 disableProximityLockLocked();
763 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700764 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800765 }
766 // Unlink the lock from the binder.
767 wl.binder.unlinkToDeath(wl, 0);
768 releaseUid = wl.uid;
769 releaseName = wl.tag;
770 releaseType = wl.monitorType;
771
772 if (releaseType >= 0) {
773 long origId = Binder.clearCallingIdentity();
774 try {
775 mBatteryStats.noteStopWakelock(releaseUid, releaseName, releaseType);
776 } catch (RemoteException e) {
777 // Ignore
778 } finally {
779 Binder.restoreCallingIdentity(origId);
780 }
781 }
782 }
783
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800784 private class PokeLock implements IBinder.DeathRecipient
785 {
786 PokeLock(int p, IBinder b, String t) {
787 super();
788 this.pokey = p;
789 this.binder = b;
790 this.tag = t;
791 try {
792 b.linkToDeath(this, 0);
793 } catch (RemoteException e) {
794 binderDied();
795 }
796 }
797 public void binderDied() {
798 setPokeLock(0, this.binder, this.tag);
799 }
800 int pokey;
801 IBinder binder;
802 String tag;
803 boolean awakeOnSet;
804 }
805
806 public void setPokeLock(int pokey, IBinder token, String tag) {
807 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
808 if (token == null) {
809 Log.e(TAG, "setPokeLock got null token for tag='" + tag + "'");
810 return;
811 }
812
813 if ((pokey & POKE_LOCK_TIMEOUT_MASK) == POKE_LOCK_TIMEOUT_MASK) {
814 throw new IllegalArgumentException("setPokeLock can't have both POKE_LOCK_SHORT_TIMEOUT"
815 + " and POKE_LOCK_MEDIUM_TIMEOUT");
816 }
817
818 synchronized (mLocks) {
819 if (pokey != 0) {
820 PokeLock p = mPokeLocks.get(token);
821 int oldPokey = 0;
822 if (p != null) {
823 oldPokey = p.pokey;
824 p.pokey = pokey;
825 } else {
826 p = new PokeLock(pokey, token, tag);
827 mPokeLocks.put(token, p);
828 }
829 int oldTimeout = oldPokey & POKE_LOCK_TIMEOUT_MASK;
830 int newTimeout = pokey & POKE_LOCK_TIMEOUT_MASK;
831 if (((mPowerState & SCREEN_ON_BIT) == 0) && (oldTimeout != newTimeout)) {
832 p.awakeOnSet = true;
833 }
834 } else {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -0700835 PokeLock rLock = mPokeLocks.remove(token);
836 if (rLock != null) {
837 token.unlinkToDeath(rLock, 0);
838 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800839 }
840
841 int oldPokey = mPokey;
842 int cumulative = 0;
843 boolean oldAwakeOnSet = mPokeAwakeOnSet;
844 boolean awakeOnSet = false;
845 for (PokeLock p: mPokeLocks.values()) {
846 cumulative |= p.pokey;
847 if (p.awakeOnSet) {
848 awakeOnSet = true;
849 }
850 }
851 mPokey = cumulative;
852 mPokeAwakeOnSet = awakeOnSet;
853
854 int oldCumulativeTimeout = oldPokey & POKE_LOCK_TIMEOUT_MASK;
855 int newCumulativeTimeout = pokey & POKE_LOCK_TIMEOUT_MASK;
856
857 if (oldCumulativeTimeout != newCumulativeTimeout) {
858 setScreenOffTimeoutsLocked();
859 // reset the countdown timer, but use the existing nextState so it doesn't
860 // change anything
861 setTimeoutLocked(SystemClock.uptimeMillis(), mTimeoutTask.nextState);
862 }
863 }
864 }
865
866 private static String lockType(int type)
867 {
868 switch (type)
869 {
870 case PowerManager.FULL_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -0700871 return "FULL_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800872 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -0700873 return "SCREEN_BRIGHT_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800874 case PowerManager.SCREEN_DIM_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -0700875 return "SCREEN_DIM_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800876 case PowerManager.PARTIAL_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -0700877 return "PARTIAL_WAKE_LOCK ";
878 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
879 return "PROXIMITY_SCREEN_OFF_WAKE_LOCK";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800880 default:
David Brown251faa62009-08-02 22:04:36 -0700881 return "??? ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800882 }
883 }
884
885 private static String dumpPowerState(int state) {
886 return (((state & KEYBOARD_BRIGHT_BIT) != 0)
887 ? "KEYBOARD_BRIGHT_BIT " : "")
888 + (((state & SCREEN_BRIGHT_BIT) != 0)
889 ? "SCREEN_BRIGHT_BIT " : "")
890 + (((state & SCREEN_ON_BIT) != 0)
891 ? "SCREEN_ON_BIT " : "")
892 + (((state & BATTERY_LOW_BIT) != 0)
893 ? "BATTERY_LOW_BIT " : "");
894 }
895
896 @Override
897 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
898 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
899 != PackageManager.PERMISSION_GRANTED) {
900 pw.println("Permission Denial: can't dump PowerManager from from pid="
901 + Binder.getCallingPid()
902 + ", uid=" + Binder.getCallingUid());
903 return;
904 }
905
906 long now = SystemClock.uptimeMillis();
907
908 pw.println("Power Manager State:");
909 pw.println(" mIsPowered=" + mIsPowered
910 + " mPowerState=" + mPowerState
911 + " mScreenOffTime=" + (SystemClock.elapsedRealtime()-mScreenOffTime)
912 + " ms");
913 pw.println(" mPartialCount=" + mPartialCount);
914 pw.println(" mWakeLockState=" + dumpPowerState(mWakeLockState));
915 pw.println(" mUserState=" + dumpPowerState(mUserState));
916 pw.println(" mPowerState=" + dumpPowerState(mPowerState));
917 pw.println(" mLocks.gather=" + dumpPowerState(mLocks.gatherState()));
918 pw.println(" mNextTimeout=" + mNextTimeout + " now=" + now
919 + " " + ((mNextTimeout-now)/1000) + "s from now");
920 pw.println(" mDimScreen=" + mDimScreen
921 + " mStayOnConditions=" + mStayOnConditions);
922 pw.println(" mOffBecauseOfUser=" + mOffBecauseOfUser
923 + " mUserState=" + mUserState);
Joe Onorato128e7292009-03-24 18:41:31 -0700924 pw.println(" mBroadcastQueue={" + mBroadcastQueue[0] + ',' + mBroadcastQueue[1]
925 + ',' + mBroadcastQueue[2] + "}");
926 pw.println(" mBroadcastWhy={" + mBroadcastWhy[0] + ',' + mBroadcastWhy[1]
927 + ',' + mBroadcastWhy[2] + "}");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800928 pw.println(" mPokey=" + mPokey + " mPokeAwakeonSet=" + mPokeAwakeOnSet);
929 pw.println(" mKeyboardVisible=" + mKeyboardVisible
930 + " mUserActivityAllowed=" + mUserActivityAllowed);
931 pw.println(" mKeylightDelay=" + mKeylightDelay + " mDimDelay=" + mDimDelay
932 + " mScreenOffDelay=" + mScreenOffDelay);
933 pw.println(" mPreventScreenOn=" + mPreventScreenOn
Mike Lockwoodfb73f792009-11-20 11:31:18 -0500934 + " mScreenBrightnessOverride=" + mScreenBrightnessOverride
935 + " mButtonBrightnessOverride=" + mButtonBrightnessOverride);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800936 pw.println(" mTotalDelaySetting=" + mTotalDelaySetting);
Mike Lockwood20ee6f22009-11-07 20:33:47 -0500937 pw.println(" mLastScreenOnTime=" + mLastScreenOnTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800938 pw.println(" mBroadcastWakeLock=" + mBroadcastWakeLock);
939 pw.println(" mStayOnWhilePluggedInScreenDimLock=" + mStayOnWhilePluggedInScreenDimLock);
940 pw.println(" mStayOnWhilePluggedInPartialLock=" + mStayOnWhilePluggedInPartialLock);
941 pw.println(" mPreventScreenOnPartialLock=" + mPreventScreenOnPartialLock);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500942 pw.println(" mProximityPartialLock=" + mProximityPartialLock);
Mike Lockwoodee2b0942009-11-09 14:09:02 -0500943 pw.println(" mProximityWakeLockCount=" + mProximityWakeLockCount);
944 pw.println(" mProximitySensorEnabled=" + mProximitySensorEnabled);
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700945 pw.println(" mProximitySensorActive=" + mProximitySensorActive);
Mike Lockwood20f87d72009-11-05 16:08:51 -0500946 pw.println(" mProximityPendingValue=" + mProximityPendingValue);
947 pw.println(" mLastProximityEventTime=" + mLastProximityEventTime);
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700948 pw.println(" mLightSensorEnabled=" + mLightSensorEnabled);
Mike Lockwoodfb73f792009-11-20 11:31:18 -0500949 pw.println(" mLightSensorValue=" + mLightSensorValue
950 + " mLightSensorPendingValue=" + mLightSensorPendingValue);
951 pw.println(" mLightSensorScreenBrightness=" + mLightSensorScreenBrightness
952 + " mLightSensorButtonBrightness=" + mLightSensorButtonBrightness
953 + " mLightSensorKeyboardBrightness=" + mLightSensorKeyboardBrightness);
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400954 pw.println(" mUseSoftwareAutoBrightness=" + mUseSoftwareAutoBrightness);
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700955 pw.println(" mAutoBrightessEnabled=" + mAutoBrightessEnabled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800956 mScreenBrightness.dump(pw, " mScreenBrightness: ");
957 mKeyboardBrightness.dump(pw, " mKeyboardBrightness: ");
958 mButtonBrightness.dump(pw, " mButtonBrightness: ");
959
960 int N = mLocks.size();
961 pw.println();
962 pw.println("mLocks.size=" + N + ":");
963 for (int i=0; i<N; i++) {
964 WakeLock wl = mLocks.get(i);
965 String type = lockType(wl.flags & LOCK_MASK);
966 String acquireCausesWakeup = "";
967 if ((wl.flags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) {
968 acquireCausesWakeup = "ACQUIRE_CAUSES_WAKEUP ";
969 }
970 String activated = "";
971 if (wl.activated) {
972 activated = " activated";
973 }
974 pw.println(" " + type + " '" + wl.tag + "'" + acquireCausesWakeup
975 + activated + " (minState=" + wl.minState + ")");
976 }
977
978 pw.println();
979 pw.println("mPokeLocks.size=" + mPokeLocks.size() + ":");
980 for (PokeLock p: mPokeLocks.values()) {
981 pw.println(" poke lock '" + p.tag + "':"
982 + ((p.pokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0
983 ? " POKE_LOCK_IGNORE_CHEEK_EVENTS" : "")
Joe Onoratoe68ffcb2009-03-24 19:11:13 -0700984 + ((p.pokey & POKE_LOCK_IGNORE_TOUCH_AND_CHEEK_EVENTS) != 0
985 ? " POKE_LOCK_IGNORE_TOUCH_AND_CHEEK_EVENTS" : "")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800986 + ((p.pokey & POKE_LOCK_SHORT_TIMEOUT) != 0
987 ? " POKE_LOCK_SHORT_TIMEOUT" : "")
988 + ((p.pokey & POKE_LOCK_MEDIUM_TIMEOUT) != 0
989 ? " POKE_LOCK_MEDIUM_TIMEOUT" : ""));
990 }
991
992 pw.println();
993 }
994
995 private void setTimeoutLocked(long now, int nextState)
996 {
Mike Lockwood2d7bb812009-11-15 18:12:22 -0500997 if (mBootCompleted) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800998 mHandler.removeCallbacks(mTimeoutTask);
999 mTimeoutTask.nextState = nextState;
1000 long when = now;
1001 switch (nextState)
1002 {
1003 case SCREEN_BRIGHT:
1004 when += mKeylightDelay;
1005 break;
1006 case SCREEN_DIM:
1007 if (mDimDelay >= 0) {
1008 when += mDimDelay;
1009 break;
1010 } else {
1011 Log.w(TAG, "mDimDelay=" + mDimDelay + " while trying to dim");
1012 }
1013 case SCREEN_OFF:
1014 synchronized (mLocks) {
1015 when += mScreenOffDelay;
1016 }
1017 break;
1018 }
1019 if (mSpew) {
1020 Log.d(TAG, "setTimeoutLocked now=" + now + " nextState=" + nextState
1021 + " when=" + when);
1022 }
1023 mHandler.postAtTime(mTimeoutTask, when);
1024 mNextTimeout = when; // for debugging
1025 }
1026 }
1027
1028 private void cancelTimerLocked()
1029 {
1030 mHandler.removeCallbacks(mTimeoutTask);
1031 mTimeoutTask.nextState = -1;
1032 }
1033
1034 private class TimeoutTask implements Runnable
1035 {
1036 int nextState; // access should be synchronized on mLocks
1037 public void run()
1038 {
1039 synchronized (mLocks) {
1040 if (mSpew) {
1041 Log.d(TAG, "user activity timeout timed out nextState=" + this.nextState);
1042 }
1043
1044 if (nextState == -1) {
1045 return;
1046 }
1047
1048 mUserState = this.nextState;
1049 setPowerState(this.nextState | mWakeLockState);
1050
1051 long now = SystemClock.uptimeMillis();
1052
1053 switch (this.nextState)
1054 {
1055 case SCREEN_BRIGHT:
1056 if (mDimDelay >= 0) {
1057 setTimeoutLocked(now, SCREEN_DIM);
1058 break;
1059 }
1060 case SCREEN_DIM:
1061 setTimeoutLocked(now, SCREEN_OFF);
1062 break;
1063 }
1064 }
1065 }
1066 }
1067
1068 private void sendNotificationLocked(boolean on, int why)
1069 {
Joe Onorato64c62ba2009-03-24 20:13:57 -07001070 if (!on) {
1071 mStillNeedSleepNotification = false;
1072 }
1073
Joe Onorato128e7292009-03-24 18:41:31 -07001074 // Add to the queue.
1075 int index = 0;
1076 while (mBroadcastQueue[index] != -1) {
1077 index++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001078 }
Joe Onorato128e7292009-03-24 18:41:31 -07001079 mBroadcastQueue[index] = on ? 1 : 0;
1080 mBroadcastWhy[index] = why;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001081
Joe Onorato128e7292009-03-24 18:41:31 -07001082 // If we added it position 2, then there is a pair that can be stripped.
1083 // If we added it position 1 and we're turning the screen off, we can strip
1084 // the pair and do nothing, because the screen is already off, and therefore
1085 // keyguard has already been enabled.
1086 // However, if we added it at position 1 and we're turning it on, then position
1087 // 0 was to turn it off, and we can't strip that, because keyguard needs to come
1088 // on, so have to run the queue then.
1089 if (index == 2) {
1090 // Also, while we're collapsing them, if it's going to be an "off," and one
1091 // is off because of user, then use that, regardless of whether it's the first
1092 // or second one.
1093 if (!on && why == WindowManagerPolicy.OFF_BECAUSE_OF_USER) {
1094 mBroadcastWhy[0] = WindowManagerPolicy.OFF_BECAUSE_OF_USER;
1095 }
1096 mBroadcastQueue[0] = on ? 1 : 0;
1097 mBroadcastQueue[1] = -1;
1098 mBroadcastQueue[2] = -1;
1099 index = 0;
1100 }
1101 if (index == 1 && !on) {
1102 mBroadcastQueue[0] = -1;
1103 mBroadcastQueue[1] = -1;
1104 index = -1;
1105 // The wake lock was being held, but we're not actually going to do any
1106 // broadcasts, so release the wake lock.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001107 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_STOP, 1, mBroadcastWakeLock.mCount);
1108 mBroadcastWakeLock.release();
Joe Onorato128e7292009-03-24 18:41:31 -07001109 }
1110
1111 // Now send the message.
1112 if (index >= 0) {
1113 // Acquire the broadcast wake lock before changing the power
1114 // state. It will be release after the broadcast is sent.
1115 // We always increment the ref count for each notification in the queue
1116 // and always decrement when that notification is handled.
1117 mBroadcastWakeLock.acquire();
1118 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_SEND, mBroadcastWakeLock.mCount);
1119 mHandler.post(mNotificationTask);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001120 }
1121 }
1122
1123 private Runnable mNotificationTask = new Runnable()
1124 {
1125 public void run()
1126 {
Joe Onorato128e7292009-03-24 18:41:31 -07001127 while (true) {
1128 int value;
1129 int why;
1130 WindowManagerPolicy policy;
1131 synchronized (mLocks) {
1132 value = mBroadcastQueue[0];
1133 why = mBroadcastWhy[0];
1134 for (int i=0; i<2; i++) {
1135 mBroadcastQueue[i] = mBroadcastQueue[i+1];
1136 mBroadcastWhy[i] = mBroadcastWhy[i+1];
1137 }
1138 policy = getPolicyLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001139 }
Joe Onorato128e7292009-03-24 18:41:31 -07001140 if (value == 1) {
1141 mScreenOnStart = SystemClock.uptimeMillis();
1142
1143 policy.screenTurnedOn();
1144 try {
1145 ActivityManagerNative.getDefault().wakingUp();
1146 } catch (RemoteException e) {
1147 // ignore it
1148 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001149
Joe Onorato128e7292009-03-24 18:41:31 -07001150 if (mSpew) {
1151 Log.d(TAG, "mBroadcastWakeLock=" + mBroadcastWakeLock);
1152 }
1153 if (mContext != null && ActivityManagerNative.isSystemReady()) {
1154 mContext.sendOrderedBroadcast(mScreenOnIntent, null,
1155 mScreenOnBroadcastDone, mHandler, 0, null, null);
1156 } else {
1157 synchronized (mLocks) {
1158 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_STOP, 2,
1159 mBroadcastWakeLock.mCount);
1160 mBroadcastWakeLock.release();
1161 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001162 }
1163 }
Joe Onorato128e7292009-03-24 18:41:31 -07001164 else if (value == 0) {
1165 mScreenOffStart = SystemClock.uptimeMillis();
1166
1167 policy.screenTurnedOff(why);
1168 try {
1169 ActivityManagerNative.getDefault().goingToSleep();
1170 } catch (RemoteException e) {
1171 // ignore it.
1172 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001173
Joe Onorato128e7292009-03-24 18:41:31 -07001174 if (mContext != null && ActivityManagerNative.isSystemReady()) {
1175 mContext.sendOrderedBroadcast(mScreenOffIntent, null,
1176 mScreenOffBroadcastDone, mHandler, 0, null, null);
1177 } else {
1178 synchronized (mLocks) {
1179 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_STOP, 3,
1180 mBroadcastWakeLock.mCount);
1181 mBroadcastWakeLock.release();
1182 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001183 }
1184 }
Joe Onorato128e7292009-03-24 18:41:31 -07001185 else {
1186 // If we're in this case, then this handler is running for a previous
1187 // paired transaction. mBroadcastWakeLock will already have been released.
1188 break;
1189 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001190 }
1191 }
1192 };
1193
1194 long mScreenOnStart;
1195 private BroadcastReceiver mScreenOnBroadcastDone = new BroadcastReceiver() {
1196 public void onReceive(Context context, Intent intent) {
1197 synchronized (mLocks) {
1198 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_DONE, 1,
1199 SystemClock.uptimeMillis() - mScreenOnStart, mBroadcastWakeLock.mCount);
1200 mBroadcastWakeLock.release();
1201 }
1202 }
1203 };
1204
1205 long mScreenOffStart;
1206 private BroadcastReceiver mScreenOffBroadcastDone = new BroadcastReceiver() {
1207 public void onReceive(Context context, Intent intent) {
1208 synchronized (mLocks) {
1209 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_DONE, 0,
1210 SystemClock.uptimeMillis() - mScreenOffStart, mBroadcastWakeLock.mCount);
1211 mBroadcastWakeLock.release();
1212 }
1213 }
1214 };
1215
1216 void logPointerUpEvent() {
1217 if (LOG_TOUCH_DOWNS) {
1218 mTotalTouchDownTime += SystemClock.elapsedRealtime() - mLastTouchDown;
1219 mLastTouchDown = 0;
1220 }
1221 }
1222
1223 void logPointerDownEvent() {
1224 if (LOG_TOUCH_DOWNS) {
1225 // If we are not already timing a down/up sequence
1226 if (mLastTouchDown == 0) {
1227 mLastTouchDown = SystemClock.elapsedRealtime();
1228 mTouchCycles++;
1229 }
1230 }
1231 }
1232
1233 /**
1234 * Prevents the screen from turning on even if it *should* turn on due
1235 * to a subsequent full wake lock being acquired.
1236 * <p>
1237 * This is a temporary hack that allows an activity to "cover up" any
1238 * display glitches that happen during the activity's startup
1239 * sequence. (Specifically, this API was added to work around a
1240 * cosmetic bug in the "incoming call" sequence, where the lock screen
1241 * would flicker briefly before the incoming call UI became visible.)
1242 * TODO: There ought to be a more elegant way of doing this,
1243 * probably by having the PowerManager and ActivityManager
1244 * work together to let apps specify that the screen on/off
1245 * state should be synchronized with the Activity lifecycle.
1246 * <p>
1247 * Note that calling preventScreenOn(true) will NOT turn the screen
1248 * off if it's currently on. (This API only affects *future*
1249 * acquisitions of full wake locks.)
1250 * But calling preventScreenOn(false) WILL turn the screen on if
1251 * it's currently off because of a prior preventScreenOn(true) call.
1252 * <p>
1253 * Any call to preventScreenOn(true) MUST be followed promptly by a call
1254 * to preventScreenOn(false). In fact, if the preventScreenOn(false)
1255 * call doesn't occur within 5 seconds, we'll turn the screen back on
1256 * ourselves (and log a warning about it); this prevents a buggy app
1257 * from disabling the screen forever.)
1258 * <p>
1259 * TODO: this feature should really be controlled by a new type of poke
1260 * lock (rather than an IPowerManager call).
1261 */
1262 public void preventScreenOn(boolean prevent) {
1263 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1264
1265 synchronized (mLocks) {
1266 if (prevent) {
1267 // First of all, grab a partial wake lock to
1268 // make sure the CPU stays on during the entire
1269 // preventScreenOn(true) -> preventScreenOn(false) sequence.
1270 mPreventScreenOnPartialLock.acquire();
1271
1272 // Post a forceReenableScreen() call (for 5 seconds in the
1273 // future) to make sure the matching preventScreenOn(false) call
1274 // has happened by then.
1275 mHandler.removeCallbacks(mForceReenableScreenTask);
1276 mHandler.postDelayed(mForceReenableScreenTask, 5000);
1277
1278 // Finally, set the flag that prevents the screen from turning on.
1279 // (Below, in setPowerState(), we'll check mPreventScreenOn and
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001280 // we *won't* call setScreenStateLocked(true) if it's set.)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001281 mPreventScreenOn = true;
1282 } else {
1283 // (Re)enable the screen.
1284 mPreventScreenOn = false;
1285
1286 // We're "undoing" a the prior preventScreenOn(true) call, so we
1287 // no longer need the 5-second safeguard.
1288 mHandler.removeCallbacks(mForceReenableScreenTask);
1289
1290 // Forcibly turn on the screen if it's supposed to be on. (This
1291 // handles the case where the screen is currently off because of
1292 // a prior preventScreenOn(true) call.)
Mike Lockwoode090281422009-11-14 21:02:56 -05001293 if (!mProximitySensorActive && (mPowerState & SCREEN_ON_BIT) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001294 if (mSpew) {
1295 Log.d(TAG,
1296 "preventScreenOn: turning on after a prior preventScreenOn(true)!");
1297 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001298 int err = setScreenStateLocked(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001299 if (err != 0) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001300 Log.w(TAG, "preventScreenOn: error from setScreenStateLocked(): " + err);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001301 }
1302 }
1303
1304 // Release the partial wake lock that we held during the
1305 // preventScreenOn(true) -> preventScreenOn(false) sequence.
1306 mPreventScreenOnPartialLock.release();
1307 }
1308 }
1309 }
1310
1311 public void setScreenBrightnessOverride(int brightness) {
1312 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1313
1314 synchronized (mLocks) {
1315 if (mScreenBrightnessOverride != brightness) {
1316 mScreenBrightnessOverride = brightness;
1317 updateLightsLocked(mPowerState, SCREEN_ON_BIT);
1318 }
1319 }
1320 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001321
1322 public void setButtonBrightnessOverride(int brightness) {
1323 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1324
1325 synchronized (mLocks) {
1326 if (mButtonBrightnessOverride != brightness) {
1327 mButtonBrightnessOverride = brightness;
1328 updateLightsLocked(mPowerState, BUTTON_BRIGHT_BIT | KEYBOARD_BRIGHT_BIT);
1329 }
1330 }
1331 }
1332
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001333 /**
1334 * Sanity-check that gets called 5 seconds after any call to
1335 * preventScreenOn(true). This ensures that the original call
1336 * is followed promptly by a call to preventScreenOn(false).
1337 */
1338 private void forceReenableScreen() {
1339 // We shouldn't get here at all if mPreventScreenOn is false, since
1340 // we should have already removed any existing
1341 // mForceReenableScreenTask messages...
1342 if (!mPreventScreenOn) {
1343 Log.w(TAG, "forceReenableScreen: mPreventScreenOn is false, nothing to do");
1344 return;
1345 }
1346
1347 // Uh oh. It's been 5 seconds since a call to
1348 // preventScreenOn(true) and we haven't re-enabled the screen yet.
1349 // This means the app that called preventScreenOn(true) is either
1350 // slow (i.e. it took more than 5 seconds to call preventScreenOn(false)),
1351 // or buggy (i.e. it forgot to call preventScreenOn(false), or
1352 // crashed before doing so.)
1353
1354 // Log a warning, and forcibly turn the screen back on.
1355 Log.w(TAG, "App called preventScreenOn(true) but didn't promptly reenable the screen! "
1356 + "Forcing the screen back on...");
1357 preventScreenOn(false);
1358 }
1359
1360 private Runnable mForceReenableScreenTask = new Runnable() {
1361 public void run() {
1362 forceReenableScreen();
1363 }
1364 };
1365
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001366 private int setScreenStateLocked(boolean on) {
1367 int err = Power.setScreenState(on);
Mike Lockwood20ee6f22009-11-07 20:33:47 -05001368 if (err == 0) {
1369 mLastScreenOnTime = (on ? SystemClock.elapsedRealtime() : 0);
1370 if (mUseSoftwareAutoBrightness) {
1371 enableLightSensor(on);
1372 if (!on) {
1373 // make sure button and key backlights are off too
Mike Lockwood3cb67a32009-11-27 14:25:58 -05001374 mButtonLight.turnOff();
1375 mKeyboardLight.turnOff();
Mike Lockwood20ee6f22009-11-07 20:33:47 -05001376 // clear current value so we will update based on the new conditions
1377 // when the sensor is reenabled.
1378 mLightSensorValue = -1;
1379 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001380 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001381 }
1382 return err;
1383 }
1384
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001385 private void setPowerState(int state)
1386 {
1387 setPowerState(state, false, false);
1388 }
1389
1390 private void setPowerState(int newState, boolean noChangeLights, boolean becauseOfUser)
1391 {
1392 synchronized (mLocks) {
1393 int err;
1394
1395 if (mSpew) {
1396 Log.d(TAG, "setPowerState: mPowerState=0x" + Integer.toHexString(mPowerState)
1397 + " newState=0x" + Integer.toHexString(newState)
1398 + " noChangeLights=" + noChangeLights);
1399 }
1400
1401 if (noChangeLights) {
1402 newState = (newState & ~LIGHTS_MASK) | (mPowerState & LIGHTS_MASK);
1403 }
Mike Lockwood36fc3022009-08-25 16:49:06 -07001404 if (mProximitySensorActive) {
1405 // don't turn on the screen when the proximity sensor lock is held
1406 newState = (newState & ~SCREEN_BRIGHT);
1407 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001408
1409 if (batteryIsLow()) {
1410 newState |= BATTERY_LOW_BIT;
1411 } else {
1412 newState &= ~BATTERY_LOW_BIT;
1413 }
1414 if (newState == mPowerState) {
1415 return;
1416 }
Mike Lockwood3333fa42009-10-26 14:50:42 -04001417
Mike Lockwood2d7bb812009-11-15 18:12:22 -05001418 if (!mBootCompleted && !mUseSoftwareAutoBrightness) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001419 newState |= ALL_BRIGHT;
1420 }
1421
1422 boolean oldScreenOn = (mPowerState & SCREEN_ON_BIT) != 0;
1423 boolean newScreenOn = (newState & SCREEN_ON_BIT) != 0;
1424
Mike Lockwood51b84492009-11-16 21:51:18 -05001425 if (mSpew) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001426 Log.d(TAG, "setPowerState: mPowerState=" + mPowerState
1427 + " newState=" + newState + " noChangeLights=" + noChangeLights);
1428 Log.d(TAG, " oldKeyboardBright=" + ((mPowerState & KEYBOARD_BRIGHT_BIT) != 0)
1429 + " newKeyboardBright=" + ((newState & KEYBOARD_BRIGHT_BIT) != 0));
1430 Log.d(TAG, " oldScreenBright=" + ((mPowerState & SCREEN_BRIGHT_BIT) != 0)
1431 + " newScreenBright=" + ((newState & SCREEN_BRIGHT_BIT) != 0));
1432 Log.d(TAG, " oldButtonBright=" + ((mPowerState & BUTTON_BRIGHT_BIT) != 0)
1433 + " newButtonBright=" + ((newState & BUTTON_BRIGHT_BIT) != 0));
1434 Log.d(TAG, " oldScreenOn=" + oldScreenOn
1435 + " newScreenOn=" + newScreenOn);
1436 Log.d(TAG, " oldBatteryLow=" + ((mPowerState & BATTERY_LOW_BIT) != 0)
1437 + " newBatteryLow=" + ((newState & BATTERY_LOW_BIT) != 0));
1438 }
1439
1440 if (mPowerState != newState) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001441 updateLightsLocked(newState, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001442 mPowerState = (mPowerState & ~LIGHTS_MASK) | (newState & LIGHTS_MASK);
1443 }
1444
1445 if (oldScreenOn != newScreenOn) {
1446 if (newScreenOn) {
Joe Onorato128e7292009-03-24 18:41:31 -07001447 // When the user presses the power button, we need to always send out the
1448 // notification that it's going to sleep so the keyguard goes on. But
1449 // we can't do that until the screen fades out, so we don't show the keyguard
1450 // too early.
1451 if (mStillNeedSleepNotification) {
1452 sendNotificationLocked(false, WindowManagerPolicy.OFF_BECAUSE_OF_USER);
1453 }
1454
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001455 // Turn on the screen UNLESS there was a prior
1456 // preventScreenOn(true) request. (Note that the lifetime
1457 // of a single preventScreenOn() request is limited to 5
1458 // seconds to prevent a buggy app from disabling the
1459 // screen forever; see forceReenableScreen().)
1460 boolean reallyTurnScreenOn = true;
1461 if (mSpew) {
1462 Log.d(TAG, "- turning screen on... mPreventScreenOn = "
1463 + mPreventScreenOn);
1464 }
1465
1466 if (mPreventScreenOn) {
1467 if (mSpew) {
1468 Log.d(TAG, "- PREVENTING screen from really turning on!");
1469 }
1470 reallyTurnScreenOn = false;
1471 }
1472 if (reallyTurnScreenOn) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001473 err = setScreenStateLocked(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001474 long identity = Binder.clearCallingIdentity();
1475 try {
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001476 mBatteryStats.noteScreenBrightness(getPreferredBrightness());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001477 mBatteryStats.noteScreenOn();
1478 } catch (RemoteException e) {
1479 Log.w(TAG, "RemoteException calling noteScreenOn on BatteryStatsService", e);
1480 } finally {
1481 Binder.restoreCallingIdentity(identity);
1482 }
1483 } else {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001484 setScreenStateLocked(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001485 // But continue as if we really did turn the screen on...
1486 err = 0;
1487 }
1488
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001489 mLastTouchDown = 0;
1490 mTotalTouchDownTime = 0;
1491 mTouchCycles = 0;
1492 EventLog.writeEvent(LOG_POWER_SCREEN_STATE, 1, becauseOfUser ? 1 : 0,
1493 mTotalTouchDownTime, mTouchCycles);
1494 if (err == 0) {
1495 mPowerState |= SCREEN_ON_BIT;
1496 sendNotificationLocked(true, -1);
1497 }
1498 } else {
Mike Lockwood497087e32009-11-08 18:33:03 -05001499 // cancel light sensor task
1500 mHandler.removeCallbacks(mAutoBrightnessTask);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001501 mScreenOffTime = SystemClock.elapsedRealtime();
1502 long identity = Binder.clearCallingIdentity();
1503 try {
1504 mBatteryStats.noteScreenOff();
1505 } catch (RemoteException e) {
1506 Log.w(TAG, "RemoteException calling noteScreenOff on BatteryStatsService", e);
1507 } finally {
1508 Binder.restoreCallingIdentity(identity);
1509 }
1510 mPowerState &= ~SCREEN_ON_BIT;
1511 if (!mScreenBrightness.animating) {
Joe Onorato128e7292009-03-24 18:41:31 -07001512 err = screenOffFinishedAnimatingLocked(becauseOfUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001513 } else {
1514 mOffBecauseOfUser = becauseOfUser;
1515 err = 0;
1516 mLastTouchDown = 0;
1517 }
1518 }
1519 }
1520 }
1521 }
1522
Joe Onorato128e7292009-03-24 18:41:31 -07001523 private int screenOffFinishedAnimatingLocked(boolean becauseOfUser) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001524 // I don't think we need to check the current state here because all of these
1525 // Power.setScreenState and sendNotificationLocked can both handle being
1526 // called multiple times in the same state. -joeo
1527 EventLog.writeEvent(LOG_POWER_SCREEN_STATE, 0, becauseOfUser ? 1 : 0,
1528 mTotalTouchDownTime, mTouchCycles);
1529 mLastTouchDown = 0;
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001530 int err = setScreenStateLocked(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001531 if (err == 0) {
1532 int why = becauseOfUser
1533 ? WindowManagerPolicy.OFF_BECAUSE_OF_USER
1534 : WindowManagerPolicy.OFF_BECAUSE_OF_TIMEOUT;
1535 sendNotificationLocked(false, why);
1536 }
1537 return err;
1538 }
1539
1540 private boolean batteryIsLow() {
1541 return (!mIsPowered &&
1542 mBatteryService.getBatteryLevel() <= Power.LOW_BATTERY_THRESHOLD);
1543 }
1544
The Android Open Source Project10592532009-03-18 17:39:46 -07001545 private void updateLightsLocked(int newState, int forceState) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001546 final int oldState = mPowerState;
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001547 newState = applyButtonState(newState);
1548 newState = applyKeyboardState(newState);
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001549 final int realDifference = (newState ^ oldState);
1550 final int difference = realDifference | forceState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001551 if (difference == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001552 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001553 }
1554
1555 int offMask = 0;
1556 int dimMask = 0;
1557 int onMask = 0;
1558
1559 int preferredBrightness = getPreferredBrightness();
1560 boolean startAnimation = false;
1561
1562 if ((difference & KEYBOARD_BRIGHT_BIT) != 0) {
1563 if (ANIMATE_KEYBOARD_LIGHTS) {
1564 if ((newState & KEYBOARD_BRIGHT_BIT) == 0) {
1565 mKeyboardBrightness.setTargetLocked(Power.BRIGHTNESS_OFF,
Joe Onorato128e7292009-03-24 18:41:31 -07001566 ANIM_STEPS, INITIAL_KEYBOARD_BRIGHTNESS,
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001567 Power.BRIGHTNESS_ON);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001568 } else {
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001569 mKeyboardBrightness.setTargetLocked(Power.BRIGHTNESS_ON,
Joe Onorato128e7292009-03-24 18:41:31 -07001570 ANIM_STEPS, INITIAL_KEYBOARD_BRIGHTNESS,
1571 Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001572 }
1573 startAnimation = true;
1574 } else {
1575 if ((newState & KEYBOARD_BRIGHT_BIT) == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001576 offMask |= KEYBOARD_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001577 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001578 onMask |= KEYBOARD_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001579 }
1580 }
1581 }
1582
1583 if ((difference & BUTTON_BRIGHT_BIT) != 0) {
1584 if (ANIMATE_BUTTON_LIGHTS) {
1585 if ((newState & BUTTON_BRIGHT_BIT) == 0) {
1586 mButtonBrightness.setTargetLocked(Power.BRIGHTNESS_OFF,
Joe Onorato128e7292009-03-24 18:41:31 -07001587 ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001588 Power.BRIGHTNESS_ON);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001589 } else {
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001590 mButtonBrightness.setTargetLocked(Power.BRIGHTNESS_ON,
Joe Onorato128e7292009-03-24 18:41:31 -07001591 ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
1592 Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001593 }
1594 startAnimation = true;
1595 } else {
1596 if ((newState & BUTTON_BRIGHT_BIT) == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001597 offMask |= BUTTON_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001598 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001599 onMask |= BUTTON_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001600 }
1601 }
1602 }
1603
1604 if ((difference & (SCREEN_ON_BIT | SCREEN_BRIGHT_BIT)) != 0) {
1605 if (ANIMATE_SCREEN_LIGHTS) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001606 int nominalCurrentValue = -1;
1607 // If there was an actual difference in the light state, then
1608 // figure out the "ideal" current value based on the previous
1609 // state. Otherwise, this is a change due to the brightness
1610 // override, so we want to animate from whatever the current
1611 // value is.
1612 if ((realDifference & (SCREEN_ON_BIT | SCREEN_BRIGHT_BIT)) != 0) {
1613 switch (oldState & (SCREEN_BRIGHT_BIT|SCREEN_ON_BIT)) {
1614 case SCREEN_BRIGHT_BIT | SCREEN_ON_BIT:
1615 nominalCurrentValue = preferredBrightness;
1616 break;
1617 case SCREEN_ON_BIT:
1618 nominalCurrentValue = Power.BRIGHTNESS_DIM;
1619 break;
1620 case 0:
1621 nominalCurrentValue = Power.BRIGHTNESS_OFF;
1622 break;
1623 case SCREEN_BRIGHT_BIT:
1624 default:
1625 // not possible
1626 nominalCurrentValue = (int)mScreenBrightness.curValue;
1627 break;
1628 }
Joe Onorato128e7292009-03-24 18:41:31 -07001629 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001630 int brightness = preferredBrightness;
1631 int steps = ANIM_STEPS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001632 if ((newState & SCREEN_BRIGHT_BIT) == 0) {
1633 // dim or turn off backlight, depending on if the screen is on
1634 // the scale is because the brightness ramp isn't linear and this biases
1635 // it so the later parts take longer.
1636 final float scale = 1.5f;
1637 float ratio = (((float)Power.BRIGHTNESS_DIM)/preferredBrightness);
1638 if (ratio > 1.0f) ratio = 1.0f;
1639 if ((newState & SCREEN_ON_BIT) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001640 if ((oldState & SCREEN_BRIGHT_BIT) != 0) {
1641 // was bright
1642 steps = ANIM_STEPS;
1643 } else {
1644 // was dim
1645 steps = (int)(ANIM_STEPS*ratio*scale);
1646 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001647 brightness = Power.BRIGHTNESS_OFF;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001648 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001649 if ((oldState & SCREEN_ON_BIT) != 0) {
1650 // was bright
1651 steps = (int)(ANIM_STEPS*(1.0f-ratio)*scale);
1652 } else {
1653 // was dim
1654 steps = (int)(ANIM_STEPS*ratio);
1655 }
1656 if (mStayOnConditions != 0 && mBatteryService.isPowered(mStayOnConditions)) {
1657 // If the "stay on while plugged in" option is
1658 // turned on, then the screen will often not
1659 // automatically turn off while plugged in. To
1660 // still have a sense of when it is inactive, we
1661 // will then count going dim as turning off.
1662 mScreenOffTime = SystemClock.elapsedRealtime();
1663 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001664 brightness = Power.BRIGHTNESS_DIM;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001665 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001666 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001667 long identity = Binder.clearCallingIdentity();
1668 try {
1669 mBatteryStats.noteScreenBrightness(brightness);
1670 } catch (RemoteException e) {
1671 // Nothing interesting to do.
1672 } finally {
1673 Binder.restoreCallingIdentity(identity);
1674 }
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001675 if (mScreenBrightness.setTargetLocked(brightness,
1676 steps, INITIAL_SCREEN_BRIGHTNESS, nominalCurrentValue)) {
1677 startAnimation = true;
1678 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001679 } else {
1680 if ((newState & SCREEN_BRIGHT_BIT) == 0) {
1681 // dim or turn off backlight, depending on if the screen is on
1682 if ((newState & SCREEN_ON_BIT) == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001683 offMask |= SCREEN_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001684 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001685 dimMask |= SCREEN_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001686 }
1687 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001688 onMask |= SCREEN_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001689 }
1690 }
1691 }
1692
1693 if (startAnimation) {
1694 if (mSpew) {
1695 Log.i(TAG, "Scheduling light animator!");
1696 }
1697 mHandler.removeCallbacks(mLightAnimator);
1698 mHandler.post(mLightAnimator);
1699 }
1700
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001701 if (offMask != 0) {
1702 //Log.i(TAG, "Setting brightess off: " + offMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001703 setLightBrightness(offMask, Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001704 }
1705 if (dimMask != 0) {
1706 int brightness = Power.BRIGHTNESS_DIM;
1707 if ((newState & BATTERY_LOW_BIT) != 0 &&
1708 brightness > Power.BRIGHTNESS_LOW_BATTERY) {
1709 brightness = Power.BRIGHTNESS_LOW_BATTERY;
1710 }
1711 //Log.i(TAG, "Setting brightess dim " + brightness + ": " + offMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001712 setLightBrightness(dimMask, brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001713 }
1714 if (onMask != 0) {
1715 int brightness = getPreferredBrightness();
1716 if ((newState & BATTERY_LOW_BIT) != 0 &&
1717 brightness > Power.BRIGHTNESS_LOW_BATTERY) {
1718 brightness = Power.BRIGHTNESS_LOW_BATTERY;
1719 }
1720 //Log.i(TAG, "Setting brightess on " + brightness + ": " + onMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001721 setLightBrightness(onMask, brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001722 }
The Android Open Source Project10592532009-03-18 17:39:46 -07001723 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001724
The Android Open Source Project10592532009-03-18 17:39:46 -07001725 private void setLightBrightness(int mask, int value) {
Mike Lockwoodcc9a63d2009-11-10 07:50:28 -05001726 int brightnessMode = (mAutoBrightessEnabled
Mike Lockwood3a322132009-11-24 00:30:52 -05001727 ? LightsService.BRIGHTNESS_MODE_SENSOR
1728 : LightsService.BRIGHTNESS_MODE_USER);
The Android Open Source Project10592532009-03-18 17:39:46 -07001729 if ((mask & SCREEN_BRIGHT_BIT) != 0) {
Mike Lockwood3cb67a32009-11-27 14:25:58 -05001730 mLcdLight.setBrightness(value, brightnessMode);
The Android Open Source Project10592532009-03-18 17:39:46 -07001731 }
1732 if ((mask & BUTTON_BRIGHT_BIT) != 0) {
Mike Lockwood3cb67a32009-11-27 14:25:58 -05001733 mButtonLight.setBrightness(value);
The Android Open Source Project10592532009-03-18 17:39:46 -07001734 }
1735 if ((mask & KEYBOARD_BRIGHT_BIT) != 0) {
Mike Lockwood3cb67a32009-11-27 14:25:58 -05001736 mKeyboardLight.setBrightness(value);
The Android Open Source Project10592532009-03-18 17:39:46 -07001737 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001738 }
1739
1740 class BrightnessState {
1741 final int mask;
1742
1743 boolean initialized;
1744 int targetValue;
1745 float curValue;
1746 float delta;
1747 boolean animating;
1748
1749 BrightnessState(int m) {
1750 mask = m;
1751 }
1752
1753 public void dump(PrintWriter pw, String prefix) {
1754 pw.println(prefix + "animating=" + animating
1755 + " targetValue=" + targetValue
1756 + " curValue=" + curValue
1757 + " delta=" + delta);
1758 }
1759
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001760 boolean setTargetLocked(int target, int stepsToTarget, int initialValue,
Joe Onorato128e7292009-03-24 18:41:31 -07001761 int nominalCurrentValue) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001762 if (!initialized) {
1763 initialized = true;
1764 curValue = (float)initialValue;
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001765 } else if (targetValue == target) {
1766 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001767 }
1768 targetValue = target;
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001769 delta = (targetValue -
1770 (nominalCurrentValue >= 0 ? nominalCurrentValue : curValue))
1771 / stepsToTarget;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001772 if (mSpew) {
Joe Onorato128e7292009-03-24 18:41:31 -07001773 String noticeMe = nominalCurrentValue == curValue ? "" : " ******************";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001774 Log.i(TAG, "Setting target " + mask + ": cur=" + curValue
Joe Onorato128e7292009-03-24 18:41:31 -07001775 + " target=" + targetValue + " delta=" + delta
1776 + " nominalCurrentValue=" + nominalCurrentValue
1777 + noticeMe);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001778 }
1779 animating = true;
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001780 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001781 }
1782
1783 boolean stepLocked() {
1784 if (!animating) return false;
1785 if (false && mSpew) {
1786 Log.i(TAG, "Step target " + mask + ": cur=" + curValue
1787 + " target=" + targetValue + " delta=" + delta);
1788 }
1789 curValue += delta;
1790 int curIntValue = (int)curValue;
1791 boolean more = true;
1792 if (delta == 0) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001793 curValue = curIntValue = targetValue;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001794 more = false;
1795 } else if (delta > 0) {
1796 if (curIntValue >= targetValue) {
1797 curValue = curIntValue = targetValue;
1798 more = false;
1799 }
1800 } else {
1801 if (curIntValue <= targetValue) {
1802 curValue = curIntValue = targetValue;
1803 more = false;
1804 }
1805 }
1806 //Log.i(TAG, "Animating brightess " + curIntValue + ": " + mask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001807 setLightBrightness(mask, curIntValue);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001808 animating = more;
1809 if (!more) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001810 if (mask == SCREEN_BRIGHT_BIT && curIntValue == Power.BRIGHTNESS_OFF) {
Joe Onorato128e7292009-03-24 18:41:31 -07001811 screenOffFinishedAnimatingLocked(mOffBecauseOfUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001812 }
1813 }
1814 return more;
1815 }
1816 }
1817
1818 private class LightAnimator implements Runnable {
1819 public void run() {
1820 synchronized (mLocks) {
1821 long now = SystemClock.uptimeMillis();
1822 boolean more = mScreenBrightness.stepLocked();
1823 if (mKeyboardBrightness.stepLocked()) {
1824 more = true;
1825 }
1826 if (mButtonBrightness.stepLocked()) {
1827 more = true;
1828 }
1829 if (more) {
1830 mHandler.postAtTime(mLightAnimator, now+(1000/60));
1831 }
1832 }
1833 }
1834 }
1835
1836 private int getPreferredBrightness() {
1837 try {
1838 if (mScreenBrightnessOverride >= 0) {
1839 return mScreenBrightnessOverride;
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001840 } else if (mLightSensorScreenBrightness >= 0 && mUseSoftwareAutoBrightness
Mike Lockwood27c6dd72009-11-04 08:57:07 -05001841 && mAutoBrightessEnabled) {
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001842 return mLightSensorScreenBrightness;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001843 }
1844 final int brightness = Settings.System.getInt(mContext.getContentResolver(),
1845 SCREEN_BRIGHTNESS);
1846 // Don't let applications turn the screen all the way off
1847 return Math.max(brightness, Power.BRIGHTNESS_DIM);
1848 } catch (SettingNotFoundException snfe) {
1849 return Power.BRIGHTNESS_ON;
1850 }
1851 }
1852
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001853 private int applyButtonState(int state) {
1854 int brightness = -1;
1855 if (mButtonBrightnessOverride >= 0) {
1856 brightness = mButtonBrightnessOverride;
1857 } else if (mLightSensorButtonBrightness >= 0 && mUseSoftwareAutoBrightness) {
1858 brightness = mLightSensorButtonBrightness;
1859 }
1860 if (brightness > 0) {
1861 return state | BUTTON_BRIGHT_BIT;
1862 } else if (brightness == 0) {
1863 return state & ~BUTTON_BRIGHT_BIT;
1864 } else {
1865 return state;
1866 }
1867 }
1868
1869 private int applyKeyboardState(int state) {
1870 int brightness = -1;
1871 if (!mKeyboardVisible) {
1872 brightness = 0;
1873 } else if (mButtonBrightnessOverride >= 0) {
1874 brightness = mButtonBrightnessOverride;
1875 } else if (mLightSensorKeyboardBrightness >= 0 && mUseSoftwareAutoBrightness) {
1876 brightness = mLightSensorKeyboardBrightness;
1877 }
1878 if (brightness > 0) {
1879 return state | KEYBOARD_BRIGHT_BIT;
1880 } else if (brightness == 0) {
1881 return state & ~KEYBOARD_BRIGHT_BIT;
1882 } else {
1883 return state;
1884 }
1885 }
1886
Charles Mendis322591c2009-10-29 11:06:59 -07001887 public boolean isScreenOn() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001888 synchronized (mLocks) {
1889 return (mPowerState & SCREEN_ON_BIT) != 0;
1890 }
1891 }
1892
Charles Mendis322591c2009-10-29 11:06:59 -07001893 boolean isScreenBright() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001894 synchronized (mLocks) {
1895 return (mPowerState & SCREEN_BRIGHT) == SCREEN_BRIGHT;
1896 }
1897 }
1898
Mike Lockwood497087e32009-11-08 18:33:03 -05001899 private boolean isScreenTurningOffLocked() {
1900 return (mScreenBrightness.animating && mScreenBrightness.targetValue == 0);
1901 }
1902
Mike Lockwood200b30b2009-09-20 00:23:59 -04001903 private void forceUserActivityLocked() {
Mike Lockwoode090281422009-11-14 21:02:56 -05001904 if (isScreenTurningOffLocked()) {
1905 // cancel animation so userActivity will succeed
1906 mScreenBrightness.animating = false;
1907 }
Mike Lockwood200b30b2009-09-20 00:23:59 -04001908 boolean savedActivityAllowed = mUserActivityAllowed;
1909 mUserActivityAllowed = true;
1910 userActivity(SystemClock.uptimeMillis(), false);
1911 mUserActivityAllowed = savedActivityAllowed;
1912 }
1913
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001914 public void userActivityWithForce(long time, boolean noChangeLights, boolean force) {
1915 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1916 userActivity(time, noChangeLights, OTHER_EVENT, force);
1917 }
1918
1919 public void userActivity(long time, boolean noChangeLights) {
1920 userActivity(time, noChangeLights, OTHER_EVENT, false);
1921 }
1922
1923 public void userActivity(long time, boolean noChangeLights, int eventType) {
1924 userActivity(time, noChangeLights, eventType, false);
1925 }
1926
1927 public void userActivity(long time, boolean noChangeLights, int eventType, boolean force) {
1928 //mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1929
1930 if (((mPokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0)
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07001931 && (eventType == CHEEK_EVENT || eventType == TOUCH_EVENT)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001932 if (false) {
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07001933 Log.d(TAG, "dropping cheek or short event mPokey=0x" + Integer.toHexString(mPokey));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001934 }
1935 return;
1936 }
1937
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07001938 if (((mPokey & POKE_LOCK_IGNORE_TOUCH_AND_CHEEK_EVENTS) != 0)
1939 && (eventType == TOUCH_EVENT || eventType == TOUCH_UP_EVENT
1940 || eventType == LONG_TOUCH_EVENT || eventType == CHEEK_EVENT)) {
1941 if (false) {
1942 Log.d(TAG, "dropping touch mPokey=0x" + Integer.toHexString(mPokey));
1943 }
1944 return;
1945 }
1946
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001947 if (false) {
1948 if (((mPokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0)) {
1949 Log.d(TAG, "userActivity !!!");//, new RuntimeException());
1950 } else {
1951 Log.d(TAG, "mPokey=0x" + Integer.toHexString(mPokey));
1952 }
1953 }
1954
1955 synchronized (mLocks) {
1956 if (mSpew) {
1957 Log.d(TAG, "userActivity mLastEventTime=" + mLastEventTime + " time=" + time
1958 + " mUserActivityAllowed=" + mUserActivityAllowed
1959 + " mUserState=0x" + Integer.toHexString(mUserState)
Mike Lockwood36fc3022009-08-25 16:49:06 -07001960 + " mWakeLockState=0x" + Integer.toHexString(mWakeLockState)
1961 + " mProximitySensorActive=" + mProximitySensorActive
1962 + " force=" + force);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001963 }
Mike Lockwood05067122009-10-27 23:07:25 -04001964 // ignore user activity if we are in the process of turning off the screen
Mike Lockwood497087e32009-11-08 18:33:03 -05001965 if (isScreenTurningOffLocked()) {
Mike Lockwood05067122009-10-27 23:07:25 -04001966 Log.d(TAG, "ignoring user activity while turning off screen");
1967 return;
1968 }
Mike Lockwood0e39ea82009-11-18 15:37:10 -05001969 // Disable proximity sensor if if user presses power key while we are in the
1970 // "waiting for proximity sensor to go negative" state.
1971 if (mProximitySensorActive && mProximityWakeLockCount == 0) {
1972 mProximitySensorActive = false;
1973 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001974 if (mLastEventTime <= time || force) {
1975 mLastEventTime = time;
Mike Lockwood36fc3022009-08-25 16:49:06 -07001976 if ((mUserActivityAllowed && !mProximitySensorActive) || force) {
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001977 // Only turn on button backlights if a button was pressed
1978 // and auto brightness is disabled
Mike Lockwood4984e732009-11-01 08:16:33 -05001979 if (eventType == BUTTON_EVENT && !mUseSoftwareAutoBrightness) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001980 mUserState = (mKeyboardVisible ? ALL_BRIGHT : SCREEN_BUTTON_BRIGHT);
1981 } else {
1982 // don't clear button/keyboard backlights when the screen is touched.
1983 mUserState |= SCREEN_BRIGHT;
1984 }
1985
Dianne Hackborn617f8772009-03-31 15:04:46 -07001986 int uid = Binder.getCallingUid();
1987 long ident = Binder.clearCallingIdentity();
1988 try {
1989 mBatteryStats.noteUserActivity(uid, eventType);
1990 } catch (RemoteException e) {
1991 // Ignore
1992 } finally {
1993 Binder.restoreCallingIdentity(ident);
1994 }
1995
Michael Chane96440f2009-05-06 10:27:36 -07001996 mWakeLockState = mLocks.reactivateScreenLocksLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001997 setPowerState(mUserState | mWakeLockState, noChangeLights, true);
1998 setTimeoutLocked(time, SCREEN_BRIGHT);
1999 }
2000 }
2001 }
2002 }
2003
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002004 private int getAutoBrightnessValue(int sensorValue, int[] values) {
2005 try {
2006 int i;
2007 for (i = 0; i < mAutoBrightnessLevels.length; i++) {
2008 if (sensorValue < mAutoBrightnessLevels[i]) {
2009 break;
2010 }
2011 }
2012 return values[i];
2013 } catch (Exception e) {
2014 // guard against null pointer or index out of bounds errors
2015 Log.e(TAG, "getAutoBrightnessValue", e);
2016 return 255;
2017 }
2018 }
2019
Mike Lockwood20f87d72009-11-05 16:08:51 -05002020 private Runnable mProximityTask = new Runnable() {
2021 public void run() {
2022 synchronized (mLocks) {
2023 if (mProximityPendingValue != -1) {
2024 proximityChangedLocked(mProximityPendingValue == 1);
2025 mProximityPendingValue = -1;
2026 }
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002027 if (mProximityPartialLock.isHeld()) {
2028 mProximityPartialLock.release();
2029 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002030 }
2031 }
2032 };
2033
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002034 private Runnable mAutoBrightnessTask = new Runnable() {
2035 public void run() {
Mike Lockwoodfa68ab42009-10-20 11:08:49 -04002036 synchronized (mLocks) {
2037 int value = (int)mLightSensorPendingValue;
2038 if (value >= 0) {
2039 mLightSensorPendingValue = -1;
2040 lightSensorChangedLocked(value);
2041 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002042 }
2043 }
2044 };
2045
2046 private void lightSensorChangedLocked(int value) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002047 if (mDebugLightSensor) {
2048 Log.d(TAG, "lightSensorChangedLocked " + value);
2049 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002050
2051 if (mLightSensorValue != value) {
2052 mLightSensorValue = value;
2053 if ((mPowerState & BATTERY_LOW_BIT) == 0) {
2054 int lcdValue = getAutoBrightnessValue(value, mLcdBacklightValues);
2055 int buttonValue = getAutoBrightnessValue(value, mButtonBacklightValues);
Mike Lockwooddf024922009-10-29 21:29:15 -04002056 int keyboardValue;
2057 if (mKeyboardVisible) {
2058 keyboardValue = getAutoBrightnessValue(value, mKeyboardBacklightValues);
2059 } else {
2060 keyboardValue = 0;
2061 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002062 mLightSensorScreenBrightness = lcdValue;
2063 mLightSensorButtonBrightness = buttonValue;
2064 mLightSensorKeyboardBrightness = keyboardValue;
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002065
2066 if (mDebugLightSensor) {
2067 Log.d(TAG, "lcdValue " + lcdValue);
2068 Log.d(TAG, "buttonValue " + buttonValue);
2069 Log.d(TAG, "keyboardValue " + keyboardValue);
2070 }
2071
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002072 boolean startAnimation = false;
Mike Lockwood4984e732009-11-01 08:16:33 -05002073 if (mAutoBrightessEnabled && mScreenBrightnessOverride < 0) {
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002074 if (ANIMATE_SCREEN_LIGHTS) {
2075 if (mScreenBrightness.setTargetLocked(lcdValue,
2076 AUTOBRIGHTNESS_ANIM_STEPS, INITIAL_SCREEN_BRIGHTNESS,
2077 (int)mScreenBrightness.curValue)) {
2078 startAnimation = true;
2079 }
2080 } else {
Mike Lockwoodcc9a63d2009-11-10 07:50:28 -05002081 int brightnessMode = (mAutoBrightessEnabled
Mike Lockwood3a322132009-11-24 00:30:52 -05002082 ? LightsService.BRIGHTNESS_MODE_SENSOR
2083 : LightsService.BRIGHTNESS_MODE_USER);
Mike Lockwood3cb67a32009-11-27 14:25:58 -05002084 mLcdLight.setBrightness(lcdValue, brightnessMode);
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002085 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002086 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002087 if (mButtonBrightnessOverride < 0) {
2088 if (ANIMATE_BUTTON_LIGHTS) {
2089 if (mButtonBrightness.setTargetLocked(buttonValue,
2090 AUTOBRIGHTNESS_ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
2091 (int)mButtonBrightness.curValue)) {
2092 startAnimation = true;
2093 }
2094 } else {
Mike Lockwood3cb67a32009-11-27 14:25:58 -05002095 mButtonLight.setBrightness(buttonValue);
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002096 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002097 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002098 if (mButtonBrightnessOverride < 0 || !mKeyboardVisible) {
2099 if (ANIMATE_KEYBOARD_LIGHTS) {
2100 if (mKeyboardBrightness.setTargetLocked(keyboardValue,
2101 AUTOBRIGHTNESS_ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
2102 (int)mKeyboardBrightness.curValue)) {
2103 startAnimation = true;
2104 }
2105 } else {
Mike Lockwood3cb67a32009-11-27 14:25:58 -05002106 mKeyboardLight.setBrightness(keyboardValue);
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002107 }
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002108 }
2109 if (startAnimation) {
2110 if (mDebugLightSensor) {
2111 Log.i(TAG, "lightSensorChangedLocked scheduling light animator");
2112 }
2113 mHandler.removeCallbacks(mLightAnimator);
2114 mHandler.post(mLightAnimator);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002115 }
2116 }
2117 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002118 }
2119
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002120 /**
2121 * The user requested that we go to sleep (probably with the power button).
2122 * This overrides all wake locks that are held.
2123 */
2124 public void goToSleep(long time)
2125 {
2126 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
2127 synchronized (mLocks) {
2128 goToSleepLocked(time);
2129 }
2130 }
2131
2132 /**
Doug Zongker50a21f42009-11-19 12:49:53 -08002133 * Reboot the device immediately, passing 'reason' (may be null)
2134 * to the underlying __reboot system call. Should not return.
2135 */
2136 public void reboot(String reason)
2137 {
2138 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
2139 try {
2140 Power.reboot(reason);
2141 } catch (IOException e) {
2142 Log.e(TAG, "reboot failed", e);
2143 }
2144 }
2145
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002146 private void goToSleepLocked(long time) {
2147
2148 if (mLastEventTime <= time) {
2149 mLastEventTime = time;
2150 // cancel all of the wake locks
2151 mWakeLockState = SCREEN_OFF;
2152 int N = mLocks.size();
2153 int numCleared = 0;
2154 for (int i=0; i<N; i++) {
2155 WakeLock wl = mLocks.get(i);
2156 if (isScreenLock(wl.flags)) {
2157 mLocks.get(i).activated = false;
2158 numCleared++;
2159 }
2160 }
2161 EventLog.writeEvent(LOG_POWER_SLEEP_REQUESTED, numCleared);
Joe Onorato128e7292009-03-24 18:41:31 -07002162 mStillNeedSleepNotification = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002163 mUserState = SCREEN_OFF;
2164 setPowerState(SCREEN_OFF, false, true);
2165 cancelTimerLocked();
2166 }
2167 }
2168
2169 public long timeSinceScreenOn() {
2170 synchronized (mLocks) {
2171 if ((mPowerState & SCREEN_ON_BIT) != 0) {
2172 return 0;
2173 }
2174 return SystemClock.elapsedRealtime() - mScreenOffTime;
2175 }
2176 }
2177
2178 public void setKeyboardVisibility(boolean visible) {
Mike Lockwooda625b382009-09-12 17:36:03 -07002179 synchronized (mLocks) {
2180 if (mSpew) {
2181 Log.d(TAG, "setKeyboardVisibility: " + visible);
2182 }
Mike Lockwood3c9435a2009-10-22 15:45:37 -04002183 if (mKeyboardVisible != visible) {
2184 mKeyboardVisible = visible;
2185 // don't signal user activity if the screen is off; other code
2186 // will take care of turning on due to a true change to the lid
2187 // switch and synchronized with the lock screen.
2188 if ((mPowerState & SCREEN_ON_BIT) != 0) {
Mike Lockwood4984e732009-11-01 08:16:33 -05002189 if (mUseSoftwareAutoBrightness) {
Mike Lockwooddf024922009-10-29 21:29:15 -04002190 // force recompute of backlight values
2191 if (mLightSensorValue >= 0) {
2192 int value = (int)mLightSensorValue;
2193 mLightSensorValue = -1;
2194 lightSensorChangedLocked(value);
2195 }
2196 }
Mike Lockwood3c9435a2009-10-22 15:45:37 -04002197 userActivity(SystemClock.uptimeMillis(), false, BUTTON_EVENT, true);
2198 }
Mike Lockwooda625b382009-09-12 17:36:03 -07002199 }
2200 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002201 }
2202
2203 /**
2204 * When the keyguard is up, it manages the power state, and userActivity doesn't do anything.
Mike Lockwood50c548d2009-11-09 16:02:06 -05002205 * When disabling user activity we also reset user power state so the keyguard can reset its
2206 * short screen timeout when keyguard is unhidden.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002207 */
2208 public void enableUserActivity(boolean enabled) {
Mike Lockwood50c548d2009-11-09 16:02:06 -05002209 if (mSpew) {
2210 Log.d(TAG, "enableUserActivity " + enabled);
2211 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002212 synchronized (mLocks) {
2213 mUserActivityAllowed = enabled;
Mike Lockwood50c548d2009-11-09 16:02:06 -05002214 if (!enabled) {
2215 // cancel timeout and clear mUserState so the keyguard can set a short timeout
2216 setTimeoutLocked(SystemClock.uptimeMillis(), 0);
2217 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002218 }
2219 }
2220
Mike Lockwooddc3494e2009-10-14 21:17:09 -07002221 private void setScreenBrightnessMode(int mode) {
Mike Lockwood2d155d22009-10-27 09:32:30 -04002222 boolean enabled = (mode == SCREEN_BRIGHTNESS_MODE_AUTOMATIC);
Mike Lockwoodf90ffcc2009-11-03 11:41:27 -05002223 if (mUseSoftwareAutoBrightness && mAutoBrightessEnabled != enabled) {
Mike Lockwood2d155d22009-10-27 09:32:30 -04002224 mAutoBrightessEnabled = enabled;
Charles Mendis322591c2009-10-29 11:06:59 -07002225 if (isScreenOn()) {
Mike Lockwood4984e732009-11-01 08:16:33 -05002226 // force recompute of backlight values
2227 if (mLightSensorValue >= 0) {
2228 int value = (int)mLightSensorValue;
2229 mLightSensorValue = -1;
2230 lightSensorChangedLocked(value);
2231 }
Mike Lockwood2d155d22009-10-27 09:32:30 -04002232 }
Mike Lockwooddc3494e2009-10-14 21:17:09 -07002233 }
2234 }
2235
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002236 /** Sets the screen off timeouts:
2237 * mKeylightDelay
2238 * mDimDelay
2239 * mScreenOffDelay
2240 * */
2241 private void setScreenOffTimeoutsLocked() {
2242 if ((mPokey & POKE_LOCK_SHORT_TIMEOUT) != 0) {
2243 mKeylightDelay = mShortKeylightDelay; // Configurable via Gservices
2244 mDimDelay = -1;
2245 mScreenOffDelay = 0;
2246 } else if ((mPokey & POKE_LOCK_MEDIUM_TIMEOUT) != 0) {
2247 mKeylightDelay = MEDIUM_KEYLIGHT_DELAY;
2248 mDimDelay = -1;
2249 mScreenOffDelay = 0;
2250 } else {
2251 int totalDelay = mTotalDelaySetting;
2252 mKeylightDelay = LONG_KEYLIGHT_DELAY;
2253 if (totalDelay < 0) {
2254 mScreenOffDelay = Integer.MAX_VALUE;
2255 } else if (mKeylightDelay < totalDelay) {
2256 // subtract the time that the keylight delay. This will give us the
2257 // remainder of the time that we need to sleep to get the accurate
2258 // screen off timeout.
2259 mScreenOffDelay = totalDelay - mKeylightDelay;
2260 } else {
2261 mScreenOffDelay = 0;
2262 }
2263 if (mDimScreen && totalDelay >= (LONG_KEYLIGHT_DELAY + LONG_DIM_TIME)) {
2264 mDimDelay = mScreenOffDelay - LONG_DIM_TIME;
2265 mScreenOffDelay = LONG_DIM_TIME;
2266 } else {
2267 mDimDelay = -1;
2268 }
2269 }
2270 if (mSpew) {
2271 Log.d(TAG, "setScreenOffTimeouts mKeylightDelay=" + mKeylightDelay
2272 + " mDimDelay=" + mDimDelay + " mScreenOffDelay=" + mScreenOffDelay
2273 + " mDimScreen=" + mDimScreen);
2274 }
2275 }
2276
2277 /**
2278 * Refreshes cached Gservices settings. Called once on startup, and
2279 * on subsequent Settings.Gservices.CHANGED_ACTION broadcasts (see
2280 * GservicesChangedReceiver).
2281 */
2282 private void updateGservicesValues() {
2283 mShortKeylightDelay = Settings.Gservices.getInt(
2284 mContext.getContentResolver(),
2285 Settings.Gservices.SHORT_KEYLIGHT_DELAY_MS,
2286 SHORT_KEYLIGHT_DELAY_DEFAULT);
2287 // Log.i(TAG, "updateGservicesValues(): mShortKeylightDelay now " + mShortKeylightDelay);
2288 }
2289
2290 /**
2291 * Receiver for the Gservices.CHANGED_ACTION broadcast intent,
2292 * which tells us we need to refresh our cached Gservices settings.
2293 */
2294 private class GservicesChangedReceiver extends BroadcastReceiver {
2295 @Override
2296 public void onReceive(Context context, Intent intent) {
2297 // Log.i(TAG, "GservicesChangedReceiver.onReceive(): " + intent);
2298 updateGservicesValues();
2299 }
2300 }
2301
2302 private class LockList extends ArrayList<WakeLock>
2303 {
2304 void addLock(WakeLock wl)
2305 {
2306 int index = getIndex(wl.binder);
2307 if (index < 0) {
2308 this.add(wl);
2309 }
2310 }
2311
2312 WakeLock removeLock(IBinder binder)
2313 {
2314 int index = getIndex(binder);
2315 if (index >= 0) {
2316 return this.remove(index);
2317 } else {
2318 return null;
2319 }
2320 }
2321
2322 int getIndex(IBinder binder)
2323 {
2324 int N = this.size();
2325 for (int i=0; i<N; i++) {
2326 if (this.get(i).binder == binder) {
2327 return i;
2328 }
2329 }
2330 return -1;
2331 }
2332
2333 int gatherState()
2334 {
2335 int result = 0;
2336 int N = this.size();
2337 for (int i=0; i<N; i++) {
2338 WakeLock wl = this.get(i);
2339 if (wl.activated) {
2340 if (isScreenLock(wl.flags)) {
2341 result |= wl.minState;
2342 }
2343 }
2344 }
2345 return result;
2346 }
Michael Chane96440f2009-05-06 10:27:36 -07002347
2348 int reactivateScreenLocksLocked()
2349 {
2350 int result = 0;
2351 int N = this.size();
2352 for (int i=0; i<N; i++) {
2353 WakeLock wl = this.get(i);
2354 if (isScreenLock(wl.flags)) {
2355 wl.activated = true;
2356 result |= wl.minState;
2357 }
2358 }
2359 return result;
2360 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002361 }
2362
2363 void setPolicy(WindowManagerPolicy p) {
2364 synchronized (mLocks) {
2365 mPolicy = p;
2366 mLocks.notifyAll();
2367 }
2368 }
2369
2370 WindowManagerPolicy getPolicyLocked() {
2371 while (mPolicy == null || !mDoneBooting) {
2372 try {
2373 mLocks.wait();
2374 } catch (InterruptedException e) {
2375 // Ignore
2376 }
2377 }
2378 return mPolicy;
2379 }
2380
2381 void systemReady() {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002382 mSensorManager = new SensorManager(mHandlerThread.getLooper());
2383 mProximitySensor = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
2384 // don't bother with the light sensor if auto brightness is handled in hardware
Mike Lockwoodaa66ea82009-10-31 16:31:27 -04002385 if (mUseSoftwareAutoBrightness) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002386 mLightSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
Mike Lockwood4984e732009-11-01 08:16:33 -05002387 enableLightSensor(true);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002388 }
2389
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002390 synchronized (mLocks) {
2391 Log.d(TAG, "system ready!");
2392 mDoneBooting = true;
Dianne Hackborn617f8772009-03-31 15:04:46 -07002393 long identity = Binder.clearCallingIdentity();
2394 try {
2395 mBatteryStats.noteScreenBrightness(getPreferredBrightness());
2396 mBatteryStats.noteScreenOn();
2397 } catch (RemoteException e) {
2398 // Nothing interesting to do.
2399 } finally {
2400 Binder.restoreCallingIdentity(identity);
2401 }
Mike Lockwood2d7bb812009-11-15 18:12:22 -05002402 }
2403 }
2404
2405 void bootCompleted() {
2406 Log.d(TAG, "bootCompleted");
2407 synchronized (mLocks) {
2408 mBootCompleted = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002409 userActivity(SystemClock.uptimeMillis(), false, BUTTON_EVENT, true);
2410 updateWakeLockLocked();
2411 mLocks.notifyAll();
2412 }
2413 }
2414
2415 public void monitor() {
2416 synchronized (mLocks) { }
2417 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002418
2419 public int getSupportedWakeLockFlags() {
2420 int result = PowerManager.PARTIAL_WAKE_LOCK
2421 | PowerManager.FULL_WAKE_LOCK
2422 | PowerManager.SCREEN_DIM_WAKE_LOCK;
2423
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002424 if (mProximitySensor != null) {
2425 result |= PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK;
2426 }
2427
2428 return result;
2429 }
2430
Mike Lockwood237a2992009-09-15 14:42:16 -04002431 public void setBacklightBrightness(int brightness) {
2432 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
2433 // Don't let applications turn the screen all the way off
2434 brightness = Math.max(brightness, Power.BRIGHTNESS_DIM);
Mike Lockwood3cb67a32009-11-27 14:25:58 -05002435 mLcdLight.setBrightness(brightness);
2436 mKeyboardLight.setBrightness(mKeyboardVisible ? brightness : 0);
2437 mButtonLight.setBrightness(brightness);
Mike Lockwood237a2992009-09-15 14:42:16 -04002438 long identity = Binder.clearCallingIdentity();
2439 try {
2440 mBatteryStats.noteScreenBrightness(brightness);
2441 } catch (RemoteException e) {
2442 Log.w(TAG, "RemoteException calling noteScreenBrightness on BatteryStatsService", e);
2443 } finally {
2444 Binder.restoreCallingIdentity(identity);
2445 }
2446
2447 // update our animation state
2448 if (ANIMATE_SCREEN_LIGHTS) {
2449 mScreenBrightness.curValue = brightness;
2450 mScreenBrightness.animating = false;
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002451 mScreenBrightness.targetValue = -1;
Mike Lockwood237a2992009-09-15 14:42:16 -04002452 }
2453 if (ANIMATE_KEYBOARD_LIGHTS) {
2454 mKeyboardBrightness.curValue = brightness;
2455 mKeyboardBrightness.animating = false;
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002456 mKeyboardBrightness.targetValue = -1;
Mike Lockwood237a2992009-09-15 14:42:16 -04002457 }
2458 if (ANIMATE_BUTTON_LIGHTS) {
2459 mButtonBrightness.curValue = brightness;
2460 mButtonBrightness.animating = false;
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002461 mButtonBrightness.targetValue = -1;
Mike Lockwood237a2992009-09-15 14:42:16 -04002462 }
2463 }
2464
Mike Lockwoodb11832d2009-11-25 15:25:55 -05002465 public void setAttentionLight(boolean on, int color) {
2466 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
Mike Lockwood3cb67a32009-11-27 14:25:58 -05002467 mAttentionLight.setFlashing(color, LightsService.LIGHT_FLASH_HARDWARE, (on ? 3 : 0), 0);
Mike Lockwoodb11832d2009-11-25 15:25:55 -05002468 }
2469
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002470 private void enableProximityLockLocked() {
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002471 if (mDebugProximitySensor) {
Mike Lockwood36fc3022009-08-25 16:49:06 -07002472 Log.d(TAG, "enableProximityLockLocked");
2473 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002474 if (!mProximitySensorEnabled) {
2475 // clear calling identity so sensor manager battery stats are accurate
2476 long identity = Binder.clearCallingIdentity();
2477 try {
2478 mSensorManager.registerListener(mProximityListener, mProximitySensor,
2479 SensorManager.SENSOR_DELAY_NORMAL);
2480 mProximitySensorEnabled = true;
2481 } finally {
2482 Binder.restoreCallingIdentity(identity);
2483 }
Mike Lockwood809ad0f2009-10-26 22:10:33 -04002484 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002485 }
2486
2487 private void disableProximityLockLocked() {
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002488 if (mDebugProximitySensor) {
Mike Lockwood36fc3022009-08-25 16:49:06 -07002489 Log.d(TAG, "disableProximityLockLocked");
2490 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002491 if (mProximitySensorEnabled) {
2492 // clear calling identity so sensor manager battery stats are accurate
2493 long identity = Binder.clearCallingIdentity();
2494 try {
2495 mSensorManager.unregisterListener(mProximityListener);
2496 mHandler.removeCallbacks(mProximityTask);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002497 if (mProximityPartialLock.isHeld()) {
2498 mProximityPartialLock.release();
2499 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002500 mProximitySensorEnabled = false;
2501 } finally {
2502 Binder.restoreCallingIdentity(identity);
2503 }
2504 if (mProximitySensorActive) {
2505 mProximitySensorActive = false;
2506 forceUserActivityLocked();
2507 }
Mike Lockwood200b30b2009-09-20 00:23:59 -04002508 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002509 }
2510
Mike Lockwood20f87d72009-11-05 16:08:51 -05002511 private void proximityChangedLocked(boolean active) {
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002512 if (mDebugProximitySensor) {
Mike Lockwood20f87d72009-11-05 16:08:51 -05002513 Log.d(TAG, "proximityChangedLocked, active: " + active);
2514 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002515 if (!mProximitySensorEnabled) {
2516 Log.d(TAG, "Ignoring proximity change after sensor is disabled");
Mike Lockwood0d72f7e2009-11-05 20:53:00 -05002517 return;
2518 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002519 if (active) {
2520 goToSleepLocked(SystemClock.uptimeMillis());
2521 mProximitySensorActive = true;
2522 } else {
2523 // proximity sensor negative events trigger as user activity.
2524 // temporarily set mUserActivityAllowed to true so this will work
2525 // even when the keyguard is on.
2526 mProximitySensorActive = false;
2527 forceUserActivityLocked();
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002528
2529 if (mProximityWakeLockCount == 0) {
2530 // disable sensor if we have no listeners left after proximity negative
2531 disableProximityLockLocked();
2532 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002533 }
2534 }
2535
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002536 private void enableLightSensor(boolean enable) {
2537 if (mDebugLightSensor) {
2538 Log.d(TAG, "enableLightSensor " + enable);
2539 }
2540 if (mSensorManager != null && mLightSensorEnabled != enable) {
2541 mLightSensorEnabled = enable;
Mike Lockwood809ad0f2009-10-26 22:10:33 -04002542 // clear calling identity so sensor manager battery stats are accurate
2543 long identity = Binder.clearCallingIdentity();
2544 try {
2545 if (enable) {
2546 mSensorManager.registerListener(mLightListener, mLightSensor,
2547 SensorManager.SENSOR_DELAY_NORMAL);
2548 } else {
2549 mSensorManager.unregisterListener(mLightListener);
2550 mHandler.removeCallbacks(mAutoBrightnessTask);
2551 }
2552 } finally {
2553 Binder.restoreCallingIdentity(identity);
Mike Lockwood06952d92009-08-13 16:05:38 -04002554 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002555 }
2556 }
2557
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002558 SensorEventListener mProximityListener = new SensorEventListener() {
2559 public void onSensorChanged(SensorEvent event) {
Mike Lockwoodba8eb1e2009-11-08 19:31:18 -05002560 long milliseconds = SystemClock.elapsedRealtime();
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002561 synchronized (mLocks) {
2562 float distance = event.values[0];
Mike Lockwood20f87d72009-11-05 16:08:51 -05002563 long timeSinceLastEvent = milliseconds - mLastProximityEventTime;
2564 mLastProximityEventTime = milliseconds;
2565 mHandler.removeCallbacks(mProximityTask);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002566 boolean proximityTaskQueued = false;
Mike Lockwood20f87d72009-11-05 16:08:51 -05002567
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002568 // compare against getMaximumRange to support sensors that only return 0 or 1
Mike Lockwood20f87d72009-11-05 16:08:51 -05002569 boolean active = (distance >= 0.0 && distance < PROXIMITY_THRESHOLD &&
2570 distance < mProximitySensor.getMaximumRange());
2571
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002572 if (mDebugProximitySensor) {
2573 Log.d(TAG, "mProximityListener.onSensorChanged active: " + active);
2574 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002575 if (timeSinceLastEvent < PROXIMITY_SENSOR_DELAY) {
2576 // enforce delaying atleast PROXIMITY_SENSOR_DELAY before processing
2577 mProximityPendingValue = (active ? 1 : 0);
2578 mHandler.postDelayed(mProximityTask, PROXIMITY_SENSOR_DELAY - timeSinceLastEvent);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002579 proximityTaskQueued = true;
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002580 } else {
Mike Lockwood20f87d72009-11-05 16:08:51 -05002581 // process the value immediately
2582 mProximityPendingValue = -1;
2583 proximityChangedLocked(active);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002584 }
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002585
2586 // update mProximityPartialLock state
2587 boolean held = mProximityPartialLock.isHeld();
2588 if (!held && proximityTaskQueued) {
2589 // hold wakelock until mProximityTask runs
2590 mProximityPartialLock.acquire();
2591 } else if (held && !proximityTaskQueued) {
2592 mProximityPartialLock.release();
2593 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002594 }
2595 }
2596
2597 public void onAccuracyChanged(Sensor sensor, int accuracy) {
2598 // ignore
2599 }
2600 };
2601
2602 SensorEventListener mLightListener = new SensorEventListener() {
2603 public void onSensorChanged(SensorEvent event) {
2604 synchronized (mLocks) {
Mike Lockwood497087e32009-11-08 18:33:03 -05002605 // ignore light sensor while screen is turning off
2606 if (isScreenTurningOffLocked()) {
2607 return;
2608 }
2609
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002610 int value = (int)event.values[0];
Mike Lockwoodba8eb1e2009-11-08 19:31:18 -05002611 long milliseconds = SystemClock.elapsedRealtime();
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002612 if (mDebugLightSensor) {
2613 Log.d(TAG, "onSensorChanged: light value: " + value);
2614 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002615 mHandler.removeCallbacks(mAutoBrightnessTask);
2616 if (mLightSensorValue != value) {
Mike Lockwood20ee6f22009-11-07 20:33:47 -05002617 if (mLightSensorValue == -1 ||
2618 milliseconds < mLastScreenOnTime + mLightSensorWarmupTime) {
2619 // process the value immediately if screen has just turned on
Mike Lockwood6c97fca2009-10-20 08:10:00 -04002620 lightSensorChangedLocked(value);
2621 } else {
2622 // delay processing to debounce the sensor
2623 mLightSensorPendingValue = value;
2624 mHandler.postDelayed(mAutoBrightnessTask, LIGHT_SENSOR_DELAY);
2625 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002626 } else {
2627 mLightSensorPendingValue = -1;
2628 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002629 }
2630 }
2631
2632 public void onAccuracyChanged(Sensor sensor, int accuracy) {
2633 // ignore
2634 }
2635 };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002636}