blob: e11c312098d28a8729673a5b9036837443ac6d13 [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;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800136
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800137 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;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800147
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800148 private final int MY_UID;
149
150 private boolean mDoneBooting = false;
Mike Lockwood2d7bb812009-11-15 18:12:22 -0500151 private boolean mBootCompleted = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800152 private int mStayOnConditions = 0;
Joe Onorato128e7292009-03-24 18:41:31 -0700153 private int[] mBroadcastQueue = new int[] { -1, -1, -1 };
154 private int[] mBroadcastWhy = new int[3];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800155 private int mPartialCount = 0;
156 private int mPowerState;
Mike Lockwood435eb642009-12-03 08:40:18 -0500157 // mScreenOffReason can be WindowManagerPolicy.OFF_BECAUSE_OF_USER,
158 // WindowManagerPolicy.OFF_BECAUSE_OF_TIMEOUT or WindowManagerPolicy.OFF_BECAUSE_OF_PROX_SENSOR
159 private int mScreenOffReason;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800160 private int mUserState;
161 private boolean mKeyboardVisible = false;
162 private boolean mUserActivityAllowed = true;
Mike Lockwoodee2b0942009-11-09 14:09:02 -0500163 private int mProximityWakeLockCount = 0;
164 private boolean mProximitySensorEnabled = false;
Mike Lockwood36fc3022009-08-25 16:49:06 -0700165 private boolean mProximitySensorActive = false;
Mike Lockwood20f87d72009-11-05 16:08:51 -0500166 private int mProximityPendingValue = -1; // -1 == nothing, 0 == inactive, 1 == active
167 private long mLastProximityEventTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800168 private int mTotalDelaySetting;
169 private int mKeylightDelay;
170 private int mDimDelay;
171 private int mScreenOffDelay;
172 private int mWakeLockState;
173 private long mLastEventTime = 0;
174 private long mScreenOffTime;
175 private volatile WindowManagerPolicy mPolicy;
176 private final LockList mLocks = new LockList();
177 private Intent mScreenOffIntent;
178 private Intent mScreenOnIntent;
Mike Lockwood3a322132009-11-24 00:30:52 -0500179 private LightsService mLightsService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800180 private Context mContext;
Mike Lockwood3cb67a32009-11-27 14:25:58 -0500181 private LightsService.Light mLcdLight;
182 private LightsService.Light mButtonLight;
183 private LightsService.Light mKeyboardLight;
184 private LightsService.Light mAttentionLight;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800185 private UnsynchronizedWakeLock mBroadcastWakeLock;
186 private UnsynchronizedWakeLock mStayOnWhilePluggedInScreenDimLock;
187 private UnsynchronizedWakeLock mStayOnWhilePluggedInPartialLock;
188 private UnsynchronizedWakeLock mPreventScreenOnPartialLock;
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500189 private UnsynchronizedWakeLock mProximityPartialLock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800190 private HandlerThread mHandlerThread;
191 private Handler mHandler;
192 private TimeoutTask mTimeoutTask = new TimeoutTask();
193 private LightAnimator mLightAnimator = new LightAnimator();
194 private final BrightnessState mScreenBrightness
The Android Open Source Project10592532009-03-18 17:39:46 -0700195 = new BrightnessState(SCREEN_BRIGHT_BIT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800196 private final BrightnessState mKeyboardBrightness
The Android Open Source Project10592532009-03-18 17:39:46 -0700197 = new BrightnessState(KEYBOARD_BRIGHT_BIT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800198 private final BrightnessState mButtonBrightness
The Android Open Source Project10592532009-03-18 17:39:46 -0700199 = new BrightnessState(BUTTON_BRIGHT_BIT);
Joe Onorato128e7292009-03-24 18:41:31 -0700200 private boolean mStillNeedSleepNotification;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800201 private boolean mIsPowered = false;
202 private IActivityManager mActivityService;
203 private IBatteryStats mBatteryStats;
204 private BatteryService mBatteryService;
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700205 private SensorManager mSensorManager;
206 private Sensor mProximitySensor;
Mike Lockwood8738e0c2009-10-04 08:44:47 -0400207 private Sensor mLightSensor;
208 private boolean mLightSensorEnabled;
209 private float mLightSensorValue = -1;
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700210 private float mLightSensorPendingValue = -1;
Mike Lockwoodfb73f792009-11-20 11:31:18 -0500211 private int mLightSensorScreenBrightness = -1;
212 private int mLightSensorButtonBrightness = -1;
213 private int mLightSensorKeyboardBrightness = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800214 private boolean mDimScreen = true;
215 private long mNextTimeout;
216 private volatile int mPokey = 0;
217 private volatile boolean mPokeAwakeOnSet = false;
218 private volatile boolean mInitComplete = false;
219 private HashMap<IBinder,PokeLock> mPokeLocks = new HashMap<IBinder,PokeLock>();
Mike Lockwood20ee6f22009-11-07 20:33:47 -0500220 // mLastScreenOnTime is the time the screen was last turned on
221 private long mLastScreenOnTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800222 private boolean mPreventScreenOn;
223 private int mScreenBrightnessOverride = -1;
Mike Lockwoodfb73f792009-11-20 11:31:18 -0500224 private int mButtonBrightnessOverride = -1;
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400225 private boolean mUseSoftwareAutoBrightness;
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700226 private boolean mAutoBrightessEnabled;
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700227 private int[] mAutoBrightnessLevels;
228 private int[] mLcdBacklightValues;
229 private int[] mButtonBacklightValues;
230 private int[] mKeyboardBacklightValues;
Mike Lockwood20ee6f22009-11-07 20:33:47 -0500231 private int mLightSensorWarmupTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800232
233 // Used when logging number and duration of touch-down cycles
234 private long mTotalTouchDownTime;
235 private long mLastTouchDown;
236 private int mTouchCycles;
237
238 // could be either static or controllable at runtime
239 private static final boolean mSpew = false;
Mike Lockwoodee2b0942009-11-09 14:09:02 -0500240 private static final boolean mDebugProximitySensor = (true || mSpew);
Mike Lockwooddd9668e2009-10-27 15:47:02 -0400241 private static final boolean mDebugLightSensor = (false || mSpew);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800242
243 /*
244 static PrintStream mLog;
245 static {
246 try {
247 mLog = new PrintStream("/data/power.log");
248 }
249 catch (FileNotFoundException e) {
250 android.util.Log.e(TAG, "Life is hard", e);
251 }
252 }
253 static class Log {
254 static void d(String tag, String s) {
255 mLog.println(s);
256 android.util.Log.d(tag, s);
257 }
258 static void i(String tag, String s) {
259 mLog.println(s);
260 android.util.Log.i(tag, s);
261 }
262 static void w(String tag, String s) {
263 mLog.println(s);
264 android.util.Log.w(tag, s);
265 }
266 static void e(String tag, String s) {
267 mLog.println(s);
268 android.util.Log.e(tag, s);
269 }
270 }
271 */
272
273 /**
274 * This class works around a deadlock between the lock in PowerManager.WakeLock
275 * and our synchronizing on mLocks. PowerManager.WakeLock synchronizes on its
276 * mToken object so it can be accessed from any thread, but it calls into here
277 * with its lock held. This class is essentially a reimplementation of
278 * PowerManager.WakeLock, but without that extra synchronized block, because we'll
279 * only call it with our own locks held.
280 */
281 private class UnsynchronizedWakeLock {
282 int mFlags;
283 String mTag;
284 IBinder mToken;
285 int mCount = 0;
286 boolean mRefCounted;
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500287 boolean mHeld;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800288
289 UnsynchronizedWakeLock(int flags, String tag, boolean refCounted) {
290 mFlags = flags;
291 mTag = tag;
292 mToken = new Binder();
293 mRefCounted = refCounted;
294 }
295
296 public void acquire() {
297 if (!mRefCounted || mCount++ == 0) {
298 long ident = Binder.clearCallingIdentity();
299 try {
300 PowerManagerService.this.acquireWakeLockLocked(mFlags, mToken,
301 MY_UID, mTag);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500302 mHeld = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800303 } finally {
304 Binder.restoreCallingIdentity(ident);
305 }
306 }
307 }
308
309 public void release() {
310 if (!mRefCounted || --mCount == 0) {
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500311 PowerManagerService.this.releaseWakeLockLocked(mToken, 0, false);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500312 mHeld = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800313 }
314 if (mCount < 0) {
315 throw new RuntimeException("WakeLock under-locked " + mTag);
316 }
317 }
318
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500319 public boolean isHeld()
320 {
321 return mHeld;
322 }
323
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800324 public String toString() {
325 return "UnsynchronizedWakeLock(mFlags=0x" + Integer.toHexString(mFlags)
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500326 + " mCount=" + mCount + " mHeld=" + mHeld + ")";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800327 }
328 }
329
330 private final class BatteryReceiver extends BroadcastReceiver {
331 @Override
332 public void onReceive(Context context, Intent intent) {
333 synchronized (mLocks) {
334 boolean wasPowered = mIsPowered;
335 mIsPowered = mBatteryService.isPowered();
336
337 if (mIsPowered != wasPowered) {
338 // update mStayOnWhilePluggedIn wake lock
339 updateWakeLockLocked();
340
341 // treat plugging and unplugging the devices as a user activity.
342 // users find it disconcerting when they unplug the device
343 // and it shuts off right away.
344 // temporarily set mUserActivityAllowed to true so this will work
345 // even when the keyguard is on.
346 synchronized (mLocks) {
Mike Lockwood200b30b2009-09-20 00:23:59 -0400347 forceUserActivityLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800348 }
349 }
350 }
351 }
352 }
353
Mike Lockwood2d7bb812009-11-15 18:12:22 -0500354 private final class BootCompletedReceiver extends BroadcastReceiver {
355 @Override
356 public void onReceive(Context context, Intent intent) {
357 bootCompleted();
358 }
359 }
360
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800361 /**
362 * Set the setting that determines whether the device stays on when plugged in.
363 * The argument is a bit string, with each bit specifying a power source that,
364 * when the device is connected to that source, causes the device to stay on.
365 * See {@link android.os.BatteryManager} for the list of power sources that
366 * can be specified. Current values include {@link android.os.BatteryManager#BATTERY_PLUGGED_AC}
367 * and {@link android.os.BatteryManager#BATTERY_PLUGGED_USB}
368 * @param val an {@code int} containing the bits that specify which power sources
369 * should cause the device to stay on.
370 */
371 public void setStayOnSetting(int val) {
372 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SETTINGS, null);
373 Settings.System.putInt(mContext.getContentResolver(),
374 Settings.System.STAY_ON_WHILE_PLUGGED_IN, val);
375 }
376
377 private class SettingsObserver implements Observer {
378 private int getInt(String name) {
379 return mSettings.getValues(name).getAsInteger(Settings.System.VALUE);
380 }
381
382 public void update(Observable o, Object arg) {
383 synchronized (mLocks) {
384 // STAY_ON_WHILE_PLUGGED_IN
385 mStayOnConditions = getInt(STAY_ON_WHILE_PLUGGED_IN);
386 updateWakeLockLocked();
387
388 // SCREEN_OFF_TIMEOUT
389 mTotalDelaySetting = getInt(SCREEN_OFF_TIMEOUT);
390
391 // DIM_SCREEN
392 //mDimScreen = getInt(DIM_SCREEN) != 0;
393
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700394 // SCREEN_BRIGHTNESS_MODE
395 setScreenBrightnessMode(getInt(SCREEN_BRIGHTNESS_MODE));
396
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800397 // recalculate everything
398 setScreenOffTimeoutsLocked();
399 }
400 }
401 }
402
403 PowerManagerService()
404 {
405 // Hack to get our uid... should have a func for this.
406 long token = Binder.clearCallingIdentity();
407 MY_UID = Binder.getCallingUid();
408 Binder.restoreCallingIdentity(token);
409
410 // XXX remove this when the kernel doesn't timeout wake locks
411 Power.setLastUserActivityTimeout(7*24*3600*1000); // one week
412
413 // assume nothing is on yet
414 mUserState = mPowerState = 0;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800415
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800416 // Add ourself to the Watchdog monitors.
417 Watchdog.getInstance().addMonitor(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800418 }
419
420 private ContentQueryMap mSettings;
421
Mike Lockwood3a322132009-11-24 00:30:52 -0500422 void init(Context context, LightsService lights, IActivityManager activity,
The Android Open Source Project10592532009-03-18 17:39:46 -0700423 BatteryService battery) {
Mike Lockwood3a322132009-11-24 00:30:52 -0500424 mLightsService = lights;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800425 mContext = context;
426 mActivityService = activity;
427 mBatteryStats = BatteryStatsService.getService();
428 mBatteryService = battery;
429
Mike Lockwood3cb67a32009-11-27 14:25:58 -0500430 mLcdLight = lights.getLight(LightsService.LIGHT_ID_BACKLIGHT);
431 mButtonLight = lights.getLight(LightsService.LIGHT_ID_BUTTONS);
432 mKeyboardLight = lights.getLight(LightsService.LIGHT_ID_KEYBOARD);
433 mAttentionLight = lights.getLight(LightsService.LIGHT_ID_ATTENTION);
434
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800435 mHandlerThread = new HandlerThread("PowerManagerService") {
436 @Override
437 protected void onLooperPrepared() {
438 super.onLooperPrepared();
439 initInThread();
440 }
441 };
442 mHandlerThread.start();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800443
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800444 synchronized (mHandlerThread) {
445 while (!mInitComplete) {
446 try {
447 mHandlerThread.wait();
448 } catch (InterruptedException e) {
449 // Ignore
450 }
451 }
452 }
453 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800454
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800455 void initInThread() {
456 mHandler = new Handler();
457
458 mBroadcastWakeLock = new UnsynchronizedWakeLock(
Joe Onorato128e7292009-03-24 18:41:31 -0700459 PowerManager.PARTIAL_WAKE_LOCK, "sleep_broadcast", true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800460 mStayOnWhilePluggedInScreenDimLock = new UnsynchronizedWakeLock(
461 PowerManager.SCREEN_DIM_WAKE_LOCK, "StayOnWhilePluggedIn Screen Dim", false);
462 mStayOnWhilePluggedInPartialLock = new UnsynchronizedWakeLock(
463 PowerManager.PARTIAL_WAKE_LOCK, "StayOnWhilePluggedIn Partial", false);
464 mPreventScreenOnPartialLock = new UnsynchronizedWakeLock(
465 PowerManager.PARTIAL_WAKE_LOCK, "PreventScreenOn Partial", false);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500466 mProximityPartialLock = new UnsynchronizedWakeLock(
467 PowerManager.PARTIAL_WAKE_LOCK, "Proximity Partial", false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800468
469 mScreenOnIntent = new Intent(Intent.ACTION_SCREEN_ON);
470 mScreenOnIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
471 mScreenOffIntent = new Intent(Intent.ACTION_SCREEN_OFF);
472 mScreenOffIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
473
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700474 Resources resources = mContext.getResources();
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400475
476 // read settings for auto-brightness
477 mUseSoftwareAutoBrightness = resources.getBoolean(
478 com.android.internal.R.bool.config_automatic_brightness_available);
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400479 if (mUseSoftwareAutoBrightness) {
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700480 mAutoBrightnessLevels = resources.getIntArray(
481 com.android.internal.R.array.config_autoBrightnessLevels);
482 mLcdBacklightValues = resources.getIntArray(
483 com.android.internal.R.array.config_autoBrightnessLcdBacklightValues);
484 mButtonBacklightValues = resources.getIntArray(
485 com.android.internal.R.array.config_autoBrightnessButtonBacklightValues);
486 mKeyboardBacklightValues = resources.getIntArray(
487 com.android.internal.R.array.config_autoBrightnessKeyboardBacklightValues);
Mike Lockwood20ee6f22009-11-07 20:33:47 -0500488 mLightSensorWarmupTime = resources.getInteger(
489 com.android.internal.R.integer.config_lightSensorWarmupTime);
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700490 }
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700491
492 ContentResolver resolver = mContext.getContentResolver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800493 Cursor settingsCursor = resolver.query(Settings.System.CONTENT_URI, null,
494 "(" + Settings.System.NAME + "=?) or ("
495 + Settings.System.NAME + "=?) or ("
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700496 + Settings.System.NAME + "=?) or ("
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800497 + Settings.System.NAME + "=?)",
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700498 new String[]{STAY_ON_WHILE_PLUGGED_IN, SCREEN_OFF_TIMEOUT, DIM_SCREEN,
499 SCREEN_BRIGHTNESS_MODE},
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800500 null);
501 mSettings = new ContentQueryMap(settingsCursor, Settings.System.NAME, true, mHandler);
502 SettingsObserver settingsObserver = new SettingsObserver();
503 mSettings.addObserver(settingsObserver);
504
505 // pretend that the settings changed so we will get their initial state
506 settingsObserver.update(mSettings, null);
507
508 // register for the battery changed notifications
509 IntentFilter filter = new IntentFilter();
510 filter.addAction(Intent.ACTION_BATTERY_CHANGED);
511 mContext.registerReceiver(new BatteryReceiver(), filter);
Mike Lockwood2d7bb812009-11-15 18:12:22 -0500512 filter = new IntentFilter();
513 filter.addAction(Intent.ACTION_BOOT_COMPLETED);
514 mContext.registerReceiver(new BootCompletedReceiver(), filter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800515
516 // Listen for Gservices changes
517 IntentFilter gservicesChangedFilter =
518 new IntentFilter(Settings.Gservices.CHANGED_ACTION);
519 mContext.registerReceiver(new GservicesChangedReceiver(), gservicesChangedFilter);
520 // And explicitly do the initial update of our cached settings
521 updateGservicesValues();
522
Mike Lockwood4984e732009-11-01 08:16:33 -0500523 if (mUseSoftwareAutoBrightness) {
Mike Lockwood6c97fca2009-10-20 08:10:00 -0400524 // turn the screen on
525 setPowerState(SCREEN_BRIGHT);
526 } else {
527 // turn everything on
528 setPowerState(ALL_BRIGHT);
529 }
Dan Murphy951764b2009-08-27 14:59:03 -0500530
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800531 synchronized (mHandlerThread) {
532 mInitComplete = true;
533 mHandlerThread.notifyAll();
534 }
535 }
536
537 private class WakeLock implements IBinder.DeathRecipient
538 {
539 WakeLock(int f, IBinder b, String t, int u) {
540 super();
541 flags = f;
542 binder = b;
543 tag = t;
544 uid = u == MY_UID ? Process.SYSTEM_UID : u;
545 if (u != MY_UID || (
546 !"KEEP_SCREEN_ON_FLAG".equals(tag)
547 && !"KeyInputQueue".equals(tag))) {
548 monitorType = (f & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK
549 ? BatteryStats.WAKE_TYPE_PARTIAL
550 : BatteryStats.WAKE_TYPE_FULL;
551 } else {
552 monitorType = -1;
553 }
554 try {
555 b.linkToDeath(this, 0);
556 } catch (RemoteException e) {
557 binderDied();
558 }
559 }
560 public void binderDied() {
561 synchronized (mLocks) {
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500562 releaseWakeLockLocked(this.binder, 0, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800563 }
564 }
565 final int flags;
566 final IBinder binder;
567 final String tag;
568 final int uid;
569 final int monitorType;
570 boolean activated = true;
571 int minState;
572 }
573
574 private void updateWakeLockLocked() {
575 if (mStayOnConditions != 0 && mBatteryService.isPowered(mStayOnConditions)) {
576 // keep the device on if we're plugged in and mStayOnWhilePluggedIn is set.
577 mStayOnWhilePluggedInScreenDimLock.acquire();
578 mStayOnWhilePluggedInPartialLock.acquire();
579 } else {
580 mStayOnWhilePluggedInScreenDimLock.release();
581 mStayOnWhilePluggedInPartialLock.release();
582 }
583 }
584
585 private boolean isScreenLock(int flags)
586 {
587 int n = flags & LOCK_MASK;
588 return n == PowerManager.FULL_WAKE_LOCK
589 || n == PowerManager.SCREEN_BRIGHT_WAKE_LOCK
590 || n == PowerManager.SCREEN_DIM_WAKE_LOCK;
591 }
592
593 public void acquireWakeLock(int flags, IBinder lock, String tag) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800594 int uid = Binder.getCallingUid();
Michael Chane96440f2009-05-06 10:27:36 -0700595 if (uid != Process.myUid()) {
596 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
597 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800598 long ident = Binder.clearCallingIdentity();
599 try {
600 synchronized (mLocks) {
601 acquireWakeLockLocked(flags, lock, uid, tag);
602 }
603 } finally {
604 Binder.restoreCallingIdentity(ident);
605 }
606 }
607
608 public void acquireWakeLockLocked(int flags, IBinder lock, int uid, String tag) {
609 int acquireUid = -1;
610 String acquireName = null;
611 int acquireType = -1;
612
613 if (mSpew) {
614 Log.d(TAG, "acquireWakeLock flags=0x" + Integer.toHexString(flags) + " tag=" + tag);
615 }
616
617 int index = mLocks.getIndex(lock);
618 WakeLock wl;
619 boolean newlock;
620 if (index < 0) {
621 wl = new WakeLock(flags, lock, tag, uid);
622 switch (wl.flags & LOCK_MASK)
623 {
624 case PowerManager.FULL_WAKE_LOCK:
Mike Lockwood4984e732009-11-01 08:16:33 -0500625 if (mUseSoftwareAutoBrightness) {
Mike Lockwood3333fa42009-10-26 14:50:42 -0400626 wl.minState = SCREEN_BRIGHT;
627 } else {
628 wl.minState = (mKeyboardVisible ? ALL_BRIGHT : SCREEN_BUTTON_BRIGHT);
629 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800630 break;
631 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
632 wl.minState = SCREEN_BRIGHT;
633 break;
634 case PowerManager.SCREEN_DIM_WAKE_LOCK:
635 wl.minState = SCREEN_DIM;
636 break;
637 case PowerManager.PARTIAL_WAKE_LOCK:
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700638 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800639 break;
640 default:
641 // just log and bail. we're in the server, so don't
642 // throw an exception.
643 Log.e(TAG, "bad wakelock type for lock '" + tag + "' "
644 + " flags=" + flags);
645 return;
646 }
647 mLocks.addLock(wl);
648 newlock = true;
649 } else {
650 wl = mLocks.get(index);
651 newlock = false;
652 }
653 if (isScreenLock(flags)) {
654 // if this causes a wakeup, we reactivate all of the locks and
655 // set it to whatever they want. otherwise, we modulate that
656 // by the current state so we never turn it more on than
657 // it already is.
658 if ((wl.flags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) {
Michael Chane96440f2009-05-06 10:27:36 -0700659 int oldWakeLockState = mWakeLockState;
660 mWakeLockState = mLocks.reactivateScreenLocksLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800661 if (mSpew) {
662 Log.d(TAG, "wakeup here mUserState=0x" + Integer.toHexString(mUserState)
Michael Chane96440f2009-05-06 10:27:36 -0700663 + " mWakeLockState=0x"
664 + Integer.toHexString(mWakeLockState)
665 + " previous wakeLockState=0x" + Integer.toHexString(oldWakeLockState));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800666 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800667 } else {
668 if (mSpew) {
669 Log.d(TAG, "here mUserState=0x" + Integer.toHexString(mUserState)
670 + " mLocks.gatherState()=0x"
671 + Integer.toHexString(mLocks.gatherState())
672 + " mWakeLockState=0x" + Integer.toHexString(mWakeLockState));
673 }
674 mWakeLockState = (mUserState | mWakeLockState) & mLocks.gatherState();
675 }
676 setPowerState(mWakeLockState | mUserState);
677 }
678 else if ((flags & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK) {
679 if (newlock) {
680 mPartialCount++;
681 if (mPartialCount == 1) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800682 if (LOG_PARTIAL_WL) EventLog.writeEvent(EventLogTags.POWER_PARTIAL_WAKE_STATE, 1, tag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800683 }
684 }
685 Power.acquireWakeLock(Power.PARTIAL_WAKE_LOCK,PARTIAL_NAME);
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700686 } else if ((flags & LOCK_MASK) == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK) {
Mike Lockwoodee2b0942009-11-09 14:09:02 -0500687 mProximityWakeLockCount++;
688 if (mProximityWakeLockCount == 1) {
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700689 enableProximityLockLocked();
690 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800691 }
692 if (newlock) {
693 acquireUid = wl.uid;
694 acquireName = wl.tag;
695 acquireType = wl.monitorType;
696 }
697
698 if (acquireType >= 0) {
699 try {
700 mBatteryStats.noteStartWakelock(acquireUid, acquireName, acquireType);
701 } catch (RemoteException e) {
702 // Ignore
703 }
704 }
705 }
706
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500707 public void releaseWakeLock(IBinder lock, int flags) {
Michael Chane96440f2009-05-06 10:27:36 -0700708 int uid = Binder.getCallingUid();
709 if (uid != Process.myUid()) {
710 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
711 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800712
713 synchronized (mLocks) {
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500714 releaseWakeLockLocked(lock, flags, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800715 }
716 }
717
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500718 private void releaseWakeLockLocked(IBinder lock, int flags, boolean death) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800719 int releaseUid;
720 String releaseName;
721 int releaseType;
722
723 WakeLock wl = mLocks.removeLock(lock);
724 if (wl == null) {
725 return;
726 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800727
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800728 if (mSpew) {
729 Log.d(TAG, "releaseWakeLock flags=0x"
730 + Integer.toHexString(wl.flags) + " tag=" + wl.tag);
731 }
732
733 if (isScreenLock(wl.flags)) {
734 mWakeLockState = mLocks.gatherState();
735 // goes in the middle to reduce flicker
736 if ((wl.flags & PowerManager.ON_AFTER_RELEASE) != 0) {
737 userActivity(SystemClock.uptimeMillis(), false);
738 }
739 setPowerState(mWakeLockState | mUserState);
740 }
741 else if ((wl.flags & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK) {
742 mPartialCount--;
743 if (mPartialCount == 0) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800744 if (LOG_PARTIAL_WL) EventLog.writeEvent(EventLogTags.POWER_PARTIAL_WAKE_STATE, 0, wl.tag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800745 Power.releaseWakeLock(PARTIAL_NAME);
746 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700747 } else if ((wl.flags & LOCK_MASK) == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK) {
Mike Lockwoodee2b0942009-11-09 14:09:02 -0500748 mProximityWakeLockCount--;
749 if (mProximityWakeLockCount == 0) {
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500750 if (mProximitySensorActive &&
751 ((flags & PowerManager.WAIT_FOR_PROXIMITY_NEGATIVE) != 0)) {
Mike Lockwoodee2b0942009-11-09 14:09:02 -0500752 // wait for proximity sensor to go negative before disabling sensor
753 if (mDebugProximitySensor) {
754 Log.d(TAG, "waiting for proximity sensor to go negative");
755 }
756 } else {
757 disableProximityLockLocked();
758 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700759 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800760 }
761 // Unlink the lock from the binder.
762 wl.binder.unlinkToDeath(wl, 0);
763 releaseUid = wl.uid;
764 releaseName = wl.tag;
765 releaseType = wl.monitorType;
766
767 if (releaseType >= 0) {
768 long origId = Binder.clearCallingIdentity();
769 try {
770 mBatteryStats.noteStopWakelock(releaseUid, releaseName, releaseType);
771 } catch (RemoteException e) {
772 // Ignore
773 } finally {
774 Binder.restoreCallingIdentity(origId);
775 }
776 }
777 }
778
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800779 private class PokeLock implements IBinder.DeathRecipient
780 {
781 PokeLock(int p, IBinder b, String t) {
782 super();
783 this.pokey = p;
784 this.binder = b;
785 this.tag = t;
786 try {
787 b.linkToDeath(this, 0);
788 } catch (RemoteException e) {
789 binderDied();
790 }
791 }
792 public void binderDied() {
793 setPokeLock(0, this.binder, this.tag);
794 }
795 int pokey;
796 IBinder binder;
797 String tag;
798 boolean awakeOnSet;
799 }
800
801 public void setPokeLock(int pokey, IBinder token, String tag) {
802 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
803 if (token == null) {
804 Log.e(TAG, "setPokeLock got null token for tag='" + tag + "'");
805 return;
806 }
807
808 if ((pokey & POKE_LOCK_TIMEOUT_MASK) == POKE_LOCK_TIMEOUT_MASK) {
809 throw new IllegalArgumentException("setPokeLock can't have both POKE_LOCK_SHORT_TIMEOUT"
810 + " and POKE_LOCK_MEDIUM_TIMEOUT");
811 }
812
813 synchronized (mLocks) {
814 if (pokey != 0) {
815 PokeLock p = mPokeLocks.get(token);
816 int oldPokey = 0;
817 if (p != null) {
818 oldPokey = p.pokey;
819 p.pokey = pokey;
820 } else {
821 p = new PokeLock(pokey, token, tag);
822 mPokeLocks.put(token, p);
823 }
824 int oldTimeout = oldPokey & POKE_LOCK_TIMEOUT_MASK;
825 int newTimeout = pokey & POKE_LOCK_TIMEOUT_MASK;
826 if (((mPowerState & SCREEN_ON_BIT) == 0) && (oldTimeout != newTimeout)) {
827 p.awakeOnSet = true;
828 }
829 } else {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -0700830 PokeLock rLock = mPokeLocks.remove(token);
831 if (rLock != null) {
832 token.unlinkToDeath(rLock, 0);
833 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800834 }
835
836 int oldPokey = mPokey;
837 int cumulative = 0;
838 boolean oldAwakeOnSet = mPokeAwakeOnSet;
839 boolean awakeOnSet = false;
840 for (PokeLock p: mPokeLocks.values()) {
841 cumulative |= p.pokey;
842 if (p.awakeOnSet) {
843 awakeOnSet = true;
844 }
845 }
846 mPokey = cumulative;
847 mPokeAwakeOnSet = awakeOnSet;
848
849 int oldCumulativeTimeout = oldPokey & POKE_LOCK_TIMEOUT_MASK;
850 int newCumulativeTimeout = pokey & POKE_LOCK_TIMEOUT_MASK;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800851
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800852 if (oldCumulativeTimeout != newCumulativeTimeout) {
853 setScreenOffTimeoutsLocked();
854 // reset the countdown timer, but use the existing nextState so it doesn't
855 // change anything
856 setTimeoutLocked(SystemClock.uptimeMillis(), mTimeoutTask.nextState);
857 }
858 }
859 }
860
861 private static String lockType(int type)
862 {
863 switch (type)
864 {
865 case PowerManager.FULL_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -0700866 return "FULL_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800867 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -0700868 return "SCREEN_BRIGHT_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800869 case PowerManager.SCREEN_DIM_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -0700870 return "SCREEN_DIM_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800871 case PowerManager.PARTIAL_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -0700872 return "PARTIAL_WAKE_LOCK ";
873 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
874 return "PROXIMITY_SCREEN_OFF_WAKE_LOCK";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800875 default:
David Brown251faa62009-08-02 22:04:36 -0700876 return "??? ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800877 }
878 }
879
880 private static String dumpPowerState(int state) {
881 return (((state & KEYBOARD_BRIGHT_BIT) != 0)
882 ? "KEYBOARD_BRIGHT_BIT " : "")
883 + (((state & SCREEN_BRIGHT_BIT) != 0)
884 ? "SCREEN_BRIGHT_BIT " : "")
885 + (((state & SCREEN_ON_BIT) != 0)
886 ? "SCREEN_ON_BIT " : "")
887 + (((state & BATTERY_LOW_BIT) != 0)
888 ? "BATTERY_LOW_BIT " : "");
889 }
890
891 @Override
892 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
893 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
894 != PackageManager.PERMISSION_GRANTED) {
895 pw.println("Permission Denial: can't dump PowerManager from from pid="
896 + Binder.getCallingPid()
897 + ", uid=" + Binder.getCallingUid());
898 return;
899 }
900
901 long now = SystemClock.uptimeMillis();
902
903 pw.println("Power Manager State:");
904 pw.println(" mIsPowered=" + mIsPowered
905 + " mPowerState=" + mPowerState
906 + " mScreenOffTime=" + (SystemClock.elapsedRealtime()-mScreenOffTime)
907 + " ms");
908 pw.println(" mPartialCount=" + mPartialCount);
909 pw.println(" mWakeLockState=" + dumpPowerState(mWakeLockState));
910 pw.println(" mUserState=" + dumpPowerState(mUserState));
911 pw.println(" mPowerState=" + dumpPowerState(mPowerState));
912 pw.println(" mLocks.gather=" + dumpPowerState(mLocks.gatherState()));
913 pw.println(" mNextTimeout=" + mNextTimeout + " now=" + now
914 + " " + ((mNextTimeout-now)/1000) + "s from now");
915 pw.println(" mDimScreen=" + mDimScreen
916 + " mStayOnConditions=" + mStayOnConditions);
Mike Lockwood435eb642009-12-03 08:40:18 -0500917 pw.println(" mScreenOffReason=" + mScreenOffReason
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800918 + " mUserState=" + mUserState);
Joe Onorato128e7292009-03-24 18:41:31 -0700919 pw.println(" mBroadcastQueue={" + mBroadcastQueue[0] + ',' + mBroadcastQueue[1]
920 + ',' + mBroadcastQueue[2] + "}");
921 pw.println(" mBroadcastWhy={" + mBroadcastWhy[0] + ',' + mBroadcastWhy[1]
922 + ',' + mBroadcastWhy[2] + "}");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800923 pw.println(" mPokey=" + mPokey + " mPokeAwakeonSet=" + mPokeAwakeOnSet);
924 pw.println(" mKeyboardVisible=" + mKeyboardVisible
925 + " mUserActivityAllowed=" + mUserActivityAllowed);
926 pw.println(" mKeylightDelay=" + mKeylightDelay + " mDimDelay=" + mDimDelay
927 + " mScreenOffDelay=" + mScreenOffDelay);
928 pw.println(" mPreventScreenOn=" + mPreventScreenOn
Mike Lockwoodfb73f792009-11-20 11:31:18 -0500929 + " mScreenBrightnessOverride=" + mScreenBrightnessOverride
930 + " mButtonBrightnessOverride=" + mButtonBrightnessOverride);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800931 pw.println(" mTotalDelaySetting=" + mTotalDelaySetting);
Mike Lockwood20ee6f22009-11-07 20:33:47 -0500932 pw.println(" mLastScreenOnTime=" + mLastScreenOnTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800933 pw.println(" mBroadcastWakeLock=" + mBroadcastWakeLock);
934 pw.println(" mStayOnWhilePluggedInScreenDimLock=" + mStayOnWhilePluggedInScreenDimLock);
935 pw.println(" mStayOnWhilePluggedInPartialLock=" + mStayOnWhilePluggedInPartialLock);
936 pw.println(" mPreventScreenOnPartialLock=" + mPreventScreenOnPartialLock);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500937 pw.println(" mProximityPartialLock=" + mProximityPartialLock);
Mike Lockwoodee2b0942009-11-09 14:09:02 -0500938 pw.println(" mProximityWakeLockCount=" + mProximityWakeLockCount);
939 pw.println(" mProximitySensorEnabled=" + mProximitySensorEnabled);
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700940 pw.println(" mProximitySensorActive=" + mProximitySensorActive);
Mike Lockwood20f87d72009-11-05 16:08:51 -0500941 pw.println(" mProximityPendingValue=" + mProximityPendingValue);
942 pw.println(" mLastProximityEventTime=" + mLastProximityEventTime);
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700943 pw.println(" mLightSensorEnabled=" + mLightSensorEnabled);
Mike Lockwoodfb73f792009-11-20 11:31:18 -0500944 pw.println(" mLightSensorValue=" + mLightSensorValue
945 + " mLightSensorPendingValue=" + mLightSensorPendingValue);
946 pw.println(" mLightSensorScreenBrightness=" + mLightSensorScreenBrightness
947 + " mLightSensorButtonBrightness=" + mLightSensorButtonBrightness
948 + " mLightSensorKeyboardBrightness=" + mLightSensorKeyboardBrightness);
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400949 pw.println(" mUseSoftwareAutoBrightness=" + mUseSoftwareAutoBrightness);
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700950 pw.println(" mAutoBrightessEnabled=" + mAutoBrightessEnabled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800951 mScreenBrightness.dump(pw, " mScreenBrightness: ");
952 mKeyboardBrightness.dump(pw, " mKeyboardBrightness: ");
953 mButtonBrightness.dump(pw, " mButtonBrightness: ");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800954
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800955 int N = mLocks.size();
956 pw.println();
957 pw.println("mLocks.size=" + N + ":");
958 for (int i=0; i<N; i++) {
959 WakeLock wl = mLocks.get(i);
960 String type = lockType(wl.flags & LOCK_MASK);
961 String acquireCausesWakeup = "";
962 if ((wl.flags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) {
963 acquireCausesWakeup = "ACQUIRE_CAUSES_WAKEUP ";
964 }
965 String activated = "";
966 if (wl.activated) {
967 activated = " activated";
968 }
969 pw.println(" " + type + " '" + wl.tag + "'" + acquireCausesWakeup
970 + activated + " (minState=" + wl.minState + ")");
971 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800972
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800973 pw.println();
974 pw.println("mPokeLocks.size=" + mPokeLocks.size() + ":");
975 for (PokeLock p: mPokeLocks.values()) {
976 pw.println(" poke lock '" + p.tag + "':"
977 + ((p.pokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0
978 ? " POKE_LOCK_IGNORE_CHEEK_EVENTS" : "")
Joe Onoratoe68ffcb2009-03-24 19:11:13 -0700979 + ((p.pokey & POKE_LOCK_IGNORE_TOUCH_AND_CHEEK_EVENTS) != 0
980 ? " POKE_LOCK_IGNORE_TOUCH_AND_CHEEK_EVENTS" : "")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800981 + ((p.pokey & POKE_LOCK_SHORT_TIMEOUT) != 0
982 ? " POKE_LOCK_SHORT_TIMEOUT" : "")
983 + ((p.pokey & POKE_LOCK_MEDIUM_TIMEOUT) != 0
984 ? " POKE_LOCK_MEDIUM_TIMEOUT" : ""));
985 }
986
987 pw.println();
988 }
989
990 private void setTimeoutLocked(long now, int nextState)
991 {
Mike Lockwood2d7bb812009-11-15 18:12:22 -0500992 if (mBootCompleted) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800993 mHandler.removeCallbacks(mTimeoutTask);
994 mTimeoutTask.nextState = nextState;
995 long when = now;
996 switch (nextState)
997 {
998 case SCREEN_BRIGHT:
999 when += mKeylightDelay;
1000 break;
1001 case SCREEN_DIM:
1002 if (mDimDelay >= 0) {
1003 when += mDimDelay;
1004 break;
1005 } else {
1006 Log.w(TAG, "mDimDelay=" + mDimDelay + " while trying to dim");
1007 }
1008 case SCREEN_OFF:
1009 synchronized (mLocks) {
1010 when += mScreenOffDelay;
1011 }
1012 break;
1013 }
1014 if (mSpew) {
1015 Log.d(TAG, "setTimeoutLocked now=" + now + " nextState=" + nextState
1016 + " when=" + when);
1017 }
1018 mHandler.postAtTime(mTimeoutTask, when);
1019 mNextTimeout = when; // for debugging
1020 }
1021 }
1022
1023 private void cancelTimerLocked()
1024 {
1025 mHandler.removeCallbacks(mTimeoutTask);
1026 mTimeoutTask.nextState = -1;
1027 }
1028
1029 private class TimeoutTask implements Runnable
1030 {
1031 int nextState; // access should be synchronized on mLocks
1032 public void run()
1033 {
1034 synchronized (mLocks) {
1035 if (mSpew) {
1036 Log.d(TAG, "user activity timeout timed out nextState=" + this.nextState);
1037 }
1038
1039 if (nextState == -1) {
1040 return;
1041 }
1042
1043 mUserState = this.nextState;
1044 setPowerState(this.nextState | mWakeLockState);
1045
1046 long now = SystemClock.uptimeMillis();
1047
1048 switch (this.nextState)
1049 {
1050 case SCREEN_BRIGHT:
1051 if (mDimDelay >= 0) {
1052 setTimeoutLocked(now, SCREEN_DIM);
1053 break;
1054 }
1055 case SCREEN_DIM:
1056 setTimeoutLocked(now, SCREEN_OFF);
1057 break;
1058 }
1059 }
1060 }
1061 }
1062
1063 private void sendNotificationLocked(boolean on, int why)
1064 {
Joe Onorato64c62ba2009-03-24 20:13:57 -07001065 if (!on) {
1066 mStillNeedSleepNotification = false;
1067 }
1068
Joe Onorato128e7292009-03-24 18:41:31 -07001069 // Add to the queue.
1070 int index = 0;
1071 while (mBroadcastQueue[index] != -1) {
1072 index++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001073 }
Joe Onorato128e7292009-03-24 18:41:31 -07001074 mBroadcastQueue[index] = on ? 1 : 0;
1075 mBroadcastWhy[index] = why;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001076
Joe Onorato128e7292009-03-24 18:41:31 -07001077 // If we added it position 2, then there is a pair that can be stripped.
1078 // If we added it position 1 and we're turning the screen off, we can strip
1079 // the pair and do nothing, because the screen is already off, and therefore
1080 // keyguard has already been enabled.
1081 // However, if we added it at position 1 and we're turning it on, then position
1082 // 0 was to turn it off, and we can't strip that, because keyguard needs to come
1083 // on, so have to run the queue then.
1084 if (index == 2) {
1085 // Also, while we're collapsing them, if it's going to be an "off," and one
1086 // is off because of user, then use that, regardless of whether it's the first
1087 // or second one.
1088 if (!on && why == WindowManagerPolicy.OFF_BECAUSE_OF_USER) {
1089 mBroadcastWhy[0] = WindowManagerPolicy.OFF_BECAUSE_OF_USER;
1090 }
1091 mBroadcastQueue[0] = on ? 1 : 0;
1092 mBroadcastQueue[1] = -1;
1093 mBroadcastQueue[2] = -1;
1094 index = 0;
1095 }
1096 if (index == 1 && !on) {
1097 mBroadcastQueue[0] = -1;
1098 mBroadcastQueue[1] = -1;
1099 index = -1;
1100 // The wake lock was being held, but we're not actually going to do any
1101 // broadcasts, so release the wake lock.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001102 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP, 1, mBroadcastWakeLock.mCount);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001103 mBroadcastWakeLock.release();
Joe Onorato128e7292009-03-24 18:41:31 -07001104 }
1105
1106 // Now send the message.
1107 if (index >= 0) {
1108 // Acquire the broadcast wake lock before changing the power
1109 // state. It will be release after the broadcast is sent.
1110 // We always increment the ref count for each notification in the queue
1111 // and always decrement when that notification is handled.
1112 mBroadcastWakeLock.acquire();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001113 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_SEND, mBroadcastWakeLock.mCount);
Joe Onorato128e7292009-03-24 18:41:31 -07001114 mHandler.post(mNotificationTask);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001115 }
1116 }
1117
1118 private Runnable mNotificationTask = new Runnable()
1119 {
1120 public void run()
1121 {
Joe Onorato128e7292009-03-24 18:41:31 -07001122 while (true) {
1123 int value;
1124 int why;
1125 WindowManagerPolicy policy;
1126 synchronized (mLocks) {
1127 value = mBroadcastQueue[0];
1128 why = mBroadcastWhy[0];
1129 for (int i=0; i<2; i++) {
1130 mBroadcastQueue[i] = mBroadcastQueue[i+1];
1131 mBroadcastWhy[i] = mBroadcastWhy[i+1];
1132 }
1133 policy = getPolicyLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001134 }
Joe Onorato128e7292009-03-24 18:41:31 -07001135 if (value == 1) {
1136 mScreenOnStart = SystemClock.uptimeMillis();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001137
Joe Onorato128e7292009-03-24 18:41:31 -07001138 policy.screenTurnedOn();
1139 try {
1140 ActivityManagerNative.getDefault().wakingUp();
1141 } catch (RemoteException e) {
1142 // ignore it
1143 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001144
Joe Onorato128e7292009-03-24 18:41:31 -07001145 if (mSpew) {
1146 Log.d(TAG, "mBroadcastWakeLock=" + mBroadcastWakeLock);
1147 }
1148 if (mContext != null && ActivityManagerNative.isSystemReady()) {
1149 mContext.sendOrderedBroadcast(mScreenOnIntent, null,
1150 mScreenOnBroadcastDone, mHandler, 0, null, null);
1151 } else {
1152 synchronized (mLocks) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001153 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP, 2,
Joe Onorato128e7292009-03-24 18:41:31 -07001154 mBroadcastWakeLock.mCount);
1155 mBroadcastWakeLock.release();
1156 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001157 }
1158 }
Joe Onorato128e7292009-03-24 18:41:31 -07001159 else if (value == 0) {
1160 mScreenOffStart = SystemClock.uptimeMillis();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001161
Joe Onorato128e7292009-03-24 18:41:31 -07001162 policy.screenTurnedOff(why);
1163 try {
1164 ActivityManagerNative.getDefault().goingToSleep();
1165 } catch (RemoteException e) {
1166 // ignore it.
1167 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001168
Joe Onorato128e7292009-03-24 18:41:31 -07001169 if (mContext != null && ActivityManagerNative.isSystemReady()) {
1170 mContext.sendOrderedBroadcast(mScreenOffIntent, null,
1171 mScreenOffBroadcastDone, mHandler, 0, null, null);
1172 } else {
1173 synchronized (mLocks) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001174 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP, 3,
Joe Onorato128e7292009-03-24 18:41:31 -07001175 mBroadcastWakeLock.mCount);
1176 mBroadcastWakeLock.release();
1177 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001178 }
1179 }
Joe Onorato128e7292009-03-24 18:41:31 -07001180 else {
1181 // If we're in this case, then this handler is running for a previous
1182 // paired transaction. mBroadcastWakeLock will already have been released.
1183 break;
1184 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001185 }
1186 }
1187 };
1188
1189 long mScreenOnStart;
1190 private BroadcastReceiver mScreenOnBroadcastDone = new BroadcastReceiver() {
1191 public void onReceive(Context context, Intent intent) {
1192 synchronized (mLocks) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001193 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_DONE, 1,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001194 SystemClock.uptimeMillis() - mScreenOnStart, mBroadcastWakeLock.mCount);
1195 mBroadcastWakeLock.release();
1196 }
1197 }
1198 };
1199
1200 long mScreenOffStart;
1201 private BroadcastReceiver mScreenOffBroadcastDone = new BroadcastReceiver() {
1202 public void onReceive(Context context, Intent intent) {
1203 synchronized (mLocks) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001204 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_DONE, 0,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001205 SystemClock.uptimeMillis() - mScreenOffStart, mBroadcastWakeLock.mCount);
1206 mBroadcastWakeLock.release();
1207 }
1208 }
1209 };
1210
1211 void logPointerUpEvent() {
1212 if (LOG_TOUCH_DOWNS) {
1213 mTotalTouchDownTime += SystemClock.elapsedRealtime() - mLastTouchDown;
1214 mLastTouchDown = 0;
1215 }
1216 }
1217
1218 void logPointerDownEvent() {
1219 if (LOG_TOUCH_DOWNS) {
1220 // If we are not already timing a down/up sequence
1221 if (mLastTouchDown == 0) {
1222 mLastTouchDown = SystemClock.elapsedRealtime();
1223 mTouchCycles++;
1224 }
1225 }
1226 }
1227
1228 /**
1229 * Prevents the screen from turning on even if it *should* turn on due
1230 * to a subsequent full wake lock being acquired.
1231 * <p>
1232 * This is a temporary hack that allows an activity to "cover up" any
1233 * display glitches that happen during the activity's startup
1234 * sequence. (Specifically, this API was added to work around a
1235 * cosmetic bug in the "incoming call" sequence, where the lock screen
1236 * would flicker briefly before the incoming call UI became visible.)
1237 * TODO: There ought to be a more elegant way of doing this,
1238 * probably by having the PowerManager and ActivityManager
1239 * work together to let apps specify that the screen on/off
1240 * state should be synchronized with the Activity lifecycle.
1241 * <p>
1242 * Note that calling preventScreenOn(true) will NOT turn the screen
1243 * off if it's currently on. (This API only affects *future*
1244 * acquisitions of full wake locks.)
1245 * But calling preventScreenOn(false) WILL turn the screen on if
1246 * it's currently off because of a prior preventScreenOn(true) call.
1247 * <p>
1248 * Any call to preventScreenOn(true) MUST be followed promptly by a call
1249 * to preventScreenOn(false). In fact, if the preventScreenOn(false)
1250 * call doesn't occur within 5 seconds, we'll turn the screen back on
1251 * ourselves (and log a warning about it); this prevents a buggy app
1252 * from disabling the screen forever.)
1253 * <p>
1254 * TODO: this feature should really be controlled by a new type of poke
1255 * lock (rather than an IPowerManager call).
1256 */
1257 public void preventScreenOn(boolean prevent) {
1258 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1259
1260 synchronized (mLocks) {
1261 if (prevent) {
1262 // First of all, grab a partial wake lock to
1263 // make sure the CPU stays on during the entire
1264 // preventScreenOn(true) -> preventScreenOn(false) sequence.
1265 mPreventScreenOnPartialLock.acquire();
1266
1267 // Post a forceReenableScreen() call (for 5 seconds in the
1268 // future) to make sure the matching preventScreenOn(false) call
1269 // has happened by then.
1270 mHandler.removeCallbacks(mForceReenableScreenTask);
1271 mHandler.postDelayed(mForceReenableScreenTask, 5000);
1272
1273 // Finally, set the flag that prevents the screen from turning on.
1274 // (Below, in setPowerState(), we'll check mPreventScreenOn and
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001275 // we *won't* call setScreenStateLocked(true) if it's set.)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001276 mPreventScreenOn = true;
1277 } else {
1278 // (Re)enable the screen.
1279 mPreventScreenOn = false;
1280
1281 // We're "undoing" a the prior preventScreenOn(true) call, so we
1282 // no longer need the 5-second safeguard.
1283 mHandler.removeCallbacks(mForceReenableScreenTask);
1284
1285 // Forcibly turn on the screen if it's supposed to be on. (This
1286 // handles the case where the screen is currently off because of
1287 // a prior preventScreenOn(true) call.)
Mike Lockwoode090281422009-11-14 21:02:56 -05001288 if (!mProximitySensorActive && (mPowerState & SCREEN_ON_BIT) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001289 if (mSpew) {
1290 Log.d(TAG,
1291 "preventScreenOn: turning on after a prior preventScreenOn(true)!");
1292 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001293 int err = setScreenStateLocked(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001294 if (err != 0) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001295 Log.w(TAG, "preventScreenOn: error from setScreenStateLocked(): " + err);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001296 }
1297 }
1298
1299 // Release the partial wake lock that we held during the
1300 // preventScreenOn(true) -> preventScreenOn(false) sequence.
1301 mPreventScreenOnPartialLock.release();
1302 }
1303 }
1304 }
1305
1306 public void setScreenBrightnessOverride(int brightness) {
1307 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1308
1309 synchronized (mLocks) {
1310 if (mScreenBrightnessOverride != brightness) {
1311 mScreenBrightnessOverride = brightness;
1312 updateLightsLocked(mPowerState, SCREEN_ON_BIT);
1313 }
1314 }
1315 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001316
1317 public void setButtonBrightnessOverride(int brightness) {
1318 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1319
1320 synchronized (mLocks) {
1321 if (mButtonBrightnessOverride != brightness) {
1322 mButtonBrightnessOverride = brightness;
1323 updateLightsLocked(mPowerState, BUTTON_BRIGHT_BIT | KEYBOARD_BRIGHT_BIT);
1324 }
1325 }
1326 }
1327
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001328 /**
1329 * Sanity-check that gets called 5 seconds after any call to
1330 * preventScreenOn(true). This ensures that the original call
1331 * is followed promptly by a call to preventScreenOn(false).
1332 */
1333 private void forceReenableScreen() {
1334 // We shouldn't get here at all if mPreventScreenOn is false, since
1335 // we should have already removed any existing
1336 // mForceReenableScreenTask messages...
1337 if (!mPreventScreenOn) {
1338 Log.w(TAG, "forceReenableScreen: mPreventScreenOn is false, nothing to do");
1339 return;
1340 }
1341
1342 // Uh oh. It's been 5 seconds since a call to
1343 // preventScreenOn(true) and we haven't re-enabled the screen yet.
1344 // This means the app that called preventScreenOn(true) is either
1345 // slow (i.e. it took more than 5 seconds to call preventScreenOn(false)),
1346 // or buggy (i.e. it forgot to call preventScreenOn(false), or
1347 // crashed before doing so.)
1348
1349 // Log a warning, and forcibly turn the screen back on.
1350 Log.w(TAG, "App called preventScreenOn(true) but didn't promptly reenable the screen! "
1351 + "Forcing the screen back on...");
1352 preventScreenOn(false);
1353 }
1354
1355 private Runnable mForceReenableScreenTask = new Runnable() {
1356 public void run() {
1357 forceReenableScreen();
1358 }
1359 };
1360
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001361 private int setScreenStateLocked(boolean on) {
1362 int err = Power.setScreenState(on);
Mike Lockwood20ee6f22009-11-07 20:33:47 -05001363 if (err == 0) {
1364 mLastScreenOnTime = (on ? SystemClock.elapsedRealtime() : 0);
1365 if (mUseSoftwareAutoBrightness) {
1366 enableLightSensor(on);
1367 if (!on) {
1368 // make sure button and key backlights are off too
Mike Lockwood3cb67a32009-11-27 14:25:58 -05001369 mButtonLight.turnOff();
1370 mKeyboardLight.turnOff();
Mike Lockwood20ee6f22009-11-07 20:33:47 -05001371 // clear current value so we will update based on the new conditions
1372 // when the sensor is reenabled.
1373 mLightSensorValue = -1;
1374 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001375 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001376 }
1377 return err;
1378 }
1379
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001380 private void setPowerState(int state)
1381 {
Mike Lockwood435eb642009-12-03 08:40:18 -05001382 setPowerState(state, false, WindowManagerPolicy.OFF_BECAUSE_OF_TIMEOUT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001383 }
1384
Mike Lockwood435eb642009-12-03 08:40:18 -05001385 private void setPowerState(int newState, boolean noChangeLights, int reason)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001386 {
1387 synchronized (mLocks) {
1388 int err;
1389
1390 if (mSpew) {
1391 Log.d(TAG, "setPowerState: mPowerState=0x" + Integer.toHexString(mPowerState)
1392 + " newState=0x" + Integer.toHexString(newState)
Mike Lockwood435eb642009-12-03 08:40:18 -05001393 + " noChangeLights=" + noChangeLights
1394 + " reason=" + reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001395 }
1396
1397 if (noChangeLights) {
1398 newState = (newState & ~LIGHTS_MASK) | (mPowerState & LIGHTS_MASK);
1399 }
Mike Lockwood36fc3022009-08-25 16:49:06 -07001400 if (mProximitySensorActive) {
1401 // don't turn on the screen when the proximity sensor lock is held
1402 newState = (newState & ~SCREEN_BRIGHT);
1403 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001404
1405 if (batteryIsLow()) {
1406 newState |= BATTERY_LOW_BIT;
1407 } else {
1408 newState &= ~BATTERY_LOW_BIT;
1409 }
1410 if (newState == mPowerState) {
1411 return;
1412 }
Mike Lockwood3333fa42009-10-26 14:50:42 -04001413
Mike Lockwood2d7bb812009-11-15 18:12:22 -05001414 if (!mBootCompleted && !mUseSoftwareAutoBrightness) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001415 newState |= ALL_BRIGHT;
1416 }
1417
1418 boolean oldScreenOn = (mPowerState & SCREEN_ON_BIT) != 0;
1419 boolean newScreenOn = (newState & SCREEN_ON_BIT) != 0;
1420
Mike Lockwood51b84492009-11-16 21:51:18 -05001421 if (mSpew) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001422 Log.d(TAG, "setPowerState: mPowerState=" + mPowerState
1423 + " newState=" + newState + " noChangeLights=" + noChangeLights);
1424 Log.d(TAG, " oldKeyboardBright=" + ((mPowerState & KEYBOARD_BRIGHT_BIT) != 0)
1425 + " newKeyboardBright=" + ((newState & KEYBOARD_BRIGHT_BIT) != 0));
1426 Log.d(TAG, " oldScreenBright=" + ((mPowerState & SCREEN_BRIGHT_BIT) != 0)
1427 + " newScreenBright=" + ((newState & SCREEN_BRIGHT_BIT) != 0));
1428 Log.d(TAG, " oldButtonBright=" + ((mPowerState & BUTTON_BRIGHT_BIT) != 0)
1429 + " newButtonBright=" + ((newState & BUTTON_BRIGHT_BIT) != 0));
1430 Log.d(TAG, " oldScreenOn=" + oldScreenOn
1431 + " newScreenOn=" + newScreenOn);
1432 Log.d(TAG, " oldBatteryLow=" + ((mPowerState & BATTERY_LOW_BIT) != 0)
1433 + " newBatteryLow=" + ((newState & BATTERY_LOW_BIT) != 0));
1434 }
1435
1436 if (mPowerState != newState) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001437 updateLightsLocked(newState, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001438 mPowerState = (mPowerState & ~LIGHTS_MASK) | (newState & LIGHTS_MASK);
1439 }
1440
1441 if (oldScreenOn != newScreenOn) {
1442 if (newScreenOn) {
Joe Onorato128e7292009-03-24 18:41:31 -07001443 // When the user presses the power button, we need to always send out the
1444 // notification that it's going to sleep so the keyguard goes on. But
1445 // we can't do that until the screen fades out, so we don't show the keyguard
1446 // too early.
1447 if (mStillNeedSleepNotification) {
1448 sendNotificationLocked(false, WindowManagerPolicy.OFF_BECAUSE_OF_USER);
1449 }
1450
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001451 // Turn on the screen UNLESS there was a prior
1452 // preventScreenOn(true) request. (Note that the lifetime
1453 // of a single preventScreenOn() request is limited to 5
1454 // seconds to prevent a buggy app from disabling the
1455 // screen forever; see forceReenableScreen().)
1456 boolean reallyTurnScreenOn = true;
1457 if (mSpew) {
1458 Log.d(TAG, "- turning screen on... mPreventScreenOn = "
1459 + mPreventScreenOn);
1460 }
1461
1462 if (mPreventScreenOn) {
1463 if (mSpew) {
1464 Log.d(TAG, "- PREVENTING screen from really turning on!");
1465 }
1466 reallyTurnScreenOn = false;
1467 }
1468 if (reallyTurnScreenOn) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001469 err = setScreenStateLocked(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001470 long identity = Binder.clearCallingIdentity();
1471 try {
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001472 mBatteryStats.noteScreenBrightness(getPreferredBrightness());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001473 mBatteryStats.noteScreenOn();
1474 } catch (RemoteException e) {
1475 Log.w(TAG, "RemoteException calling noteScreenOn on BatteryStatsService", e);
1476 } finally {
1477 Binder.restoreCallingIdentity(identity);
1478 }
1479 } else {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001480 setScreenStateLocked(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001481 // But continue as if we really did turn the screen on...
1482 err = 0;
1483 }
1484
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001485 mLastTouchDown = 0;
1486 mTotalTouchDownTime = 0;
1487 mTouchCycles = 0;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001488 EventLog.writeEvent(EventLogTags.POWER_SCREEN_STATE, 1, reason,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001489 mTotalTouchDownTime, mTouchCycles);
1490 if (err == 0) {
1491 mPowerState |= SCREEN_ON_BIT;
1492 sendNotificationLocked(true, -1);
1493 }
1494 } else {
Mike Lockwood497087e32009-11-08 18:33:03 -05001495 // cancel light sensor task
1496 mHandler.removeCallbacks(mAutoBrightnessTask);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001497 mScreenOffTime = SystemClock.elapsedRealtime();
1498 long identity = Binder.clearCallingIdentity();
1499 try {
1500 mBatteryStats.noteScreenOff();
1501 } catch (RemoteException e) {
1502 Log.w(TAG, "RemoteException calling noteScreenOff on BatteryStatsService", e);
1503 } finally {
1504 Binder.restoreCallingIdentity(identity);
1505 }
1506 mPowerState &= ~SCREEN_ON_BIT;
Mike Lockwood435eb642009-12-03 08:40:18 -05001507 mScreenOffReason = reason;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001508 if (!mScreenBrightness.animating) {
Mike Lockwood435eb642009-12-03 08:40:18 -05001509 err = screenOffFinishedAnimatingLocked(reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001510 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001511 err = 0;
1512 mLastTouchDown = 0;
1513 }
1514 }
1515 }
1516 }
1517 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001518
Mike Lockwood435eb642009-12-03 08:40:18 -05001519 private int screenOffFinishedAnimatingLocked(int reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001520 // I don't think we need to check the current state here because all of these
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001521 // Power.setScreenState and sendNotificationLocked can both handle being
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001522 // called multiple times in the same state. -joeo
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001523 EventLog.writeEvent(EventLogTags.POWER_SCREEN_STATE, 0, reason, mTotalTouchDownTime, mTouchCycles);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001524 mLastTouchDown = 0;
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001525 int err = setScreenStateLocked(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001526 if (err == 0) {
Mike Lockwood435eb642009-12-03 08:40:18 -05001527 mScreenOffReason = reason;
1528 sendNotificationLocked(false, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001529 }
1530 return err;
1531 }
1532
1533 private boolean batteryIsLow() {
1534 return (!mIsPowered &&
1535 mBatteryService.getBatteryLevel() <= Power.LOW_BATTERY_THRESHOLD);
1536 }
1537
The Android Open Source Project10592532009-03-18 17:39:46 -07001538 private void updateLightsLocked(int newState, int forceState) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001539 final int oldState = mPowerState;
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001540 newState = applyButtonState(newState);
1541 newState = applyKeyboardState(newState);
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001542 final int realDifference = (newState ^ oldState);
1543 final int difference = realDifference | forceState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001544 if (difference == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001545 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001546 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001547
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001548 int offMask = 0;
1549 int dimMask = 0;
1550 int onMask = 0;
1551
1552 int preferredBrightness = getPreferredBrightness();
1553 boolean startAnimation = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001554
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001555 if ((difference & KEYBOARD_BRIGHT_BIT) != 0) {
1556 if (ANIMATE_KEYBOARD_LIGHTS) {
1557 if ((newState & KEYBOARD_BRIGHT_BIT) == 0) {
1558 mKeyboardBrightness.setTargetLocked(Power.BRIGHTNESS_OFF,
Joe Onorato128e7292009-03-24 18:41:31 -07001559 ANIM_STEPS, INITIAL_KEYBOARD_BRIGHTNESS,
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001560 Power.BRIGHTNESS_ON);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001561 } else {
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001562 mKeyboardBrightness.setTargetLocked(Power.BRIGHTNESS_ON,
Joe Onorato128e7292009-03-24 18:41:31 -07001563 ANIM_STEPS, INITIAL_KEYBOARD_BRIGHTNESS,
1564 Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001565 }
1566 startAnimation = true;
1567 } else {
1568 if ((newState & KEYBOARD_BRIGHT_BIT) == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001569 offMask |= KEYBOARD_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001570 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001571 onMask |= KEYBOARD_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001572 }
1573 }
1574 }
1575
1576 if ((difference & BUTTON_BRIGHT_BIT) != 0) {
1577 if (ANIMATE_BUTTON_LIGHTS) {
1578 if ((newState & BUTTON_BRIGHT_BIT) == 0) {
1579 mButtonBrightness.setTargetLocked(Power.BRIGHTNESS_OFF,
Joe Onorato128e7292009-03-24 18:41:31 -07001580 ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001581 Power.BRIGHTNESS_ON);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001582 } else {
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001583 mButtonBrightness.setTargetLocked(Power.BRIGHTNESS_ON,
Joe Onorato128e7292009-03-24 18:41:31 -07001584 ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
1585 Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001586 }
1587 startAnimation = true;
1588 } else {
1589 if ((newState & BUTTON_BRIGHT_BIT) == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001590 offMask |= BUTTON_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001591 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001592 onMask |= BUTTON_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001593 }
1594 }
1595 }
1596
1597 if ((difference & (SCREEN_ON_BIT | SCREEN_BRIGHT_BIT)) != 0) {
1598 if (ANIMATE_SCREEN_LIGHTS) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001599 int nominalCurrentValue = -1;
1600 // If there was an actual difference in the light state, then
1601 // figure out the "ideal" current value based on the previous
1602 // state. Otherwise, this is a change due to the brightness
1603 // override, so we want to animate from whatever the current
1604 // value is.
1605 if ((realDifference & (SCREEN_ON_BIT | SCREEN_BRIGHT_BIT)) != 0) {
1606 switch (oldState & (SCREEN_BRIGHT_BIT|SCREEN_ON_BIT)) {
1607 case SCREEN_BRIGHT_BIT | SCREEN_ON_BIT:
1608 nominalCurrentValue = preferredBrightness;
1609 break;
1610 case SCREEN_ON_BIT:
1611 nominalCurrentValue = Power.BRIGHTNESS_DIM;
1612 break;
1613 case 0:
1614 nominalCurrentValue = Power.BRIGHTNESS_OFF;
1615 break;
1616 case SCREEN_BRIGHT_BIT:
1617 default:
1618 // not possible
1619 nominalCurrentValue = (int)mScreenBrightness.curValue;
1620 break;
1621 }
Joe Onorato128e7292009-03-24 18:41:31 -07001622 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001623 int brightness = preferredBrightness;
1624 int steps = ANIM_STEPS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001625 if ((newState & SCREEN_BRIGHT_BIT) == 0) {
1626 // dim or turn off backlight, depending on if the screen is on
1627 // the scale is because the brightness ramp isn't linear and this biases
1628 // it so the later parts take longer.
1629 final float scale = 1.5f;
1630 float ratio = (((float)Power.BRIGHTNESS_DIM)/preferredBrightness);
1631 if (ratio > 1.0f) ratio = 1.0f;
1632 if ((newState & SCREEN_ON_BIT) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001633 if ((oldState & SCREEN_BRIGHT_BIT) != 0) {
1634 // was bright
1635 steps = ANIM_STEPS;
1636 } else {
1637 // was dim
1638 steps = (int)(ANIM_STEPS*ratio*scale);
1639 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001640 brightness = Power.BRIGHTNESS_OFF;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001641 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001642 if ((oldState & SCREEN_ON_BIT) != 0) {
1643 // was bright
1644 steps = (int)(ANIM_STEPS*(1.0f-ratio)*scale);
1645 } else {
1646 // was dim
1647 steps = (int)(ANIM_STEPS*ratio);
1648 }
1649 if (mStayOnConditions != 0 && mBatteryService.isPowered(mStayOnConditions)) {
1650 // If the "stay on while plugged in" option is
1651 // turned on, then the screen will often not
1652 // automatically turn off while plugged in. To
1653 // still have a sense of when it is inactive, we
1654 // will then count going dim as turning off.
1655 mScreenOffTime = SystemClock.elapsedRealtime();
1656 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001657 brightness = Power.BRIGHTNESS_DIM;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001658 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001659 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001660 long identity = Binder.clearCallingIdentity();
1661 try {
1662 mBatteryStats.noteScreenBrightness(brightness);
1663 } catch (RemoteException e) {
1664 // Nothing interesting to do.
1665 } finally {
1666 Binder.restoreCallingIdentity(identity);
1667 }
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001668 if (mScreenBrightness.setTargetLocked(brightness,
1669 steps, INITIAL_SCREEN_BRIGHTNESS, nominalCurrentValue)) {
1670 startAnimation = true;
1671 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001672 } else {
1673 if ((newState & SCREEN_BRIGHT_BIT) == 0) {
1674 // dim or turn off backlight, depending on if the screen is on
1675 if ((newState & SCREEN_ON_BIT) == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001676 offMask |= SCREEN_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001677 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001678 dimMask |= SCREEN_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001679 }
1680 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001681 onMask |= SCREEN_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001682 }
1683 }
1684 }
1685
1686 if (startAnimation) {
1687 if (mSpew) {
1688 Log.i(TAG, "Scheduling light animator!");
1689 }
1690 mHandler.removeCallbacks(mLightAnimator);
1691 mHandler.post(mLightAnimator);
1692 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001693
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001694 if (offMask != 0) {
1695 //Log.i(TAG, "Setting brightess off: " + offMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001696 setLightBrightness(offMask, Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001697 }
1698 if (dimMask != 0) {
1699 int brightness = Power.BRIGHTNESS_DIM;
1700 if ((newState & BATTERY_LOW_BIT) != 0 &&
1701 brightness > Power.BRIGHTNESS_LOW_BATTERY) {
1702 brightness = Power.BRIGHTNESS_LOW_BATTERY;
1703 }
1704 //Log.i(TAG, "Setting brightess dim " + brightness + ": " + offMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001705 setLightBrightness(dimMask, brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001706 }
1707 if (onMask != 0) {
1708 int brightness = getPreferredBrightness();
1709 if ((newState & BATTERY_LOW_BIT) != 0 &&
1710 brightness > Power.BRIGHTNESS_LOW_BATTERY) {
1711 brightness = Power.BRIGHTNESS_LOW_BATTERY;
1712 }
1713 //Log.i(TAG, "Setting brightess on " + brightness + ": " + onMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001714 setLightBrightness(onMask, brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001715 }
The Android Open Source Project10592532009-03-18 17:39:46 -07001716 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001717
The Android Open Source Project10592532009-03-18 17:39:46 -07001718 private void setLightBrightness(int mask, int value) {
Mike Lockwoodcc9a63d2009-11-10 07:50:28 -05001719 int brightnessMode = (mAutoBrightessEnabled
Mike Lockwood3a322132009-11-24 00:30:52 -05001720 ? LightsService.BRIGHTNESS_MODE_SENSOR
1721 : LightsService.BRIGHTNESS_MODE_USER);
The Android Open Source Project10592532009-03-18 17:39:46 -07001722 if ((mask & SCREEN_BRIGHT_BIT) != 0) {
Mike Lockwood3cb67a32009-11-27 14:25:58 -05001723 mLcdLight.setBrightness(value, brightnessMode);
The Android Open Source Project10592532009-03-18 17:39:46 -07001724 }
1725 if ((mask & BUTTON_BRIGHT_BIT) != 0) {
Mike Lockwood3cb67a32009-11-27 14:25:58 -05001726 mButtonLight.setBrightness(value);
The Android Open Source Project10592532009-03-18 17:39:46 -07001727 }
1728 if ((mask & KEYBOARD_BRIGHT_BIT) != 0) {
Mike Lockwood3cb67a32009-11-27 14:25:58 -05001729 mKeyboardLight.setBrightness(value);
The Android Open Source Project10592532009-03-18 17:39:46 -07001730 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001731 }
1732
1733 class BrightnessState {
1734 final int mask;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001735
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001736 boolean initialized;
1737 int targetValue;
1738 float curValue;
1739 float delta;
1740 boolean animating;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001741
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001742 BrightnessState(int m) {
1743 mask = m;
1744 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001745
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001746 public void dump(PrintWriter pw, String prefix) {
1747 pw.println(prefix + "animating=" + animating
1748 + " targetValue=" + targetValue
1749 + " curValue=" + curValue
1750 + " delta=" + delta);
1751 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001752
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001753 boolean setTargetLocked(int target, int stepsToTarget, int initialValue,
Joe Onorato128e7292009-03-24 18:41:31 -07001754 int nominalCurrentValue) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001755 if (!initialized) {
1756 initialized = true;
1757 curValue = (float)initialValue;
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001758 } else if (targetValue == target) {
1759 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001760 }
1761 targetValue = target;
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001762 delta = (targetValue -
1763 (nominalCurrentValue >= 0 ? nominalCurrentValue : curValue))
1764 / stepsToTarget;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001765 if (mSpew) {
Joe Onorato128e7292009-03-24 18:41:31 -07001766 String noticeMe = nominalCurrentValue == curValue ? "" : " ******************";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001767 Log.i(TAG, "Setting target " + mask + ": cur=" + curValue
Joe Onorato128e7292009-03-24 18:41:31 -07001768 + " target=" + targetValue + " delta=" + delta
1769 + " nominalCurrentValue=" + nominalCurrentValue
1770 + noticeMe);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001771 }
1772 animating = true;
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001773 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001774 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001775
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001776 boolean stepLocked() {
1777 if (!animating) return false;
1778 if (false && mSpew) {
1779 Log.i(TAG, "Step target " + mask + ": cur=" + curValue
1780 + " target=" + targetValue + " delta=" + delta);
1781 }
1782 curValue += delta;
1783 int curIntValue = (int)curValue;
1784 boolean more = true;
1785 if (delta == 0) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001786 curValue = curIntValue = targetValue;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001787 more = false;
1788 } else if (delta > 0) {
1789 if (curIntValue >= targetValue) {
1790 curValue = curIntValue = targetValue;
1791 more = false;
1792 }
1793 } else {
1794 if (curIntValue <= targetValue) {
1795 curValue = curIntValue = targetValue;
1796 more = false;
1797 }
1798 }
1799 //Log.i(TAG, "Animating brightess " + curIntValue + ": " + mask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001800 setLightBrightness(mask, curIntValue);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001801 animating = more;
1802 if (!more) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001803 if (mask == SCREEN_BRIGHT_BIT && curIntValue == Power.BRIGHTNESS_OFF) {
Mike Lockwood435eb642009-12-03 08:40:18 -05001804 screenOffFinishedAnimatingLocked(mScreenOffReason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001805 }
1806 }
1807 return more;
1808 }
1809 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001810
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001811 private class LightAnimator implements Runnable {
1812 public void run() {
1813 synchronized (mLocks) {
1814 long now = SystemClock.uptimeMillis();
1815 boolean more = mScreenBrightness.stepLocked();
1816 if (mKeyboardBrightness.stepLocked()) {
1817 more = true;
1818 }
1819 if (mButtonBrightness.stepLocked()) {
1820 more = true;
1821 }
1822 if (more) {
1823 mHandler.postAtTime(mLightAnimator, now+(1000/60));
1824 }
1825 }
1826 }
1827 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001828
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001829 private int getPreferredBrightness() {
1830 try {
1831 if (mScreenBrightnessOverride >= 0) {
1832 return mScreenBrightnessOverride;
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001833 } else if (mLightSensorScreenBrightness >= 0 && mUseSoftwareAutoBrightness
Mike Lockwood27c6dd72009-11-04 08:57:07 -05001834 && mAutoBrightessEnabled) {
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001835 return mLightSensorScreenBrightness;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001836 }
1837 final int brightness = Settings.System.getInt(mContext.getContentResolver(),
1838 SCREEN_BRIGHTNESS);
1839 // Don't let applications turn the screen all the way off
1840 return Math.max(brightness, Power.BRIGHTNESS_DIM);
1841 } catch (SettingNotFoundException snfe) {
1842 return Power.BRIGHTNESS_ON;
1843 }
1844 }
1845
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001846 private int applyButtonState(int state) {
1847 int brightness = -1;
1848 if (mButtonBrightnessOverride >= 0) {
1849 brightness = mButtonBrightnessOverride;
1850 } else if (mLightSensorButtonBrightness >= 0 && mUseSoftwareAutoBrightness) {
1851 brightness = mLightSensorButtonBrightness;
1852 }
1853 if (brightness > 0) {
1854 return state | BUTTON_BRIGHT_BIT;
1855 } else if (brightness == 0) {
1856 return state & ~BUTTON_BRIGHT_BIT;
1857 } else {
1858 return state;
1859 }
1860 }
1861
1862 private int applyKeyboardState(int state) {
1863 int brightness = -1;
1864 if (!mKeyboardVisible) {
1865 brightness = 0;
1866 } else if (mButtonBrightnessOverride >= 0) {
1867 brightness = mButtonBrightnessOverride;
1868 } else if (mLightSensorKeyboardBrightness >= 0 && mUseSoftwareAutoBrightness) {
1869 brightness = mLightSensorKeyboardBrightness;
1870 }
1871 if (brightness > 0) {
1872 return state | KEYBOARD_BRIGHT_BIT;
1873 } else if (brightness == 0) {
1874 return state & ~KEYBOARD_BRIGHT_BIT;
1875 } else {
1876 return state;
1877 }
1878 }
1879
Charles Mendis322591c2009-10-29 11:06:59 -07001880 public boolean isScreenOn() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001881 synchronized (mLocks) {
1882 return (mPowerState & SCREEN_ON_BIT) != 0;
1883 }
1884 }
1885
Charles Mendis322591c2009-10-29 11:06:59 -07001886 boolean isScreenBright() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001887 synchronized (mLocks) {
1888 return (mPowerState & SCREEN_BRIGHT) == SCREEN_BRIGHT;
1889 }
1890 }
1891
Mike Lockwood497087e32009-11-08 18:33:03 -05001892 private boolean isScreenTurningOffLocked() {
1893 return (mScreenBrightness.animating && mScreenBrightness.targetValue == 0);
1894 }
1895
Mike Lockwood200b30b2009-09-20 00:23:59 -04001896 private void forceUserActivityLocked() {
Mike Lockwoode090281422009-11-14 21:02:56 -05001897 if (isScreenTurningOffLocked()) {
1898 // cancel animation so userActivity will succeed
1899 mScreenBrightness.animating = false;
1900 }
Mike Lockwood200b30b2009-09-20 00:23:59 -04001901 boolean savedActivityAllowed = mUserActivityAllowed;
1902 mUserActivityAllowed = true;
1903 userActivity(SystemClock.uptimeMillis(), false);
1904 mUserActivityAllowed = savedActivityAllowed;
1905 }
1906
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001907 public void userActivityWithForce(long time, boolean noChangeLights, boolean force) {
1908 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1909 userActivity(time, noChangeLights, OTHER_EVENT, force);
1910 }
1911
1912 public void userActivity(long time, boolean noChangeLights) {
1913 userActivity(time, noChangeLights, OTHER_EVENT, false);
1914 }
1915
1916 public void userActivity(long time, boolean noChangeLights, int eventType) {
1917 userActivity(time, noChangeLights, eventType, false);
1918 }
1919
1920 public void userActivity(long time, boolean noChangeLights, int eventType, boolean force) {
1921 //mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1922
1923 if (((mPokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0)
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07001924 && (eventType == CHEEK_EVENT || eventType == TOUCH_EVENT)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001925 if (false) {
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07001926 Log.d(TAG, "dropping cheek or short event mPokey=0x" + Integer.toHexString(mPokey));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001927 }
1928 return;
1929 }
1930
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07001931 if (((mPokey & POKE_LOCK_IGNORE_TOUCH_AND_CHEEK_EVENTS) != 0)
1932 && (eventType == TOUCH_EVENT || eventType == TOUCH_UP_EVENT
1933 || eventType == LONG_TOUCH_EVENT || eventType == CHEEK_EVENT)) {
1934 if (false) {
1935 Log.d(TAG, "dropping touch mPokey=0x" + Integer.toHexString(mPokey));
1936 }
1937 return;
1938 }
1939
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001940 if (false) {
1941 if (((mPokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0)) {
1942 Log.d(TAG, "userActivity !!!");//, new RuntimeException());
1943 } else {
1944 Log.d(TAG, "mPokey=0x" + Integer.toHexString(mPokey));
1945 }
1946 }
1947
1948 synchronized (mLocks) {
1949 if (mSpew) {
1950 Log.d(TAG, "userActivity mLastEventTime=" + mLastEventTime + " time=" + time
1951 + " mUserActivityAllowed=" + mUserActivityAllowed
1952 + " mUserState=0x" + Integer.toHexString(mUserState)
Mike Lockwood36fc3022009-08-25 16:49:06 -07001953 + " mWakeLockState=0x" + Integer.toHexString(mWakeLockState)
1954 + " mProximitySensorActive=" + mProximitySensorActive
1955 + " force=" + force);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001956 }
Mike Lockwood05067122009-10-27 23:07:25 -04001957 // ignore user activity if we are in the process of turning off the screen
Mike Lockwood497087e32009-11-08 18:33:03 -05001958 if (isScreenTurningOffLocked()) {
Mike Lockwood05067122009-10-27 23:07:25 -04001959 Log.d(TAG, "ignoring user activity while turning off screen");
1960 return;
1961 }
Mike Lockwood0e39ea82009-11-18 15:37:10 -05001962 // Disable proximity sensor if if user presses power key while we are in the
1963 // "waiting for proximity sensor to go negative" state.
1964 if (mProximitySensorActive && mProximityWakeLockCount == 0) {
1965 mProximitySensorActive = false;
1966 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001967 if (mLastEventTime <= time || force) {
1968 mLastEventTime = time;
Mike Lockwood36fc3022009-08-25 16:49:06 -07001969 if ((mUserActivityAllowed && !mProximitySensorActive) || force) {
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001970 // Only turn on button backlights if a button was pressed
1971 // and auto brightness is disabled
Mike Lockwood4984e732009-11-01 08:16:33 -05001972 if (eventType == BUTTON_EVENT && !mUseSoftwareAutoBrightness) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001973 mUserState = (mKeyboardVisible ? ALL_BRIGHT : SCREEN_BUTTON_BRIGHT);
1974 } else {
1975 // don't clear button/keyboard backlights when the screen is touched.
1976 mUserState |= SCREEN_BRIGHT;
1977 }
1978
Dianne Hackborn617f8772009-03-31 15:04:46 -07001979 int uid = Binder.getCallingUid();
1980 long ident = Binder.clearCallingIdentity();
1981 try {
1982 mBatteryStats.noteUserActivity(uid, eventType);
1983 } catch (RemoteException e) {
1984 // Ignore
1985 } finally {
1986 Binder.restoreCallingIdentity(ident);
1987 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001988
Michael Chane96440f2009-05-06 10:27:36 -07001989 mWakeLockState = mLocks.reactivateScreenLocksLocked();
Mike Lockwood435eb642009-12-03 08:40:18 -05001990 setPowerState(mUserState | mWakeLockState, noChangeLights,
1991 WindowManagerPolicy.OFF_BECAUSE_OF_USER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001992 setTimeoutLocked(time, SCREEN_BRIGHT);
1993 }
1994 }
1995 }
1996 }
1997
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001998 private int getAutoBrightnessValue(int sensorValue, int[] values) {
1999 try {
2000 int i;
2001 for (i = 0; i < mAutoBrightnessLevels.length; i++) {
2002 if (sensorValue < mAutoBrightnessLevels[i]) {
2003 break;
2004 }
2005 }
2006 return values[i];
2007 } catch (Exception e) {
2008 // guard against null pointer or index out of bounds errors
2009 Log.e(TAG, "getAutoBrightnessValue", e);
2010 return 255;
2011 }
2012 }
2013
Mike Lockwood20f87d72009-11-05 16:08:51 -05002014 private Runnable mProximityTask = new Runnable() {
2015 public void run() {
2016 synchronized (mLocks) {
2017 if (mProximityPendingValue != -1) {
2018 proximityChangedLocked(mProximityPendingValue == 1);
2019 mProximityPendingValue = -1;
2020 }
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002021 if (mProximityPartialLock.isHeld()) {
2022 mProximityPartialLock.release();
2023 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002024 }
2025 }
2026 };
2027
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002028 private Runnable mAutoBrightnessTask = new Runnable() {
2029 public void run() {
Mike Lockwoodfa68ab42009-10-20 11:08:49 -04002030 synchronized (mLocks) {
2031 int value = (int)mLightSensorPendingValue;
2032 if (value >= 0) {
2033 mLightSensorPendingValue = -1;
2034 lightSensorChangedLocked(value);
2035 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002036 }
2037 }
2038 };
2039
2040 private void lightSensorChangedLocked(int value) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002041 if (mDebugLightSensor) {
2042 Log.d(TAG, "lightSensorChangedLocked " + value);
2043 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002044
2045 if (mLightSensorValue != value) {
2046 mLightSensorValue = value;
2047 if ((mPowerState & BATTERY_LOW_BIT) == 0) {
2048 int lcdValue = getAutoBrightnessValue(value, mLcdBacklightValues);
2049 int buttonValue = getAutoBrightnessValue(value, mButtonBacklightValues);
Mike Lockwooddf024922009-10-29 21:29:15 -04002050 int keyboardValue;
2051 if (mKeyboardVisible) {
2052 keyboardValue = getAutoBrightnessValue(value, mKeyboardBacklightValues);
2053 } else {
2054 keyboardValue = 0;
2055 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002056 mLightSensorScreenBrightness = lcdValue;
2057 mLightSensorButtonBrightness = buttonValue;
2058 mLightSensorKeyboardBrightness = keyboardValue;
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002059
2060 if (mDebugLightSensor) {
2061 Log.d(TAG, "lcdValue " + lcdValue);
2062 Log.d(TAG, "buttonValue " + buttonValue);
2063 Log.d(TAG, "keyboardValue " + keyboardValue);
2064 }
2065
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002066 boolean startAnimation = false;
Mike Lockwood4984e732009-11-01 08:16:33 -05002067 if (mAutoBrightessEnabled && mScreenBrightnessOverride < 0) {
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002068 if (ANIMATE_SCREEN_LIGHTS) {
2069 if (mScreenBrightness.setTargetLocked(lcdValue,
2070 AUTOBRIGHTNESS_ANIM_STEPS, INITIAL_SCREEN_BRIGHTNESS,
2071 (int)mScreenBrightness.curValue)) {
2072 startAnimation = true;
2073 }
2074 } else {
Mike Lockwoodcc9a63d2009-11-10 07:50:28 -05002075 int brightnessMode = (mAutoBrightessEnabled
Mike Lockwood3a322132009-11-24 00:30:52 -05002076 ? LightsService.BRIGHTNESS_MODE_SENSOR
2077 : LightsService.BRIGHTNESS_MODE_USER);
Mike Lockwood3cb67a32009-11-27 14:25:58 -05002078 mLcdLight.setBrightness(lcdValue, brightnessMode);
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002079 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002080 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002081 if (mButtonBrightnessOverride < 0) {
2082 if (ANIMATE_BUTTON_LIGHTS) {
2083 if (mButtonBrightness.setTargetLocked(buttonValue,
2084 AUTOBRIGHTNESS_ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
2085 (int)mButtonBrightness.curValue)) {
2086 startAnimation = true;
2087 }
2088 } else {
Mike Lockwood3cb67a32009-11-27 14:25:58 -05002089 mButtonLight.setBrightness(buttonValue);
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002090 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002091 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002092 if (mButtonBrightnessOverride < 0 || !mKeyboardVisible) {
2093 if (ANIMATE_KEYBOARD_LIGHTS) {
2094 if (mKeyboardBrightness.setTargetLocked(keyboardValue,
2095 AUTOBRIGHTNESS_ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
2096 (int)mKeyboardBrightness.curValue)) {
2097 startAnimation = true;
2098 }
2099 } else {
Mike Lockwood3cb67a32009-11-27 14:25:58 -05002100 mKeyboardLight.setBrightness(keyboardValue);
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002101 }
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002102 }
2103 if (startAnimation) {
2104 if (mDebugLightSensor) {
2105 Log.i(TAG, "lightSensorChangedLocked scheduling light animator");
2106 }
2107 mHandler.removeCallbacks(mLightAnimator);
2108 mHandler.post(mLightAnimator);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002109 }
2110 }
2111 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002112 }
2113
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002114 /**
2115 * The user requested that we go to sleep (probably with the power button).
2116 * This overrides all wake locks that are held.
2117 */
2118 public void goToSleep(long time)
2119 {
2120 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
2121 synchronized (mLocks) {
Mike Lockwood435eb642009-12-03 08:40:18 -05002122 goToSleepLocked(time, WindowManagerPolicy.OFF_BECAUSE_OF_USER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002123 }
2124 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002125
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002126 /**
Doug Zongker50a21f42009-11-19 12:49:53 -08002127 * Reboot the device immediately, passing 'reason' (may be null)
2128 * to the underlying __reboot system call. Should not return.
2129 */
2130 public void reboot(String reason)
2131 {
2132 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
2133 try {
2134 Power.reboot(reason);
2135 } catch (IOException e) {
2136 Log.e(TAG, "reboot failed", e);
2137 }
2138 }
2139
Mike Lockwood435eb642009-12-03 08:40:18 -05002140 private void goToSleepLocked(long time, int reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002141
2142 if (mLastEventTime <= time) {
2143 mLastEventTime = time;
2144 // cancel all of the wake locks
2145 mWakeLockState = SCREEN_OFF;
2146 int N = mLocks.size();
2147 int numCleared = 0;
2148 for (int i=0; i<N; i++) {
2149 WakeLock wl = mLocks.get(i);
2150 if (isScreenLock(wl.flags)) {
2151 mLocks.get(i).activated = false;
2152 numCleared++;
2153 }
2154 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002155 EventLog.writeEvent(EventLogTags.POWER_SLEEP_REQUESTED, numCleared);
Joe Onorato128e7292009-03-24 18:41:31 -07002156 mStillNeedSleepNotification = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002157 mUserState = SCREEN_OFF;
Mike Lockwood435eb642009-12-03 08:40:18 -05002158 setPowerState(SCREEN_OFF, false, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002159 cancelTimerLocked();
2160 }
2161 }
2162
2163 public long timeSinceScreenOn() {
2164 synchronized (mLocks) {
2165 if ((mPowerState & SCREEN_ON_BIT) != 0) {
2166 return 0;
2167 }
2168 return SystemClock.elapsedRealtime() - mScreenOffTime;
2169 }
2170 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002171
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002172 public void setKeyboardVisibility(boolean visible) {
Mike Lockwooda625b382009-09-12 17:36:03 -07002173 synchronized (mLocks) {
2174 if (mSpew) {
2175 Log.d(TAG, "setKeyboardVisibility: " + visible);
2176 }
Mike Lockwood3c9435a2009-10-22 15:45:37 -04002177 if (mKeyboardVisible != visible) {
2178 mKeyboardVisible = visible;
2179 // don't signal user activity if the screen is off; other code
2180 // will take care of turning on due to a true change to the lid
2181 // switch and synchronized with the lock screen.
2182 if ((mPowerState & SCREEN_ON_BIT) != 0) {
Mike Lockwood4984e732009-11-01 08:16:33 -05002183 if (mUseSoftwareAutoBrightness) {
Mike Lockwooddf024922009-10-29 21:29:15 -04002184 // force recompute of backlight values
2185 if (mLightSensorValue >= 0) {
2186 int value = (int)mLightSensorValue;
2187 mLightSensorValue = -1;
2188 lightSensorChangedLocked(value);
2189 }
2190 }
Mike Lockwood3c9435a2009-10-22 15:45:37 -04002191 userActivity(SystemClock.uptimeMillis(), false, BUTTON_EVENT, true);
2192 }
Mike Lockwooda625b382009-09-12 17:36:03 -07002193 }
2194 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002195 }
2196
2197 /**
2198 * When the keyguard is up, it manages the power state, and userActivity doesn't do anything.
Mike Lockwood50c548d2009-11-09 16:02:06 -05002199 * When disabling user activity we also reset user power state so the keyguard can reset its
2200 * short screen timeout when keyguard is unhidden.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002201 */
2202 public void enableUserActivity(boolean enabled) {
Mike Lockwood50c548d2009-11-09 16:02:06 -05002203 if (mSpew) {
2204 Log.d(TAG, "enableUserActivity " + enabled);
2205 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002206 synchronized (mLocks) {
2207 mUserActivityAllowed = enabled;
Mike Lockwood50c548d2009-11-09 16:02:06 -05002208 if (!enabled) {
2209 // cancel timeout and clear mUserState so the keyguard can set a short timeout
2210 setTimeoutLocked(SystemClock.uptimeMillis(), 0);
2211 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002212 }
2213 }
2214
Mike Lockwooddc3494e2009-10-14 21:17:09 -07002215 private void setScreenBrightnessMode(int mode) {
Mike Lockwood2d155d22009-10-27 09:32:30 -04002216 boolean enabled = (mode == SCREEN_BRIGHTNESS_MODE_AUTOMATIC);
Mike Lockwoodf90ffcc2009-11-03 11:41:27 -05002217 if (mUseSoftwareAutoBrightness && mAutoBrightessEnabled != enabled) {
Mike Lockwood2d155d22009-10-27 09:32:30 -04002218 mAutoBrightessEnabled = enabled;
Charles Mendis322591c2009-10-29 11:06:59 -07002219 if (isScreenOn()) {
Mike Lockwood4984e732009-11-01 08:16:33 -05002220 // force recompute of backlight values
2221 if (mLightSensorValue >= 0) {
2222 int value = (int)mLightSensorValue;
2223 mLightSensorValue = -1;
2224 lightSensorChangedLocked(value);
2225 }
Mike Lockwood2d155d22009-10-27 09:32:30 -04002226 }
Mike Lockwooddc3494e2009-10-14 21:17:09 -07002227 }
2228 }
2229
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002230 /** Sets the screen off timeouts:
2231 * mKeylightDelay
2232 * mDimDelay
2233 * mScreenOffDelay
2234 * */
2235 private void setScreenOffTimeoutsLocked() {
2236 if ((mPokey & POKE_LOCK_SHORT_TIMEOUT) != 0) {
2237 mKeylightDelay = mShortKeylightDelay; // Configurable via Gservices
2238 mDimDelay = -1;
2239 mScreenOffDelay = 0;
2240 } else if ((mPokey & POKE_LOCK_MEDIUM_TIMEOUT) != 0) {
2241 mKeylightDelay = MEDIUM_KEYLIGHT_DELAY;
2242 mDimDelay = -1;
2243 mScreenOffDelay = 0;
2244 } else {
2245 int totalDelay = mTotalDelaySetting;
2246 mKeylightDelay = LONG_KEYLIGHT_DELAY;
2247 if (totalDelay < 0) {
2248 mScreenOffDelay = Integer.MAX_VALUE;
2249 } else if (mKeylightDelay < totalDelay) {
2250 // subtract the time that the keylight delay. This will give us the
2251 // remainder of the time that we need to sleep to get the accurate
2252 // screen off timeout.
2253 mScreenOffDelay = totalDelay - mKeylightDelay;
2254 } else {
2255 mScreenOffDelay = 0;
2256 }
2257 if (mDimScreen && totalDelay >= (LONG_KEYLIGHT_DELAY + LONG_DIM_TIME)) {
2258 mDimDelay = mScreenOffDelay - LONG_DIM_TIME;
2259 mScreenOffDelay = LONG_DIM_TIME;
2260 } else {
2261 mDimDelay = -1;
2262 }
2263 }
2264 if (mSpew) {
2265 Log.d(TAG, "setScreenOffTimeouts mKeylightDelay=" + mKeylightDelay
2266 + " mDimDelay=" + mDimDelay + " mScreenOffDelay=" + mScreenOffDelay
2267 + " mDimScreen=" + mDimScreen);
2268 }
2269 }
2270
2271 /**
2272 * Refreshes cached Gservices settings. Called once on startup, and
2273 * on subsequent Settings.Gservices.CHANGED_ACTION broadcasts (see
2274 * GservicesChangedReceiver).
2275 */
2276 private void updateGservicesValues() {
2277 mShortKeylightDelay = Settings.Gservices.getInt(
2278 mContext.getContentResolver(),
2279 Settings.Gservices.SHORT_KEYLIGHT_DELAY_MS,
2280 SHORT_KEYLIGHT_DELAY_DEFAULT);
2281 // Log.i(TAG, "updateGservicesValues(): mShortKeylightDelay now " + mShortKeylightDelay);
2282 }
2283
2284 /**
2285 * Receiver for the Gservices.CHANGED_ACTION broadcast intent,
2286 * which tells us we need to refresh our cached Gservices settings.
2287 */
2288 private class GservicesChangedReceiver extends BroadcastReceiver {
2289 @Override
2290 public void onReceive(Context context, Intent intent) {
2291 // Log.i(TAG, "GservicesChangedReceiver.onReceive(): " + intent);
2292 updateGservicesValues();
2293 }
2294 }
2295
2296 private class LockList extends ArrayList<WakeLock>
2297 {
2298 void addLock(WakeLock wl)
2299 {
2300 int index = getIndex(wl.binder);
2301 if (index < 0) {
2302 this.add(wl);
2303 }
2304 }
2305
2306 WakeLock removeLock(IBinder binder)
2307 {
2308 int index = getIndex(binder);
2309 if (index >= 0) {
2310 return this.remove(index);
2311 } else {
2312 return null;
2313 }
2314 }
2315
2316 int getIndex(IBinder binder)
2317 {
2318 int N = this.size();
2319 for (int i=0; i<N; i++) {
2320 if (this.get(i).binder == binder) {
2321 return i;
2322 }
2323 }
2324 return -1;
2325 }
2326
2327 int gatherState()
2328 {
2329 int result = 0;
2330 int N = this.size();
2331 for (int i=0; i<N; i++) {
2332 WakeLock wl = this.get(i);
2333 if (wl.activated) {
2334 if (isScreenLock(wl.flags)) {
2335 result |= wl.minState;
2336 }
2337 }
2338 }
2339 return result;
2340 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002341
Michael Chane96440f2009-05-06 10:27:36 -07002342 int reactivateScreenLocksLocked()
2343 {
2344 int result = 0;
2345 int N = this.size();
2346 for (int i=0; i<N; i++) {
2347 WakeLock wl = this.get(i);
2348 if (isScreenLock(wl.flags)) {
2349 wl.activated = true;
2350 result |= wl.minState;
2351 }
2352 }
2353 return result;
2354 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002355 }
2356
2357 void setPolicy(WindowManagerPolicy p) {
2358 synchronized (mLocks) {
2359 mPolicy = p;
2360 mLocks.notifyAll();
2361 }
2362 }
2363
2364 WindowManagerPolicy getPolicyLocked() {
2365 while (mPolicy == null || !mDoneBooting) {
2366 try {
2367 mLocks.wait();
2368 } catch (InterruptedException e) {
2369 // Ignore
2370 }
2371 }
2372 return mPolicy;
2373 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002374
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002375 void systemReady() {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002376 mSensorManager = new SensorManager(mHandlerThread.getLooper());
2377 mProximitySensor = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
2378 // don't bother with the light sensor if auto brightness is handled in hardware
Mike Lockwoodaa66ea82009-10-31 16:31:27 -04002379 if (mUseSoftwareAutoBrightness) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002380 mLightSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
Mike Lockwood4984e732009-11-01 08:16:33 -05002381 enableLightSensor(true);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002382 }
2383
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002384 synchronized (mLocks) {
2385 Log.d(TAG, "system ready!");
2386 mDoneBooting = true;
Dianne Hackborn617f8772009-03-31 15:04:46 -07002387 long identity = Binder.clearCallingIdentity();
2388 try {
2389 mBatteryStats.noteScreenBrightness(getPreferredBrightness());
2390 mBatteryStats.noteScreenOn();
2391 } catch (RemoteException e) {
2392 // Nothing interesting to do.
2393 } finally {
2394 Binder.restoreCallingIdentity(identity);
2395 }
Mike Lockwood2d7bb812009-11-15 18:12:22 -05002396 }
2397 }
2398
2399 void bootCompleted() {
2400 Log.d(TAG, "bootCompleted");
2401 synchronized (mLocks) {
2402 mBootCompleted = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002403 userActivity(SystemClock.uptimeMillis(), false, BUTTON_EVENT, true);
2404 updateWakeLockLocked();
2405 mLocks.notifyAll();
2406 }
2407 }
2408
2409 public void monitor() {
2410 synchronized (mLocks) { }
2411 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002412
2413 public int getSupportedWakeLockFlags() {
2414 int result = PowerManager.PARTIAL_WAKE_LOCK
2415 | PowerManager.FULL_WAKE_LOCK
2416 | PowerManager.SCREEN_DIM_WAKE_LOCK;
2417
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002418 if (mProximitySensor != null) {
2419 result |= PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK;
2420 }
2421
2422 return result;
2423 }
2424
Mike Lockwood237a2992009-09-15 14:42:16 -04002425 public void setBacklightBrightness(int brightness) {
2426 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
2427 // Don't let applications turn the screen all the way off
2428 brightness = Math.max(brightness, Power.BRIGHTNESS_DIM);
Mike Lockwood3cb67a32009-11-27 14:25:58 -05002429 mLcdLight.setBrightness(brightness);
2430 mKeyboardLight.setBrightness(mKeyboardVisible ? brightness : 0);
2431 mButtonLight.setBrightness(brightness);
Mike Lockwood237a2992009-09-15 14:42:16 -04002432 long identity = Binder.clearCallingIdentity();
2433 try {
2434 mBatteryStats.noteScreenBrightness(brightness);
2435 } catch (RemoteException e) {
2436 Log.w(TAG, "RemoteException calling noteScreenBrightness on BatteryStatsService", e);
2437 } finally {
2438 Binder.restoreCallingIdentity(identity);
2439 }
2440
2441 // update our animation state
2442 if (ANIMATE_SCREEN_LIGHTS) {
2443 mScreenBrightness.curValue = brightness;
2444 mScreenBrightness.animating = false;
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002445 mScreenBrightness.targetValue = -1;
Mike Lockwood237a2992009-09-15 14:42:16 -04002446 }
2447 if (ANIMATE_KEYBOARD_LIGHTS) {
2448 mKeyboardBrightness.curValue = brightness;
2449 mKeyboardBrightness.animating = false;
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002450 mKeyboardBrightness.targetValue = -1;
Mike Lockwood237a2992009-09-15 14:42:16 -04002451 }
2452 if (ANIMATE_BUTTON_LIGHTS) {
2453 mButtonBrightness.curValue = brightness;
2454 mButtonBrightness.animating = false;
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002455 mButtonBrightness.targetValue = -1;
Mike Lockwood237a2992009-09-15 14:42:16 -04002456 }
2457 }
2458
Mike Lockwoodb11832d2009-11-25 15:25:55 -05002459 public void setAttentionLight(boolean on, int color) {
2460 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
Mike Lockwood3cb67a32009-11-27 14:25:58 -05002461 mAttentionLight.setFlashing(color, LightsService.LIGHT_FLASH_HARDWARE, (on ? 3 : 0), 0);
Mike Lockwoodb11832d2009-11-25 15:25:55 -05002462 }
2463
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002464 private void enableProximityLockLocked() {
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002465 if (mDebugProximitySensor) {
Mike Lockwood36fc3022009-08-25 16:49:06 -07002466 Log.d(TAG, "enableProximityLockLocked");
2467 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002468 if (!mProximitySensorEnabled) {
2469 // clear calling identity so sensor manager battery stats are accurate
2470 long identity = Binder.clearCallingIdentity();
2471 try {
2472 mSensorManager.registerListener(mProximityListener, mProximitySensor,
2473 SensorManager.SENSOR_DELAY_NORMAL);
2474 mProximitySensorEnabled = true;
2475 } finally {
2476 Binder.restoreCallingIdentity(identity);
2477 }
Mike Lockwood809ad0f2009-10-26 22:10:33 -04002478 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002479 }
2480
2481 private void disableProximityLockLocked() {
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002482 if (mDebugProximitySensor) {
Mike Lockwood36fc3022009-08-25 16:49:06 -07002483 Log.d(TAG, "disableProximityLockLocked");
2484 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002485 if (mProximitySensorEnabled) {
2486 // clear calling identity so sensor manager battery stats are accurate
2487 long identity = Binder.clearCallingIdentity();
2488 try {
2489 mSensorManager.unregisterListener(mProximityListener);
2490 mHandler.removeCallbacks(mProximityTask);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002491 if (mProximityPartialLock.isHeld()) {
2492 mProximityPartialLock.release();
2493 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002494 mProximitySensorEnabled = false;
2495 } finally {
2496 Binder.restoreCallingIdentity(identity);
2497 }
2498 if (mProximitySensorActive) {
2499 mProximitySensorActive = false;
2500 forceUserActivityLocked();
2501 }
Mike Lockwood200b30b2009-09-20 00:23:59 -04002502 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002503 }
2504
Mike Lockwood20f87d72009-11-05 16:08:51 -05002505 private void proximityChangedLocked(boolean active) {
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002506 if (mDebugProximitySensor) {
Mike Lockwood20f87d72009-11-05 16:08:51 -05002507 Log.d(TAG, "proximityChangedLocked, active: " + active);
2508 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002509 if (!mProximitySensorEnabled) {
2510 Log.d(TAG, "Ignoring proximity change after sensor is disabled");
Mike Lockwood0d72f7e2009-11-05 20:53:00 -05002511 return;
2512 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002513 if (active) {
Mike Lockwood435eb642009-12-03 08:40:18 -05002514 goToSleepLocked(SystemClock.uptimeMillis(),
2515 WindowManagerPolicy.OFF_BECAUSE_OF_PROX_SENSOR);
Mike Lockwood20f87d72009-11-05 16:08:51 -05002516 mProximitySensorActive = true;
2517 } else {
2518 // proximity sensor negative events trigger as user activity.
2519 // temporarily set mUserActivityAllowed to true so this will work
2520 // even when the keyguard is on.
2521 mProximitySensorActive = false;
2522 forceUserActivityLocked();
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002523
2524 if (mProximityWakeLockCount == 0) {
2525 // disable sensor if we have no listeners left after proximity negative
2526 disableProximityLockLocked();
2527 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002528 }
2529 }
2530
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002531 private void enableLightSensor(boolean enable) {
2532 if (mDebugLightSensor) {
2533 Log.d(TAG, "enableLightSensor " + enable);
2534 }
2535 if (mSensorManager != null && mLightSensorEnabled != enable) {
2536 mLightSensorEnabled = enable;
Mike Lockwood809ad0f2009-10-26 22:10:33 -04002537 // clear calling identity so sensor manager battery stats are accurate
2538 long identity = Binder.clearCallingIdentity();
2539 try {
2540 if (enable) {
2541 mSensorManager.registerListener(mLightListener, mLightSensor,
2542 SensorManager.SENSOR_DELAY_NORMAL);
2543 } else {
2544 mSensorManager.unregisterListener(mLightListener);
2545 mHandler.removeCallbacks(mAutoBrightnessTask);
2546 }
2547 } finally {
2548 Binder.restoreCallingIdentity(identity);
Mike Lockwood06952d92009-08-13 16:05:38 -04002549 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002550 }
2551 }
2552
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002553 SensorEventListener mProximityListener = new SensorEventListener() {
2554 public void onSensorChanged(SensorEvent event) {
Mike Lockwoodba8eb1e2009-11-08 19:31:18 -05002555 long milliseconds = SystemClock.elapsedRealtime();
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002556 synchronized (mLocks) {
2557 float distance = event.values[0];
Mike Lockwood20f87d72009-11-05 16:08:51 -05002558 long timeSinceLastEvent = milliseconds - mLastProximityEventTime;
2559 mLastProximityEventTime = milliseconds;
2560 mHandler.removeCallbacks(mProximityTask);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002561 boolean proximityTaskQueued = false;
Mike Lockwood20f87d72009-11-05 16:08:51 -05002562
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002563 // compare against getMaximumRange to support sensors that only return 0 or 1
Mike Lockwood20f87d72009-11-05 16:08:51 -05002564 boolean active = (distance >= 0.0 && distance < PROXIMITY_THRESHOLD &&
2565 distance < mProximitySensor.getMaximumRange());
2566
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002567 if (mDebugProximitySensor) {
2568 Log.d(TAG, "mProximityListener.onSensorChanged active: " + active);
2569 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002570 if (timeSinceLastEvent < PROXIMITY_SENSOR_DELAY) {
2571 // enforce delaying atleast PROXIMITY_SENSOR_DELAY before processing
2572 mProximityPendingValue = (active ? 1 : 0);
2573 mHandler.postDelayed(mProximityTask, PROXIMITY_SENSOR_DELAY - timeSinceLastEvent);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002574 proximityTaskQueued = true;
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002575 } else {
Mike Lockwood20f87d72009-11-05 16:08:51 -05002576 // process the value immediately
2577 mProximityPendingValue = -1;
2578 proximityChangedLocked(active);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002579 }
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002580
2581 // update mProximityPartialLock state
2582 boolean held = mProximityPartialLock.isHeld();
2583 if (!held && proximityTaskQueued) {
2584 // hold wakelock until mProximityTask runs
2585 mProximityPartialLock.acquire();
2586 } else if (held && !proximityTaskQueued) {
2587 mProximityPartialLock.release();
2588 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002589 }
2590 }
2591
2592 public void onAccuracyChanged(Sensor sensor, int accuracy) {
2593 // ignore
2594 }
2595 };
2596
2597 SensorEventListener mLightListener = new SensorEventListener() {
2598 public void onSensorChanged(SensorEvent event) {
2599 synchronized (mLocks) {
Mike Lockwood497087e32009-11-08 18:33:03 -05002600 // ignore light sensor while screen is turning off
2601 if (isScreenTurningOffLocked()) {
2602 return;
2603 }
2604
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002605 int value = (int)event.values[0];
Mike Lockwoodba8eb1e2009-11-08 19:31:18 -05002606 long milliseconds = SystemClock.elapsedRealtime();
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002607 if (mDebugLightSensor) {
2608 Log.d(TAG, "onSensorChanged: light value: " + value);
2609 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002610 mHandler.removeCallbacks(mAutoBrightnessTask);
2611 if (mLightSensorValue != value) {
Mike Lockwood20ee6f22009-11-07 20:33:47 -05002612 if (mLightSensorValue == -1 ||
2613 milliseconds < mLastScreenOnTime + mLightSensorWarmupTime) {
2614 // process the value immediately if screen has just turned on
Mike Lockwood6c97fca2009-10-20 08:10:00 -04002615 lightSensorChangedLocked(value);
2616 } else {
2617 // delay processing to debounce the sensor
2618 mLightSensorPendingValue = value;
2619 mHandler.postDelayed(mAutoBrightnessTask, LIGHT_SENSOR_DELAY);
2620 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002621 } else {
2622 mLightSensorPendingValue = -1;
2623 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002624 }
2625 }
2626
2627 public void onAccuracyChanged(Sensor sensor, int accuracy) {
2628 // ignore
2629 }
2630 };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002631}