blob: ca7d94a683ea4d56fe8e85ea631a5030dfcdc03c [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
19import com.android.internal.app.IBatteryStats;
20import com.android.server.am.BatteryStatsService;
21
22import android.app.ActivityManagerNative;
23import android.app.IActivityManager;
24import android.content.BroadcastReceiver;
25import android.content.ContentQueryMap;
26import android.content.ContentResolver;
27import android.content.Context;
28import android.content.Intent;
29import android.content.IntentFilter;
30import android.content.pm.PackageManager;
Mike Lockwoodd7786b42009-10-15 17:09:16 -070031import android.content.res.Resources;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080032import android.database.Cursor;
Mike Lockwoodbc706a02009-07-27 13:50:57 -070033import android.hardware.Sensor;
34import android.hardware.SensorEvent;
35import android.hardware.SensorEventListener;
36import android.hardware.SensorManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080037import android.os.BatteryStats;
38import android.os.Binder;
39import android.os.Handler;
40import android.os.HandlerThread;
41import android.os.IBinder;
42import android.os.IPowerManager;
43import android.os.LocalPowerManager;
44import android.os.Power;
45import android.os.PowerManager;
46import android.os.Process;
47import android.os.RemoteException;
48import android.os.SystemClock;
49import android.provider.Settings.SettingNotFoundException;
50import android.provider.Settings;
51import android.util.EventLog;
52import android.util.Log;
53import android.view.WindowManagerPolicy;
54import static android.provider.Settings.System.DIM_SCREEN;
55import static android.provider.Settings.System.SCREEN_BRIGHTNESS;
Dan Murphy951764b2009-08-27 14:59:03 -050056import static android.provider.Settings.System.SCREEN_BRIGHTNESS_MODE;
Mike Lockwooddc3494e2009-10-14 21:17:09 -070057import static android.provider.Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080058import static android.provider.Settings.System.SCREEN_OFF_TIMEOUT;
59import static android.provider.Settings.System.STAY_ON_WHILE_PLUGGED_IN;
60
61import java.io.FileDescriptor;
Doug Zongker50a21f42009-11-19 12:49:53 -080062import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080063import java.io.PrintWriter;
64import java.util.ArrayList;
65import java.util.HashMap;
66import java.util.Observable;
67import java.util.Observer;
68
Mike Lockwoodbc706a02009-07-27 13:50:57 -070069class PowerManagerService extends IPowerManager.Stub
Mike Lockwood8738e0c2009-10-04 08:44:47 -040070 implements LocalPowerManager, Watchdog.Monitor {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080071
72 private static final String TAG = "PowerManagerService";
73 static final String PARTIAL_NAME = "PowerManagerService";
74
75 private static final boolean LOG_PARTIAL_WL = false;
76
77 // Indicates whether touch-down cycles should be logged as part of the
78 // LOG_POWER_SCREEN_STATE log events
79 private static final boolean LOG_TOUCH_DOWNS = true;
80
81 private static final int LOCK_MASK = PowerManager.PARTIAL_WAKE_LOCK
82 | PowerManager.SCREEN_DIM_WAKE_LOCK
83 | PowerManager.SCREEN_BRIGHT_WAKE_LOCK
Mike Lockwoodbc706a02009-07-27 13:50:57 -070084 | PowerManager.FULL_WAKE_LOCK
85 | PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080086
87 // time since last state: time since last event:
88 // The short keylight delay comes from Gservices; this is the default.
89 private static final int SHORT_KEYLIGHT_DELAY_DEFAULT = 6000; // t+6 sec
90 private static final int MEDIUM_KEYLIGHT_DELAY = 15000; // t+15 sec
91 private static final int LONG_KEYLIGHT_DELAY = 6000; // t+6 sec
92 private static final int LONG_DIM_TIME = 7000; // t+N-5 sec
93
Mike Lockwoodd7786b42009-10-15 17:09:16 -070094 // How long to wait to debounce light sensor changes.
Mike Lockwood9b8136922009-11-06 15:53:59 -050095 private static final int LIGHT_SENSOR_DELAY = 2000;
Mike Lockwoodd7786b42009-10-15 17:09:16 -070096
Mike Lockwood20f87d72009-11-05 16:08:51 -050097 // For debouncing the proximity sensor.
98 private static final int PROXIMITY_SENSOR_DELAY = 1000;
99
Mike Lockwoodd20ea362009-09-15 00:13:38 -0400100 // trigger proximity if distance is less than 5 cm
101 private static final float PROXIMITY_THRESHOLD = 5.0f;
102
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800103 // Cached Gservices settings; see updateGservicesValues()
104 private int mShortKeylightDelay = SHORT_KEYLIGHT_DELAY_DEFAULT;
105
106 // flags for setPowerState
107 private static final int SCREEN_ON_BIT = 0x00000001;
108 private static final int SCREEN_BRIGHT_BIT = 0x00000002;
109 private static final int BUTTON_BRIGHT_BIT = 0x00000004;
110 private static final int KEYBOARD_BRIGHT_BIT = 0x00000008;
111 private static final int BATTERY_LOW_BIT = 0x00000010;
112
113 // values for setPowerState
114
115 // SCREEN_OFF == everything off
116 private static final int SCREEN_OFF = 0x00000000;
117
118 // SCREEN_DIM == screen on, screen backlight dim
119 private static final int SCREEN_DIM = SCREEN_ON_BIT;
120
121 // SCREEN_BRIGHT == screen on, screen backlight bright
122 private static final int SCREEN_BRIGHT = SCREEN_ON_BIT | SCREEN_BRIGHT_BIT;
123
124 // SCREEN_BUTTON_BRIGHT == screen on, screen and button backlights bright
125 private static final int SCREEN_BUTTON_BRIGHT = SCREEN_BRIGHT | BUTTON_BRIGHT_BIT;
126
127 // SCREEN_BUTTON_BRIGHT == screen on, screen, button and keyboard backlights bright
128 private static final int ALL_BRIGHT = SCREEN_BUTTON_BRIGHT | KEYBOARD_BRIGHT_BIT;
129
130 // used for noChangeLights in setPowerState()
131 private static final int LIGHTS_MASK = SCREEN_BRIGHT_BIT | BUTTON_BRIGHT_BIT | KEYBOARD_BRIGHT_BIT;
132
133 static final boolean ANIMATE_SCREEN_LIGHTS = true;
134 static final boolean ANIMATE_BUTTON_LIGHTS = false;
135 static final boolean ANIMATE_KEYBOARD_LIGHTS = false;
136
137 static final int ANIM_STEPS = 60/4;
Mike Lockwooddd9668e2009-10-27 15:47:02 -0400138 // Slower animation for autobrightness changes
139 static final int AUTOBRIGHTNESS_ANIM_STEPS = 60;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800140
141 // These magic numbers are the initial state of the LEDs at boot. Ideally
142 // we should read them from the driver, but our current hardware returns 0
143 // for the initial value. Oops!
144 static final int INITIAL_SCREEN_BRIGHTNESS = 255;
145 static final int INITIAL_BUTTON_BRIGHTNESS = Power.BRIGHTNESS_OFF;
146 static final int INITIAL_KEYBOARD_BRIGHTNESS = Power.BRIGHTNESS_OFF;
147
148 static final int LOG_POWER_SLEEP_REQUESTED = 2724;
149 static final int LOG_POWER_SCREEN_BROADCAST_SEND = 2725;
150 static final int LOG_POWER_SCREEN_BROADCAST_DONE = 2726;
151 static final int LOG_POWER_SCREEN_BROADCAST_STOP = 2727;
152 static final int LOG_POWER_SCREEN_STATE = 2728;
153 static final int LOG_POWER_PARTIAL_WAKE_STATE = 2729;
154
155 private final int MY_UID;
156
157 private boolean mDoneBooting = false;
Mike Lockwood2d7bb812009-11-15 18:12:22 -0500158 private boolean mBootCompleted = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800159 private int mStayOnConditions = 0;
Joe Onorato128e7292009-03-24 18:41:31 -0700160 private int[] mBroadcastQueue = new int[] { -1, -1, -1 };
161 private int[] mBroadcastWhy = new int[3];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800162 private int mPartialCount = 0;
163 private int mPowerState;
164 private boolean mOffBecauseOfUser;
165 private int mUserState;
166 private boolean mKeyboardVisible = false;
167 private boolean mUserActivityAllowed = true;
Mike Lockwoodee2b0942009-11-09 14:09:02 -0500168 private int mProximityWakeLockCount = 0;
169 private boolean mProximitySensorEnabled = false;
Mike Lockwood36fc3022009-08-25 16:49:06 -0700170 private boolean mProximitySensorActive = false;
Mike Lockwood20f87d72009-11-05 16:08:51 -0500171 private int mProximityPendingValue = -1; // -1 == nothing, 0 == inactive, 1 == active
172 private long mLastProximityEventTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800173 private int mTotalDelaySetting;
174 private int mKeylightDelay;
175 private int mDimDelay;
176 private int mScreenOffDelay;
177 private int mWakeLockState;
178 private long mLastEventTime = 0;
179 private long mScreenOffTime;
180 private volatile WindowManagerPolicy mPolicy;
181 private final LockList mLocks = new LockList();
182 private Intent mScreenOffIntent;
183 private Intent mScreenOnIntent;
Mike Lockwood3a322132009-11-24 00:30:52 -0500184 private LightsService mLightsService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800185 private Context mContext;
186 private UnsynchronizedWakeLock mBroadcastWakeLock;
187 private UnsynchronizedWakeLock mStayOnWhilePluggedInScreenDimLock;
188 private UnsynchronizedWakeLock mStayOnWhilePluggedInPartialLock;
189 private UnsynchronizedWakeLock mPreventScreenOnPartialLock;
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500190 private UnsynchronizedWakeLock mProximityPartialLock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800191 private HandlerThread mHandlerThread;
192 private Handler mHandler;
193 private TimeoutTask mTimeoutTask = new TimeoutTask();
194 private LightAnimator mLightAnimator = new LightAnimator();
195 private final BrightnessState mScreenBrightness
The Android Open Source Project10592532009-03-18 17:39:46 -0700196 = new BrightnessState(SCREEN_BRIGHT_BIT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800197 private final BrightnessState mKeyboardBrightness
The Android Open Source Project10592532009-03-18 17:39:46 -0700198 = new BrightnessState(KEYBOARD_BRIGHT_BIT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800199 private final BrightnessState mButtonBrightness
The Android Open Source Project10592532009-03-18 17:39:46 -0700200 = new BrightnessState(BUTTON_BRIGHT_BIT);
Joe Onorato128e7292009-03-24 18:41:31 -0700201 private boolean mStillNeedSleepNotification;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800202 private boolean mIsPowered = false;
203 private IActivityManager mActivityService;
204 private IBatteryStats mBatteryStats;
205 private BatteryService mBatteryService;
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700206 private SensorManager mSensorManager;
207 private Sensor mProximitySensor;
Mike Lockwood8738e0c2009-10-04 08:44:47 -0400208 private Sensor mLightSensor;
209 private boolean mLightSensorEnabled;
210 private float mLightSensorValue = -1;
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700211 private float mLightSensorPendingValue = -1;
Mike Lockwoodfb73f792009-11-20 11:31:18 -0500212 private int mLightSensorScreenBrightness = -1;
213 private int mLightSensorButtonBrightness = -1;
214 private int mLightSensorKeyboardBrightness = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800215 private boolean mDimScreen = true;
216 private long mNextTimeout;
217 private volatile int mPokey = 0;
218 private volatile boolean mPokeAwakeOnSet = false;
219 private volatile boolean mInitComplete = false;
220 private HashMap<IBinder,PokeLock> mPokeLocks = new HashMap<IBinder,PokeLock>();
Mike Lockwood20ee6f22009-11-07 20:33:47 -0500221 // mLastScreenOnTime is the time the screen was last turned on
222 private long mLastScreenOnTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800223 private boolean mPreventScreenOn;
224 private int mScreenBrightnessOverride = -1;
Mike Lockwoodfb73f792009-11-20 11:31:18 -0500225 private int mButtonBrightnessOverride = -1;
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400226 private boolean mUseSoftwareAutoBrightness;
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700227 private boolean mAutoBrightessEnabled;
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700228 private int[] mAutoBrightnessLevels;
229 private int[] mLcdBacklightValues;
230 private int[] mButtonBacklightValues;
231 private int[] mKeyboardBacklightValues;
Mike Lockwood20ee6f22009-11-07 20:33:47 -0500232 private int mLightSensorWarmupTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800233
234 // Used when logging number and duration of touch-down cycles
235 private long mTotalTouchDownTime;
236 private long mLastTouchDown;
237 private int mTouchCycles;
238
239 // could be either static or controllable at runtime
240 private static final boolean mSpew = false;
Mike Lockwoodee2b0942009-11-09 14:09:02 -0500241 private static final boolean mDebugProximitySensor = (true || mSpew);
Mike Lockwooddd9668e2009-10-27 15:47:02 -0400242 private static final boolean mDebugLightSensor = (false || mSpew);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800243
244 /*
245 static PrintStream mLog;
246 static {
247 try {
248 mLog = new PrintStream("/data/power.log");
249 }
250 catch (FileNotFoundException e) {
251 android.util.Log.e(TAG, "Life is hard", e);
252 }
253 }
254 static class Log {
255 static void d(String tag, String s) {
256 mLog.println(s);
257 android.util.Log.d(tag, s);
258 }
259 static void i(String tag, String s) {
260 mLog.println(s);
261 android.util.Log.i(tag, s);
262 }
263 static void w(String tag, String s) {
264 mLog.println(s);
265 android.util.Log.w(tag, s);
266 }
267 static void e(String tag, String s) {
268 mLog.println(s);
269 android.util.Log.e(tag, s);
270 }
271 }
272 */
273
274 /**
275 * This class works around a deadlock between the lock in PowerManager.WakeLock
276 * and our synchronizing on mLocks. PowerManager.WakeLock synchronizes on its
277 * mToken object so it can be accessed from any thread, but it calls into here
278 * with its lock held. This class is essentially a reimplementation of
279 * PowerManager.WakeLock, but without that extra synchronized block, because we'll
280 * only call it with our own locks held.
281 */
282 private class UnsynchronizedWakeLock {
283 int mFlags;
284 String mTag;
285 IBinder mToken;
286 int mCount = 0;
287 boolean mRefCounted;
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500288 boolean mHeld;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800289
290 UnsynchronizedWakeLock(int flags, String tag, boolean refCounted) {
291 mFlags = flags;
292 mTag = tag;
293 mToken = new Binder();
294 mRefCounted = refCounted;
295 }
296
297 public void acquire() {
298 if (!mRefCounted || mCount++ == 0) {
299 long ident = Binder.clearCallingIdentity();
300 try {
301 PowerManagerService.this.acquireWakeLockLocked(mFlags, mToken,
302 MY_UID, mTag);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500303 mHeld = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800304 } finally {
305 Binder.restoreCallingIdentity(ident);
306 }
307 }
308 }
309
310 public void release() {
311 if (!mRefCounted || --mCount == 0) {
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500312 PowerManagerService.this.releaseWakeLockLocked(mToken, 0, false);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500313 mHeld = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800314 }
315 if (mCount < 0) {
316 throw new RuntimeException("WakeLock under-locked " + mTag);
317 }
318 }
319
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500320 public boolean isHeld()
321 {
322 return mHeld;
323 }
324
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800325 public String toString() {
326 return "UnsynchronizedWakeLock(mFlags=0x" + Integer.toHexString(mFlags)
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500327 + " mCount=" + mCount + " mHeld=" + mHeld + ")";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800328 }
329 }
330
331 private final class BatteryReceiver extends BroadcastReceiver {
332 @Override
333 public void onReceive(Context context, Intent intent) {
334 synchronized (mLocks) {
335 boolean wasPowered = mIsPowered;
336 mIsPowered = mBatteryService.isPowered();
337
338 if (mIsPowered != wasPowered) {
339 // update mStayOnWhilePluggedIn wake lock
340 updateWakeLockLocked();
341
342 // treat plugging and unplugging the devices as a user activity.
343 // users find it disconcerting when they unplug the device
344 // and it shuts off right away.
345 // temporarily set mUserActivityAllowed to true so this will work
346 // even when the keyguard is on.
347 synchronized (mLocks) {
Mike Lockwood200b30b2009-09-20 00:23:59 -0400348 forceUserActivityLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800349 }
350 }
351 }
352 }
353 }
354
Mike Lockwood2d7bb812009-11-15 18:12:22 -0500355 private final class BootCompletedReceiver extends BroadcastReceiver {
356 @Override
357 public void onReceive(Context context, Intent intent) {
358 bootCompleted();
359 }
360 }
361
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800362 /**
363 * Set the setting that determines whether the device stays on when plugged in.
364 * The argument is a bit string, with each bit specifying a power source that,
365 * when the device is connected to that source, causes the device to stay on.
366 * See {@link android.os.BatteryManager} for the list of power sources that
367 * can be specified. Current values include {@link android.os.BatteryManager#BATTERY_PLUGGED_AC}
368 * and {@link android.os.BatteryManager#BATTERY_PLUGGED_USB}
369 * @param val an {@code int} containing the bits that specify which power sources
370 * should cause the device to stay on.
371 */
372 public void setStayOnSetting(int val) {
373 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SETTINGS, null);
374 Settings.System.putInt(mContext.getContentResolver(),
375 Settings.System.STAY_ON_WHILE_PLUGGED_IN, val);
376 }
377
378 private class SettingsObserver implements Observer {
379 private int getInt(String name) {
380 return mSettings.getValues(name).getAsInteger(Settings.System.VALUE);
381 }
382
383 public void update(Observable o, Object arg) {
384 synchronized (mLocks) {
385 // STAY_ON_WHILE_PLUGGED_IN
386 mStayOnConditions = getInt(STAY_ON_WHILE_PLUGGED_IN);
387 updateWakeLockLocked();
388
389 // SCREEN_OFF_TIMEOUT
390 mTotalDelaySetting = getInt(SCREEN_OFF_TIMEOUT);
391
392 // DIM_SCREEN
393 //mDimScreen = getInt(DIM_SCREEN) != 0;
394
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700395 // SCREEN_BRIGHTNESS_MODE
396 setScreenBrightnessMode(getInt(SCREEN_BRIGHTNESS_MODE));
397
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800398 // recalculate everything
399 setScreenOffTimeoutsLocked();
400 }
401 }
402 }
403
404 PowerManagerService()
405 {
406 // Hack to get our uid... should have a func for this.
407 long token = Binder.clearCallingIdentity();
408 MY_UID = Binder.getCallingUid();
409 Binder.restoreCallingIdentity(token);
410
411 // XXX remove this when the kernel doesn't timeout wake locks
412 Power.setLastUserActivityTimeout(7*24*3600*1000); // one week
413
414 // assume nothing is on yet
415 mUserState = mPowerState = 0;
416
417 // Add ourself to the Watchdog monitors.
418 Watchdog.getInstance().addMonitor(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800419 }
420
421 private ContentQueryMap mSettings;
422
Mike Lockwood3a322132009-11-24 00:30:52 -0500423 void init(Context context, LightsService lights, IActivityManager activity,
The Android Open Source Project10592532009-03-18 17:39:46 -0700424 BatteryService battery) {
Mike Lockwood3a322132009-11-24 00:30:52 -0500425 mLightsService = lights;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800426 mContext = context;
427 mActivityService = activity;
428 mBatteryStats = BatteryStatsService.getService();
429 mBatteryService = battery;
430
431 mHandlerThread = new HandlerThread("PowerManagerService") {
432 @Override
433 protected void onLooperPrepared() {
434 super.onLooperPrepared();
435 initInThread();
436 }
437 };
438 mHandlerThread.start();
439
440 synchronized (mHandlerThread) {
441 while (!mInitComplete) {
442 try {
443 mHandlerThread.wait();
444 } catch (InterruptedException e) {
445 // Ignore
446 }
447 }
448 }
449 }
450
451 void initInThread() {
452 mHandler = new Handler();
453
454 mBroadcastWakeLock = new UnsynchronizedWakeLock(
Joe Onorato128e7292009-03-24 18:41:31 -0700455 PowerManager.PARTIAL_WAKE_LOCK, "sleep_broadcast", true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800456 mStayOnWhilePluggedInScreenDimLock = new UnsynchronizedWakeLock(
457 PowerManager.SCREEN_DIM_WAKE_LOCK, "StayOnWhilePluggedIn Screen Dim", false);
458 mStayOnWhilePluggedInPartialLock = new UnsynchronizedWakeLock(
459 PowerManager.PARTIAL_WAKE_LOCK, "StayOnWhilePluggedIn Partial", false);
460 mPreventScreenOnPartialLock = new UnsynchronizedWakeLock(
461 PowerManager.PARTIAL_WAKE_LOCK, "PreventScreenOn Partial", false);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500462 mProximityPartialLock = new UnsynchronizedWakeLock(
463 PowerManager.PARTIAL_WAKE_LOCK, "Proximity Partial", false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800464
465 mScreenOnIntent = new Intent(Intent.ACTION_SCREEN_ON);
466 mScreenOnIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
467 mScreenOffIntent = new Intent(Intent.ACTION_SCREEN_OFF);
468 mScreenOffIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
469
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700470 Resources resources = mContext.getResources();
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400471
472 // read settings for auto-brightness
473 mUseSoftwareAutoBrightness = resources.getBoolean(
474 com.android.internal.R.bool.config_automatic_brightness_available);
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400475 if (mUseSoftwareAutoBrightness) {
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700476 mAutoBrightnessLevels = resources.getIntArray(
477 com.android.internal.R.array.config_autoBrightnessLevels);
478 mLcdBacklightValues = resources.getIntArray(
479 com.android.internal.R.array.config_autoBrightnessLcdBacklightValues);
480 mButtonBacklightValues = resources.getIntArray(
481 com.android.internal.R.array.config_autoBrightnessButtonBacklightValues);
482 mKeyboardBacklightValues = resources.getIntArray(
483 com.android.internal.R.array.config_autoBrightnessKeyboardBacklightValues);
Mike Lockwood20ee6f22009-11-07 20:33:47 -0500484 mLightSensorWarmupTime = resources.getInteger(
485 com.android.internal.R.integer.config_lightSensorWarmupTime);
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700486 }
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700487
488 ContentResolver resolver = mContext.getContentResolver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800489 Cursor settingsCursor = resolver.query(Settings.System.CONTENT_URI, null,
490 "(" + Settings.System.NAME + "=?) or ("
491 + Settings.System.NAME + "=?) or ("
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700492 + Settings.System.NAME + "=?) or ("
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800493 + Settings.System.NAME + "=?)",
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700494 new String[]{STAY_ON_WHILE_PLUGGED_IN, SCREEN_OFF_TIMEOUT, DIM_SCREEN,
495 SCREEN_BRIGHTNESS_MODE},
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800496 null);
497 mSettings = new ContentQueryMap(settingsCursor, Settings.System.NAME, true, mHandler);
498 SettingsObserver settingsObserver = new SettingsObserver();
499 mSettings.addObserver(settingsObserver);
500
501 // pretend that the settings changed so we will get their initial state
502 settingsObserver.update(mSettings, null);
503
504 // register for the battery changed notifications
505 IntentFilter filter = new IntentFilter();
506 filter.addAction(Intent.ACTION_BATTERY_CHANGED);
507 mContext.registerReceiver(new BatteryReceiver(), filter);
Mike Lockwood2d7bb812009-11-15 18:12:22 -0500508 filter = new IntentFilter();
509 filter.addAction(Intent.ACTION_BOOT_COMPLETED);
510 mContext.registerReceiver(new BootCompletedReceiver(), filter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800511
512 // Listen for Gservices changes
513 IntentFilter gservicesChangedFilter =
514 new IntentFilter(Settings.Gservices.CHANGED_ACTION);
515 mContext.registerReceiver(new GservicesChangedReceiver(), gservicesChangedFilter);
516 // And explicitly do the initial update of our cached settings
517 updateGservicesValues();
518
Mike Lockwood4984e732009-11-01 08:16:33 -0500519 if (mUseSoftwareAutoBrightness) {
Mike Lockwood6c97fca2009-10-20 08:10:00 -0400520 // turn the screen on
521 setPowerState(SCREEN_BRIGHT);
522 } else {
523 // turn everything on
524 setPowerState(ALL_BRIGHT);
525 }
Dan Murphy951764b2009-08-27 14:59:03 -0500526
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800527 synchronized (mHandlerThread) {
528 mInitComplete = true;
529 mHandlerThread.notifyAll();
530 }
531 }
532
533 private class WakeLock implements IBinder.DeathRecipient
534 {
535 WakeLock(int f, IBinder b, String t, int u) {
536 super();
537 flags = f;
538 binder = b;
539 tag = t;
540 uid = u == MY_UID ? Process.SYSTEM_UID : u;
541 if (u != MY_UID || (
542 !"KEEP_SCREEN_ON_FLAG".equals(tag)
543 && !"KeyInputQueue".equals(tag))) {
544 monitorType = (f & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK
545 ? BatteryStats.WAKE_TYPE_PARTIAL
546 : BatteryStats.WAKE_TYPE_FULL;
547 } else {
548 monitorType = -1;
549 }
550 try {
551 b.linkToDeath(this, 0);
552 } catch (RemoteException e) {
553 binderDied();
554 }
555 }
556 public void binderDied() {
557 synchronized (mLocks) {
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500558 releaseWakeLockLocked(this.binder, 0, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800559 }
560 }
561 final int flags;
562 final IBinder binder;
563 final String tag;
564 final int uid;
565 final int monitorType;
566 boolean activated = true;
567 int minState;
568 }
569
570 private void updateWakeLockLocked() {
571 if (mStayOnConditions != 0 && mBatteryService.isPowered(mStayOnConditions)) {
572 // keep the device on if we're plugged in and mStayOnWhilePluggedIn is set.
573 mStayOnWhilePluggedInScreenDimLock.acquire();
574 mStayOnWhilePluggedInPartialLock.acquire();
575 } else {
576 mStayOnWhilePluggedInScreenDimLock.release();
577 mStayOnWhilePluggedInPartialLock.release();
578 }
579 }
580
581 private boolean isScreenLock(int flags)
582 {
583 int n = flags & LOCK_MASK;
584 return n == PowerManager.FULL_WAKE_LOCK
585 || n == PowerManager.SCREEN_BRIGHT_WAKE_LOCK
586 || n == PowerManager.SCREEN_DIM_WAKE_LOCK;
587 }
588
589 public void acquireWakeLock(int flags, IBinder lock, String tag) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800590 int uid = Binder.getCallingUid();
Michael Chane96440f2009-05-06 10:27:36 -0700591 if (uid != Process.myUid()) {
592 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
593 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800594 long ident = Binder.clearCallingIdentity();
595 try {
596 synchronized (mLocks) {
597 acquireWakeLockLocked(flags, lock, uid, tag);
598 }
599 } finally {
600 Binder.restoreCallingIdentity(ident);
601 }
602 }
603
604 public void acquireWakeLockLocked(int flags, IBinder lock, int uid, String tag) {
605 int acquireUid = -1;
606 String acquireName = null;
607 int acquireType = -1;
608
609 if (mSpew) {
610 Log.d(TAG, "acquireWakeLock flags=0x" + Integer.toHexString(flags) + " tag=" + tag);
611 }
612
613 int index = mLocks.getIndex(lock);
614 WakeLock wl;
615 boolean newlock;
616 if (index < 0) {
617 wl = new WakeLock(flags, lock, tag, uid);
618 switch (wl.flags & LOCK_MASK)
619 {
620 case PowerManager.FULL_WAKE_LOCK:
Mike Lockwood4984e732009-11-01 08:16:33 -0500621 if (mUseSoftwareAutoBrightness) {
Mike Lockwood3333fa42009-10-26 14:50:42 -0400622 wl.minState = SCREEN_BRIGHT;
623 } else {
624 wl.minState = (mKeyboardVisible ? ALL_BRIGHT : SCREEN_BUTTON_BRIGHT);
625 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800626 break;
627 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
628 wl.minState = SCREEN_BRIGHT;
629 break;
630 case PowerManager.SCREEN_DIM_WAKE_LOCK:
631 wl.minState = SCREEN_DIM;
632 break;
633 case PowerManager.PARTIAL_WAKE_LOCK:
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700634 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800635 break;
636 default:
637 // just log and bail. we're in the server, so don't
638 // throw an exception.
639 Log.e(TAG, "bad wakelock type for lock '" + tag + "' "
640 + " flags=" + flags);
641 return;
642 }
643 mLocks.addLock(wl);
644 newlock = true;
645 } else {
646 wl = mLocks.get(index);
647 newlock = false;
648 }
649 if (isScreenLock(flags)) {
650 // if this causes a wakeup, we reactivate all of the locks and
651 // set it to whatever they want. otherwise, we modulate that
652 // by the current state so we never turn it more on than
653 // it already is.
654 if ((wl.flags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) {
Michael Chane96440f2009-05-06 10:27:36 -0700655 int oldWakeLockState = mWakeLockState;
656 mWakeLockState = mLocks.reactivateScreenLocksLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800657 if (mSpew) {
658 Log.d(TAG, "wakeup here mUserState=0x" + Integer.toHexString(mUserState)
Michael Chane96440f2009-05-06 10:27:36 -0700659 + " mWakeLockState=0x"
660 + Integer.toHexString(mWakeLockState)
661 + " previous wakeLockState=0x" + Integer.toHexString(oldWakeLockState));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800662 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800663 } else {
664 if (mSpew) {
665 Log.d(TAG, "here mUserState=0x" + Integer.toHexString(mUserState)
666 + " mLocks.gatherState()=0x"
667 + Integer.toHexString(mLocks.gatherState())
668 + " mWakeLockState=0x" + Integer.toHexString(mWakeLockState));
669 }
670 mWakeLockState = (mUserState | mWakeLockState) & mLocks.gatherState();
671 }
672 setPowerState(mWakeLockState | mUserState);
673 }
674 else if ((flags & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK) {
675 if (newlock) {
676 mPartialCount++;
677 if (mPartialCount == 1) {
678 if (LOG_PARTIAL_WL) EventLog.writeEvent(LOG_POWER_PARTIAL_WAKE_STATE, 1, tag);
679 }
680 }
681 Power.acquireWakeLock(Power.PARTIAL_WAKE_LOCK,PARTIAL_NAME);
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700682 } else if ((flags & LOCK_MASK) == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK) {
Mike Lockwoodee2b0942009-11-09 14:09:02 -0500683 mProximityWakeLockCount++;
684 if (mProximityWakeLockCount == 1) {
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700685 enableProximityLockLocked();
686 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800687 }
688 if (newlock) {
689 acquireUid = wl.uid;
690 acquireName = wl.tag;
691 acquireType = wl.monitorType;
692 }
693
694 if (acquireType >= 0) {
695 try {
696 mBatteryStats.noteStartWakelock(acquireUid, acquireName, acquireType);
697 } catch (RemoteException e) {
698 // Ignore
699 }
700 }
701 }
702
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500703 public void releaseWakeLock(IBinder lock, int flags) {
Michael Chane96440f2009-05-06 10:27:36 -0700704 int uid = Binder.getCallingUid();
705 if (uid != Process.myUid()) {
706 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
707 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800708
709 synchronized (mLocks) {
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500710 releaseWakeLockLocked(lock, flags, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800711 }
712 }
713
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500714 private void releaseWakeLockLocked(IBinder lock, int flags, boolean death) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800715 int releaseUid;
716 String releaseName;
717 int releaseType;
718
719 WakeLock wl = mLocks.removeLock(lock);
720 if (wl == null) {
721 return;
722 }
723
724 if (mSpew) {
725 Log.d(TAG, "releaseWakeLock flags=0x"
726 + Integer.toHexString(wl.flags) + " tag=" + wl.tag);
727 }
728
729 if (isScreenLock(wl.flags)) {
730 mWakeLockState = mLocks.gatherState();
731 // goes in the middle to reduce flicker
732 if ((wl.flags & PowerManager.ON_AFTER_RELEASE) != 0) {
733 userActivity(SystemClock.uptimeMillis(), false);
734 }
735 setPowerState(mWakeLockState | mUserState);
736 }
737 else if ((wl.flags & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK) {
738 mPartialCount--;
739 if (mPartialCount == 0) {
740 if (LOG_PARTIAL_WL) EventLog.writeEvent(LOG_POWER_PARTIAL_WAKE_STATE, 0, wl.tag);
741 Power.releaseWakeLock(PARTIAL_NAME);
742 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700743 } else if ((wl.flags & LOCK_MASK) == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK) {
Mike Lockwoodee2b0942009-11-09 14:09:02 -0500744 mProximityWakeLockCount--;
745 if (mProximityWakeLockCount == 0) {
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500746 if (mProximitySensorActive &&
747 ((flags & PowerManager.WAIT_FOR_PROXIMITY_NEGATIVE) != 0)) {
Mike Lockwoodee2b0942009-11-09 14:09:02 -0500748 // wait for proximity sensor to go negative before disabling sensor
749 if (mDebugProximitySensor) {
750 Log.d(TAG, "waiting for proximity sensor to go negative");
751 }
752 } else {
753 disableProximityLockLocked();
754 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700755 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800756 }
757 // Unlink the lock from the binder.
758 wl.binder.unlinkToDeath(wl, 0);
759 releaseUid = wl.uid;
760 releaseName = wl.tag;
761 releaseType = wl.monitorType;
762
763 if (releaseType >= 0) {
764 long origId = Binder.clearCallingIdentity();
765 try {
766 mBatteryStats.noteStopWakelock(releaseUid, releaseName, releaseType);
767 } catch (RemoteException e) {
768 // Ignore
769 } finally {
770 Binder.restoreCallingIdentity(origId);
771 }
772 }
773 }
774
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800775 private class PokeLock implements IBinder.DeathRecipient
776 {
777 PokeLock(int p, IBinder b, String t) {
778 super();
779 this.pokey = p;
780 this.binder = b;
781 this.tag = t;
782 try {
783 b.linkToDeath(this, 0);
784 } catch (RemoteException e) {
785 binderDied();
786 }
787 }
788 public void binderDied() {
789 setPokeLock(0, this.binder, this.tag);
790 }
791 int pokey;
792 IBinder binder;
793 String tag;
794 boolean awakeOnSet;
795 }
796
797 public void setPokeLock(int pokey, IBinder token, String tag) {
798 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
799 if (token == null) {
800 Log.e(TAG, "setPokeLock got null token for tag='" + tag + "'");
801 return;
802 }
803
804 if ((pokey & POKE_LOCK_TIMEOUT_MASK) == POKE_LOCK_TIMEOUT_MASK) {
805 throw new IllegalArgumentException("setPokeLock can't have both POKE_LOCK_SHORT_TIMEOUT"
806 + " and POKE_LOCK_MEDIUM_TIMEOUT");
807 }
808
809 synchronized (mLocks) {
810 if (pokey != 0) {
811 PokeLock p = mPokeLocks.get(token);
812 int oldPokey = 0;
813 if (p != null) {
814 oldPokey = p.pokey;
815 p.pokey = pokey;
816 } else {
817 p = new PokeLock(pokey, token, tag);
818 mPokeLocks.put(token, p);
819 }
820 int oldTimeout = oldPokey & POKE_LOCK_TIMEOUT_MASK;
821 int newTimeout = pokey & POKE_LOCK_TIMEOUT_MASK;
822 if (((mPowerState & SCREEN_ON_BIT) == 0) && (oldTimeout != newTimeout)) {
823 p.awakeOnSet = true;
824 }
825 } else {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -0700826 PokeLock rLock = mPokeLocks.remove(token);
827 if (rLock != null) {
828 token.unlinkToDeath(rLock, 0);
829 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800830 }
831
832 int oldPokey = mPokey;
833 int cumulative = 0;
834 boolean oldAwakeOnSet = mPokeAwakeOnSet;
835 boolean awakeOnSet = false;
836 for (PokeLock p: mPokeLocks.values()) {
837 cumulative |= p.pokey;
838 if (p.awakeOnSet) {
839 awakeOnSet = true;
840 }
841 }
842 mPokey = cumulative;
843 mPokeAwakeOnSet = awakeOnSet;
844
845 int oldCumulativeTimeout = oldPokey & POKE_LOCK_TIMEOUT_MASK;
846 int newCumulativeTimeout = pokey & POKE_LOCK_TIMEOUT_MASK;
847
848 if (oldCumulativeTimeout != newCumulativeTimeout) {
849 setScreenOffTimeoutsLocked();
850 // reset the countdown timer, but use the existing nextState so it doesn't
851 // change anything
852 setTimeoutLocked(SystemClock.uptimeMillis(), mTimeoutTask.nextState);
853 }
854 }
855 }
856
857 private static String lockType(int type)
858 {
859 switch (type)
860 {
861 case PowerManager.FULL_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -0700862 return "FULL_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800863 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -0700864 return "SCREEN_BRIGHT_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800865 case PowerManager.SCREEN_DIM_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -0700866 return "SCREEN_DIM_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800867 case PowerManager.PARTIAL_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -0700868 return "PARTIAL_WAKE_LOCK ";
869 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
870 return "PROXIMITY_SCREEN_OFF_WAKE_LOCK";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800871 default:
David Brown251faa62009-08-02 22:04:36 -0700872 return "??? ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800873 }
874 }
875
876 private static String dumpPowerState(int state) {
877 return (((state & KEYBOARD_BRIGHT_BIT) != 0)
878 ? "KEYBOARD_BRIGHT_BIT " : "")
879 + (((state & SCREEN_BRIGHT_BIT) != 0)
880 ? "SCREEN_BRIGHT_BIT " : "")
881 + (((state & SCREEN_ON_BIT) != 0)
882 ? "SCREEN_ON_BIT " : "")
883 + (((state & BATTERY_LOW_BIT) != 0)
884 ? "BATTERY_LOW_BIT " : "");
885 }
886
887 @Override
888 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
889 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
890 != PackageManager.PERMISSION_GRANTED) {
891 pw.println("Permission Denial: can't dump PowerManager from from pid="
892 + Binder.getCallingPid()
893 + ", uid=" + Binder.getCallingUid());
894 return;
895 }
896
897 long now = SystemClock.uptimeMillis();
898
899 pw.println("Power Manager State:");
900 pw.println(" mIsPowered=" + mIsPowered
901 + " mPowerState=" + mPowerState
902 + " mScreenOffTime=" + (SystemClock.elapsedRealtime()-mScreenOffTime)
903 + " ms");
904 pw.println(" mPartialCount=" + mPartialCount);
905 pw.println(" mWakeLockState=" + dumpPowerState(mWakeLockState));
906 pw.println(" mUserState=" + dumpPowerState(mUserState));
907 pw.println(" mPowerState=" + dumpPowerState(mPowerState));
908 pw.println(" mLocks.gather=" + dumpPowerState(mLocks.gatherState()));
909 pw.println(" mNextTimeout=" + mNextTimeout + " now=" + now
910 + " " + ((mNextTimeout-now)/1000) + "s from now");
911 pw.println(" mDimScreen=" + mDimScreen
912 + " mStayOnConditions=" + mStayOnConditions);
913 pw.println(" mOffBecauseOfUser=" + mOffBecauseOfUser
914 + " mUserState=" + mUserState);
Joe Onorato128e7292009-03-24 18:41:31 -0700915 pw.println(" mBroadcastQueue={" + mBroadcastQueue[0] + ',' + mBroadcastQueue[1]
916 + ',' + mBroadcastQueue[2] + "}");
917 pw.println(" mBroadcastWhy={" + mBroadcastWhy[0] + ',' + mBroadcastWhy[1]
918 + ',' + mBroadcastWhy[2] + "}");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800919 pw.println(" mPokey=" + mPokey + " mPokeAwakeonSet=" + mPokeAwakeOnSet);
920 pw.println(" mKeyboardVisible=" + mKeyboardVisible
921 + " mUserActivityAllowed=" + mUserActivityAllowed);
922 pw.println(" mKeylightDelay=" + mKeylightDelay + " mDimDelay=" + mDimDelay
923 + " mScreenOffDelay=" + mScreenOffDelay);
924 pw.println(" mPreventScreenOn=" + mPreventScreenOn
Mike Lockwoodfb73f792009-11-20 11:31:18 -0500925 + " mScreenBrightnessOverride=" + mScreenBrightnessOverride
926 + " mButtonBrightnessOverride=" + mButtonBrightnessOverride);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800927 pw.println(" mTotalDelaySetting=" + mTotalDelaySetting);
Mike Lockwood20ee6f22009-11-07 20:33:47 -0500928 pw.println(" mLastScreenOnTime=" + mLastScreenOnTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800929 pw.println(" mBroadcastWakeLock=" + mBroadcastWakeLock);
930 pw.println(" mStayOnWhilePluggedInScreenDimLock=" + mStayOnWhilePluggedInScreenDimLock);
931 pw.println(" mStayOnWhilePluggedInPartialLock=" + mStayOnWhilePluggedInPartialLock);
932 pw.println(" mPreventScreenOnPartialLock=" + mPreventScreenOnPartialLock);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500933 pw.println(" mProximityPartialLock=" + mProximityPartialLock);
Mike Lockwoodee2b0942009-11-09 14:09:02 -0500934 pw.println(" mProximityWakeLockCount=" + mProximityWakeLockCount);
935 pw.println(" mProximitySensorEnabled=" + mProximitySensorEnabled);
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700936 pw.println(" mProximitySensorActive=" + mProximitySensorActive);
Mike Lockwood20f87d72009-11-05 16:08:51 -0500937 pw.println(" mProximityPendingValue=" + mProximityPendingValue);
938 pw.println(" mLastProximityEventTime=" + mLastProximityEventTime);
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700939 pw.println(" mLightSensorEnabled=" + mLightSensorEnabled);
Mike Lockwoodfb73f792009-11-20 11:31:18 -0500940 pw.println(" mLightSensorValue=" + mLightSensorValue
941 + " mLightSensorPendingValue=" + mLightSensorPendingValue);
942 pw.println(" mLightSensorScreenBrightness=" + mLightSensorScreenBrightness
943 + " mLightSensorButtonBrightness=" + mLightSensorButtonBrightness
944 + " mLightSensorKeyboardBrightness=" + mLightSensorKeyboardBrightness);
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400945 pw.println(" mUseSoftwareAutoBrightness=" + mUseSoftwareAutoBrightness);
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700946 pw.println(" mAutoBrightessEnabled=" + mAutoBrightessEnabled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800947 mScreenBrightness.dump(pw, " mScreenBrightness: ");
948 mKeyboardBrightness.dump(pw, " mKeyboardBrightness: ");
949 mButtonBrightness.dump(pw, " mButtonBrightness: ");
950
951 int N = mLocks.size();
952 pw.println();
953 pw.println("mLocks.size=" + N + ":");
954 for (int i=0; i<N; i++) {
955 WakeLock wl = mLocks.get(i);
956 String type = lockType(wl.flags & LOCK_MASK);
957 String acquireCausesWakeup = "";
958 if ((wl.flags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) {
959 acquireCausesWakeup = "ACQUIRE_CAUSES_WAKEUP ";
960 }
961 String activated = "";
962 if (wl.activated) {
963 activated = " activated";
964 }
965 pw.println(" " + type + " '" + wl.tag + "'" + acquireCausesWakeup
966 + activated + " (minState=" + wl.minState + ")");
967 }
968
969 pw.println();
970 pw.println("mPokeLocks.size=" + mPokeLocks.size() + ":");
971 for (PokeLock p: mPokeLocks.values()) {
972 pw.println(" poke lock '" + p.tag + "':"
973 + ((p.pokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0
974 ? " POKE_LOCK_IGNORE_CHEEK_EVENTS" : "")
Joe Onoratoe68ffcb2009-03-24 19:11:13 -0700975 + ((p.pokey & POKE_LOCK_IGNORE_TOUCH_AND_CHEEK_EVENTS) != 0
976 ? " POKE_LOCK_IGNORE_TOUCH_AND_CHEEK_EVENTS" : "")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800977 + ((p.pokey & POKE_LOCK_SHORT_TIMEOUT) != 0
978 ? " POKE_LOCK_SHORT_TIMEOUT" : "")
979 + ((p.pokey & POKE_LOCK_MEDIUM_TIMEOUT) != 0
980 ? " POKE_LOCK_MEDIUM_TIMEOUT" : ""));
981 }
982
983 pw.println();
984 }
985
986 private void setTimeoutLocked(long now, int nextState)
987 {
Mike Lockwood2d7bb812009-11-15 18:12:22 -0500988 if (mBootCompleted) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800989 mHandler.removeCallbacks(mTimeoutTask);
990 mTimeoutTask.nextState = nextState;
991 long when = now;
992 switch (nextState)
993 {
994 case SCREEN_BRIGHT:
995 when += mKeylightDelay;
996 break;
997 case SCREEN_DIM:
998 if (mDimDelay >= 0) {
999 when += mDimDelay;
1000 break;
1001 } else {
1002 Log.w(TAG, "mDimDelay=" + mDimDelay + " while trying to dim");
1003 }
1004 case SCREEN_OFF:
1005 synchronized (mLocks) {
1006 when += mScreenOffDelay;
1007 }
1008 break;
1009 }
1010 if (mSpew) {
1011 Log.d(TAG, "setTimeoutLocked now=" + now + " nextState=" + nextState
1012 + " when=" + when);
1013 }
1014 mHandler.postAtTime(mTimeoutTask, when);
1015 mNextTimeout = when; // for debugging
1016 }
1017 }
1018
1019 private void cancelTimerLocked()
1020 {
1021 mHandler.removeCallbacks(mTimeoutTask);
1022 mTimeoutTask.nextState = -1;
1023 }
1024
1025 private class TimeoutTask implements Runnable
1026 {
1027 int nextState; // access should be synchronized on mLocks
1028 public void run()
1029 {
1030 synchronized (mLocks) {
1031 if (mSpew) {
1032 Log.d(TAG, "user activity timeout timed out nextState=" + this.nextState);
1033 }
1034
1035 if (nextState == -1) {
1036 return;
1037 }
1038
1039 mUserState = this.nextState;
1040 setPowerState(this.nextState | mWakeLockState);
1041
1042 long now = SystemClock.uptimeMillis();
1043
1044 switch (this.nextState)
1045 {
1046 case SCREEN_BRIGHT:
1047 if (mDimDelay >= 0) {
1048 setTimeoutLocked(now, SCREEN_DIM);
1049 break;
1050 }
1051 case SCREEN_DIM:
1052 setTimeoutLocked(now, SCREEN_OFF);
1053 break;
1054 }
1055 }
1056 }
1057 }
1058
1059 private void sendNotificationLocked(boolean on, int why)
1060 {
Joe Onorato64c62ba2009-03-24 20:13:57 -07001061 if (!on) {
1062 mStillNeedSleepNotification = false;
1063 }
1064
Joe Onorato128e7292009-03-24 18:41:31 -07001065 // Add to the queue.
1066 int index = 0;
1067 while (mBroadcastQueue[index] != -1) {
1068 index++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001069 }
Joe Onorato128e7292009-03-24 18:41:31 -07001070 mBroadcastQueue[index] = on ? 1 : 0;
1071 mBroadcastWhy[index] = why;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001072
Joe Onorato128e7292009-03-24 18:41:31 -07001073 // If we added it position 2, then there is a pair that can be stripped.
1074 // If we added it position 1 and we're turning the screen off, we can strip
1075 // the pair and do nothing, because the screen is already off, and therefore
1076 // keyguard has already been enabled.
1077 // However, if we added it at position 1 and we're turning it on, then position
1078 // 0 was to turn it off, and we can't strip that, because keyguard needs to come
1079 // on, so have to run the queue then.
1080 if (index == 2) {
1081 // Also, while we're collapsing them, if it's going to be an "off," and one
1082 // is off because of user, then use that, regardless of whether it's the first
1083 // or second one.
1084 if (!on && why == WindowManagerPolicy.OFF_BECAUSE_OF_USER) {
1085 mBroadcastWhy[0] = WindowManagerPolicy.OFF_BECAUSE_OF_USER;
1086 }
1087 mBroadcastQueue[0] = on ? 1 : 0;
1088 mBroadcastQueue[1] = -1;
1089 mBroadcastQueue[2] = -1;
1090 index = 0;
1091 }
1092 if (index == 1 && !on) {
1093 mBroadcastQueue[0] = -1;
1094 mBroadcastQueue[1] = -1;
1095 index = -1;
1096 // The wake lock was being held, but we're not actually going to do any
1097 // broadcasts, so release the wake lock.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001098 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_STOP, 1, mBroadcastWakeLock.mCount);
1099 mBroadcastWakeLock.release();
Joe Onorato128e7292009-03-24 18:41:31 -07001100 }
1101
1102 // Now send the message.
1103 if (index >= 0) {
1104 // Acquire the broadcast wake lock before changing the power
1105 // state. It will be release after the broadcast is sent.
1106 // We always increment the ref count for each notification in the queue
1107 // and always decrement when that notification is handled.
1108 mBroadcastWakeLock.acquire();
1109 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_SEND, mBroadcastWakeLock.mCount);
1110 mHandler.post(mNotificationTask);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001111 }
1112 }
1113
1114 private Runnable mNotificationTask = new Runnable()
1115 {
1116 public void run()
1117 {
Joe Onorato128e7292009-03-24 18:41:31 -07001118 while (true) {
1119 int value;
1120 int why;
1121 WindowManagerPolicy policy;
1122 synchronized (mLocks) {
1123 value = mBroadcastQueue[0];
1124 why = mBroadcastWhy[0];
1125 for (int i=0; i<2; i++) {
1126 mBroadcastQueue[i] = mBroadcastQueue[i+1];
1127 mBroadcastWhy[i] = mBroadcastWhy[i+1];
1128 }
1129 policy = getPolicyLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001130 }
Joe Onorato128e7292009-03-24 18:41:31 -07001131 if (value == 1) {
1132 mScreenOnStart = SystemClock.uptimeMillis();
1133
1134 policy.screenTurnedOn();
1135 try {
1136 ActivityManagerNative.getDefault().wakingUp();
1137 } catch (RemoteException e) {
1138 // ignore it
1139 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001140
Joe Onorato128e7292009-03-24 18:41:31 -07001141 if (mSpew) {
1142 Log.d(TAG, "mBroadcastWakeLock=" + mBroadcastWakeLock);
1143 }
1144 if (mContext != null && ActivityManagerNative.isSystemReady()) {
1145 mContext.sendOrderedBroadcast(mScreenOnIntent, null,
1146 mScreenOnBroadcastDone, mHandler, 0, null, null);
1147 } else {
1148 synchronized (mLocks) {
1149 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_STOP, 2,
1150 mBroadcastWakeLock.mCount);
1151 mBroadcastWakeLock.release();
1152 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001153 }
1154 }
Joe Onorato128e7292009-03-24 18:41:31 -07001155 else if (value == 0) {
1156 mScreenOffStart = SystemClock.uptimeMillis();
1157
1158 policy.screenTurnedOff(why);
1159 try {
1160 ActivityManagerNative.getDefault().goingToSleep();
1161 } catch (RemoteException e) {
1162 // ignore it.
1163 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001164
Joe Onorato128e7292009-03-24 18:41:31 -07001165 if (mContext != null && ActivityManagerNative.isSystemReady()) {
1166 mContext.sendOrderedBroadcast(mScreenOffIntent, null,
1167 mScreenOffBroadcastDone, mHandler, 0, null, null);
1168 } else {
1169 synchronized (mLocks) {
1170 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_STOP, 3,
1171 mBroadcastWakeLock.mCount);
1172 mBroadcastWakeLock.release();
1173 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001174 }
1175 }
Joe Onorato128e7292009-03-24 18:41:31 -07001176 else {
1177 // If we're in this case, then this handler is running for a previous
1178 // paired transaction. mBroadcastWakeLock will already have been released.
1179 break;
1180 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001181 }
1182 }
1183 };
1184
1185 long mScreenOnStart;
1186 private BroadcastReceiver mScreenOnBroadcastDone = new BroadcastReceiver() {
1187 public void onReceive(Context context, Intent intent) {
1188 synchronized (mLocks) {
1189 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_DONE, 1,
1190 SystemClock.uptimeMillis() - mScreenOnStart, mBroadcastWakeLock.mCount);
1191 mBroadcastWakeLock.release();
1192 }
1193 }
1194 };
1195
1196 long mScreenOffStart;
1197 private BroadcastReceiver mScreenOffBroadcastDone = new BroadcastReceiver() {
1198 public void onReceive(Context context, Intent intent) {
1199 synchronized (mLocks) {
1200 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_DONE, 0,
1201 SystemClock.uptimeMillis() - mScreenOffStart, mBroadcastWakeLock.mCount);
1202 mBroadcastWakeLock.release();
1203 }
1204 }
1205 };
1206
1207 void logPointerUpEvent() {
1208 if (LOG_TOUCH_DOWNS) {
1209 mTotalTouchDownTime += SystemClock.elapsedRealtime() - mLastTouchDown;
1210 mLastTouchDown = 0;
1211 }
1212 }
1213
1214 void logPointerDownEvent() {
1215 if (LOG_TOUCH_DOWNS) {
1216 // If we are not already timing a down/up sequence
1217 if (mLastTouchDown == 0) {
1218 mLastTouchDown = SystemClock.elapsedRealtime();
1219 mTouchCycles++;
1220 }
1221 }
1222 }
1223
1224 /**
1225 * Prevents the screen from turning on even if it *should* turn on due
1226 * to a subsequent full wake lock being acquired.
1227 * <p>
1228 * This is a temporary hack that allows an activity to "cover up" any
1229 * display glitches that happen during the activity's startup
1230 * sequence. (Specifically, this API was added to work around a
1231 * cosmetic bug in the "incoming call" sequence, where the lock screen
1232 * would flicker briefly before the incoming call UI became visible.)
1233 * TODO: There ought to be a more elegant way of doing this,
1234 * probably by having the PowerManager and ActivityManager
1235 * work together to let apps specify that the screen on/off
1236 * state should be synchronized with the Activity lifecycle.
1237 * <p>
1238 * Note that calling preventScreenOn(true) will NOT turn the screen
1239 * off if it's currently on. (This API only affects *future*
1240 * acquisitions of full wake locks.)
1241 * But calling preventScreenOn(false) WILL turn the screen on if
1242 * it's currently off because of a prior preventScreenOn(true) call.
1243 * <p>
1244 * Any call to preventScreenOn(true) MUST be followed promptly by a call
1245 * to preventScreenOn(false). In fact, if the preventScreenOn(false)
1246 * call doesn't occur within 5 seconds, we'll turn the screen back on
1247 * ourselves (and log a warning about it); this prevents a buggy app
1248 * from disabling the screen forever.)
1249 * <p>
1250 * TODO: this feature should really be controlled by a new type of poke
1251 * lock (rather than an IPowerManager call).
1252 */
1253 public void preventScreenOn(boolean prevent) {
1254 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1255
1256 synchronized (mLocks) {
1257 if (prevent) {
1258 // First of all, grab a partial wake lock to
1259 // make sure the CPU stays on during the entire
1260 // preventScreenOn(true) -> preventScreenOn(false) sequence.
1261 mPreventScreenOnPartialLock.acquire();
1262
1263 // Post a forceReenableScreen() call (for 5 seconds in the
1264 // future) to make sure the matching preventScreenOn(false) call
1265 // has happened by then.
1266 mHandler.removeCallbacks(mForceReenableScreenTask);
1267 mHandler.postDelayed(mForceReenableScreenTask, 5000);
1268
1269 // Finally, set the flag that prevents the screen from turning on.
1270 // (Below, in setPowerState(), we'll check mPreventScreenOn and
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001271 // we *won't* call setScreenStateLocked(true) if it's set.)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001272 mPreventScreenOn = true;
1273 } else {
1274 // (Re)enable the screen.
1275 mPreventScreenOn = false;
1276
1277 // We're "undoing" a the prior preventScreenOn(true) call, so we
1278 // no longer need the 5-second safeguard.
1279 mHandler.removeCallbacks(mForceReenableScreenTask);
1280
1281 // Forcibly turn on the screen if it's supposed to be on. (This
1282 // handles the case where the screen is currently off because of
1283 // a prior preventScreenOn(true) call.)
Mike Lockwoode090281422009-11-14 21:02:56 -05001284 if (!mProximitySensorActive && (mPowerState & SCREEN_ON_BIT) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001285 if (mSpew) {
1286 Log.d(TAG,
1287 "preventScreenOn: turning on after a prior preventScreenOn(true)!");
1288 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001289 int err = setScreenStateLocked(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001290 if (err != 0) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001291 Log.w(TAG, "preventScreenOn: error from setScreenStateLocked(): " + err);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001292 }
1293 }
1294
1295 // Release the partial wake lock that we held during the
1296 // preventScreenOn(true) -> preventScreenOn(false) sequence.
1297 mPreventScreenOnPartialLock.release();
1298 }
1299 }
1300 }
1301
1302 public void setScreenBrightnessOverride(int brightness) {
1303 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1304
1305 synchronized (mLocks) {
1306 if (mScreenBrightnessOverride != brightness) {
1307 mScreenBrightnessOverride = brightness;
1308 updateLightsLocked(mPowerState, SCREEN_ON_BIT);
1309 }
1310 }
1311 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001312
1313 public void setButtonBrightnessOverride(int brightness) {
1314 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1315
1316 synchronized (mLocks) {
1317 if (mButtonBrightnessOverride != brightness) {
1318 mButtonBrightnessOverride = brightness;
1319 updateLightsLocked(mPowerState, BUTTON_BRIGHT_BIT | KEYBOARD_BRIGHT_BIT);
1320 }
1321 }
1322 }
1323
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001324 /**
1325 * Sanity-check that gets called 5 seconds after any call to
1326 * preventScreenOn(true). This ensures that the original call
1327 * is followed promptly by a call to preventScreenOn(false).
1328 */
1329 private void forceReenableScreen() {
1330 // We shouldn't get here at all if mPreventScreenOn is false, since
1331 // we should have already removed any existing
1332 // mForceReenableScreenTask messages...
1333 if (!mPreventScreenOn) {
1334 Log.w(TAG, "forceReenableScreen: mPreventScreenOn is false, nothing to do");
1335 return;
1336 }
1337
1338 // Uh oh. It's been 5 seconds since a call to
1339 // preventScreenOn(true) and we haven't re-enabled the screen yet.
1340 // This means the app that called preventScreenOn(true) is either
1341 // slow (i.e. it took more than 5 seconds to call preventScreenOn(false)),
1342 // or buggy (i.e. it forgot to call preventScreenOn(false), or
1343 // crashed before doing so.)
1344
1345 // Log a warning, and forcibly turn the screen back on.
1346 Log.w(TAG, "App called preventScreenOn(true) but didn't promptly reenable the screen! "
1347 + "Forcing the screen back on...");
1348 preventScreenOn(false);
1349 }
1350
1351 private Runnable mForceReenableScreenTask = new Runnable() {
1352 public void run() {
1353 forceReenableScreen();
1354 }
1355 };
1356
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001357 private int setScreenStateLocked(boolean on) {
1358 int err = Power.setScreenState(on);
Mike Lockwood20ee6f22009-11-07 20:33:47 -05001359 if (err == 0) {
1360 mLastScreenOnTime = (on ? SystemClock.elapsedRealtime() : 0);
1361 if (mUseSoftwareAutoBrightness) {
1362 enableLightSensor(on);
1363 if (!on) {
1364 // make sure button and key backlights are off too
Mike Lockwoodcc9a63d2009-11-10 07:50:28 -05001365 int brightnessMode = (mUseSoftwareAutoBrightness
Mike Lockwood3a322132009-11-24 00:30:52 -05001366 ? LightsService.BRIGHTNESS_MODE_SENSOR
1367 : LightsService.BRIGHTNESS_MODE_USER);
1368 mLightsService.setLightBrightness(LightsService.LIGHT_ID_BUTTONS, 0,
Mike Lockwoodcc9a63d2009-11-10 07:50:28 -05001369 brightnessMode);
Mike Lockwood3a322132009-11-24 00:30:52 -05001370 mLightsService.setLightBrightness(LightsService.LIGHT_ID_KEYBOARD, 0,
Mike Lockwoodcc9a63d2009-11-10 07:50:28 -05001371 brightnessMode);
Mike Lockwood20ee6f22009-11-07 20:33:47 -05001372 // clear current value so we will update based on the new conditions
1373 // when the sensor is reenabled.
1374 mLightSensorValue = -1;
1375 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001376 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001377 }
1378 return err;
1379 }
1380
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001381 private void setPowerState(int state)
1382 {
1383 setPowerState(state, false, false);
1384 }
1385
1386 private void setPowerState(int newState, boolean noChangeLights, boolean becauseOfUser)
1387 {
1388 synchronized (mLocks) {
1389 int err;
1390
1391 if (mSpew) {
1392 Log.d(TAG, "setPowerState: mPowerState=0x" + Integer.toHexString(mPowerState)
1393 + " newState=0x" + Integer.toHexString(newState)
1394 + " noChangeLights=" + noChangeLights);
1395 }
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;
1488 EventLog.writeEvent(LOG_POWER_SCREEN_STATE, 1, becauseOfUser ? 1 : 0,
1489 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;
1507 if (!mScreenBrightness.animating) {
Joe Onorato128e7292009-03-24 18:41:31 -07001508 err = screenOffFinishedAnimatingLocked(becauseOfUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001509 } else {
1510 mOffBecauseOfUser = becauseOfUser;
1511 err = 0;
1512 mLastTouchDown = 0;
1513 }
1514 }
1515 }
1516 }
1517 }
1518
Joe Onorato128e7292009-03-24 18:41:31 -07001519 private int screenOffFinishedAnimatingLocked(boolean becauseOfUser) {
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
1521 // Power.setScreenState and sendNotificationLocked can both handle being
1522 // called multiple times in the same state. -joeo
1523 EventLog.writeEvent(LOG_POWER_SCREEN_STATE, 0, becauseOfUser ? 1 : 0,
1524 mTotalTouchDownTime, mTouchCycles);
1525 mLastTouchDown = 0;
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001526 int err = setScreenStateLocked(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001527 if (err == 0) {
1528 int why = becauseOfUser
1529 ? WindowManagerPolicy.OFF_BECAUSE_OF_USER
1530 : WindowManagerPolicy.OFF_BECAUSE_OF_TIMEOUT;
1531 sendNotificationLocked(false, why);
1532 }
1533 return err;
1534 }
1535
1536 private boolean batteryIsLow() {
1537 return (!mIsPowered &&
1538 mBatteryService.getBatteryLevel() <= Power.LOW_BATTERY_THRESHOLD);
1539 }
1540
The Android Open Source Project10592532009-03-18 17:39:46 -07001541 private void updateLightsLocked(int newState, int forceState) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001542 final int oldState = mPowerState;
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001543 newState = applyButtonState(newState);
1544 newState = applyKeyboardState(newState);
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001545 final int realDifference = (newState ^ oldState);
1546 final int difference = realDifference | forceState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001547 if (difference == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001548 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001549 }
1550
1551 int offMask = 0;
1552 int dimMask = 0;
1553 int onMask = 0;
1554
1555 int preferredBrightness = getPreferredBrightness();
1556 boolean startAnimation = false;
1557
1558 if ((difference & KEYBOARD_BRIGHT_BIT) != 0) {
1559 if (ANIMATE_KEYBOARD_LIGHTS) {
1560 if ((newState & KEYBOARD_BRIGHT_BIT) == 0) {
1561 mKeyboardBrightness.setTargetLocked(Power.BRIGHTNESS_OFF,
Joe Onorato128e7292009-03-24 18:41:31 -07001562 ANIM_STEPS, INITIAL_KEYBOARD_BRIGHTNESS,
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001563 Power.BRIGHTNESS_ON);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001564 } else {
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001565 mKeyboardBrightness.setTargetLocked(Power.BRIGHTNESS_ON,
Joe Onorato128e7292009-03-24 18:41:31 -07001566 ANIM_STEPS, INITIAL_KEYBOARD_BRIGHTNESS,
1567 Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001568 }
1569 startAnimation = true;
1570 } else {
1571 if ((newState & KEYBOARD_BRIGHT_BIT) == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001572 offMask |= KEYBOARD_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001573 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001574 onMask |= KEYBOARD_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001575 }
1576 }
1577 }
1578
1579 if ((difference & BUTTON_BRIGHT_BIT) != 0) {
1580 if (ANIMATE_BUTTON_LIGHTS) {
1581 if ((newState & BUTTON_BRIGHT_BIT) == 0) {
1582 mButtonBrightness.setTargetLocked(Power.BRIGHTNESS_OFF,
Joe Onorato128e7292009-03-24 18:41:31 -07001583 ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001584 Power.BRIGHTNESS_ON);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001585 } else {
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001586 mButtonBrightness.setTargetLocked(Power.BRIGHTNESS_ON,
Joe Onorato128e7292009-03-24 18:41:31 -07001587 ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
1588 Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001589 }
1590 startAnimation = true;
1591 } else {
1592 if ((newState & BUTTON_BRIGHT_BIT) == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001593 offMask |= BUTTON_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001594 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001595 onMask |= BUTTON_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001596 }
1597 }
1598 }
1599
1600 if ((difference & (SCREEN_ON_BIT | SCREEN_BRIGHT_BIT)) != 0) {
1601 if (ANIMATE_SCREEN_LIGHTS) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001602 int nominalCurrentValue = -1;
1603 // If there was an actual difference in the light state, then
1604 // figure out the "ideal" current value based on the previous
1605 // state. Otherwise, this is a change due to the brightness
1606 // override, so we want to animate from whatever the current
1607 // value is.
1608 if ((realDifference & (SCREEN_ON_BIT | SCREEN_BRIGHT_BIT)) != 0) {
1609 switch (oldState & (SCREEN_BRIGHT_BIT|SCREEN_ON_BIT)) {
1610 case SCREEN_BRIGHT_BIT | SCREEN_ON_BIT:
1611 nominalCurrentValue = preferredBrightness;
1612 break;
1613 case SCREEN_ON_BIT:
1614 nominalCurrentValue = Power.BRIGHTNESS_DIM;
1615 break;
1616 case 0:
1617 nominalCurrentValue = Power.BRIGHTNESS_OFF;
1618 break;
1619 case SCREEN_BRIGHT_BIT:
1620 default:
1621 // not possible
1622 nominalCurrentValue = (int)mScreenBrightness.curValue;
1623 break;
1624 }
Joe Onorato128e7292009-03-24 18:41:31 -07001625 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001626 int brightness = preferredBrightness;
1627 int steps = ANIM_STEPS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001628 if ((newState & SCREEN_BRIGHT_BIT) == 0) {
1629 // dim or turn off backlight, depending on if the screen is on
1630 // the scale is because the brightness ramp isn't linear and this biases
1631 // it so the later parts take longer.
1632 final float scale = 1.5f;
1633 float ratio = (((float)Power.BRIGHTNESS_DIM)/preferredBrightness);
1634 if (ratio > 1.0f) ratio = 1.0f;
1635 if ((newState & SCREEN_ON_BIT) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001636 if ((oldState & SCREEN_BRIGHT_BIT) != 0) {
1637 // was bright
1638 steps = ANIM_STEPS;
1639 } else {
1640 // was dim
1641 steps = (int)(ANIM_STEPS*ratio*scale);
1642 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001643 brightness = Power.BRIGHTNESS_OFF;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001644 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001645 if ((oldState & SCREEN_ON_BIT) != 0) {
1646 // was bright
1647 steps = (int)(ANIM_STEPS*(1.0f-ratio)*scale);
1648 } else {
1649 // was dim
1650 steps = (int)(ANIM_STEPS*ratio);
1651 }
1652 if (mStayOnConditions != 0 && mBatteryService.isPowered(mStayOnConditions)) {
1653 // If the "stay on while plugged in" option is
1654 // turned on, then the screen will often not
1655 // automatically turn off while plugged in. To
1656 // still have a sense of when it is inactive, we
1657 // will then count going dim as turning off.
1658 mScreenOffTime = SystemClock.elapsedRealtime();
1659 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001660 brightness = Power.BRIGHTNESS_DIM;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001661 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001662 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001663 long identity = Binder.clearCallingIdentity();
1664 try {
1665 mBatteryStats.noteScreenBrightness(brightness);
1666 } catch (RemoteException e) {
1667 // Nothing interesting to do.
1668 } finally {
1669 Binder.restoreCallingIdentity(identity);
1670 }
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001671 if (mScreenBrightness.setTargetLocked(brightness,
1672 steps, INITIAL_SCREEN_BRIGHTNESS, nominalCurrentValue)) {
1673 startAnimation = true;
1674 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001675 } else {
1676 if ((newState & SCREEN_BRIGHT_BIT) == 0) {
1677 // dim or turn off backlight, depending on if the screen is on
1678 if ((newState & SCREEN_ON_BIT) == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001679 offMask |= SCREEN_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001680 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001681 dimMask |= SCREEN_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001682 }
1683 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001684 onMask |= SCREEN_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001685 }
1686 }
1687 }
1688
1689 if (startAnimation) {
1690 if (mSpew) {
1691 Log.i(TAG, "Scheduling light animator!");
1692 }
1693 mHandler.removeCallbacks(mLightAnimator);
1694 mHandler.post(mLightAnimator);
1695 }
1696
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001697 if (offMask != 0) {
1698 //Log.i(TAG, "Setting brightess off: " + offMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001699 setLightBrightness(offMask, Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001700 }
1701 if (dimMask != 0) {
1702 int brightness = Power.BRIGHTNESS_DIM;
1703 if ((newState & BATTERY_LOW_BIT) != 0 &&
1704 brightness > Power.BRIGHTNESS_LOW_BATTERY) {
1705 brightness = Power.BRIGHTNESS_LOW_BATTERY;
1706 }
1707 //Log.i(TAG, "Setting brightess dim " + brightness + ": " + offMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001708 setLightBrightness(dimMask, brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001709 }
1710 if (onMask != 0) {
1711 int brightness = getPreferredBrightness();
1712 if ((newState & BATTERY_LOW_BIT) != 0 &&
1713 brightness > Power.BRIGHTNESS_LOW_BATTERY) {
1714 brightness = Power.BRIGHTNESS_LOW_BATTERY;
1715 }
1716 //Log.i(TAG, "Setting brightess on " + brightness + ": " + onMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001717 setLightBrightness(onMask, brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001718 }
The Android Open Source Project10592532009-03-18 17:39:46 -07001719 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001720
The Android Open Source Project10592532009-03-18 17:39:46 -07001721 private void setLightBrightness(int mask, int value) {
Mike Lockwoodcc9a63d2009-11-10 07:50:28 -05001722 int brightnessMode = (mAutoBrightessEnabled
Mike Lockwood3a322132009-11-24 00:30:52 -05001723 ? LightsService.BRIGHTNESS_MODE_SENSOR
1724 : LightsService.BRIGHTNESS_MODE_USER);
The Android Open Source Project10592532009-03-18 17:39:46 -07001725 if ((mask & SCREEN_BRIGHT_BIT) != 0) {
Mike Lockwood3a322132009-11-24 00:30:52 -05001726 mLightsService.setLightBrightness(LightsService.LIGHT_ID_BACKLIGHT, value,
Mike Lockwoodcc9a63d2009-11-10 07:50:28 -05001727 brightnessMode);
The Android Open Source Project10592532009-03-18 17:39:46 -07001728 }
Mike Lockwoodcc9a63d2009-11-10 07:50:28 -05001729 brightnessMode = (mUseSoftwareAutoBrightness
Mike Lockwood3a322132009-11-24 00:30:52 -05001730 ? LightsService.BRIGHTNESS_MODE_SENSOR
1731 : LightsService.BRIGHTNESS_MODE_USER);
The Android Open Source Project10592532009-03-18 17:39:46 -07001732 if ((mask & BUTTON_BRIGHT_BIT) != 0) {
Mike Lockwood3a322132009-11-24 00:30:52 -05001733 mLightsService.setLightBrightness(LightsService.LIGHT_ID_BUTTONS, value,
Mike Lockwoodcc9a63d2009-11-10 07:50:28 -05001734 brightnessMode);
The Android Open Source Project10592532009-03-18 17:39:46 -07001735 }
1736 if ((mask & KEYBOARD_BRIGHT_BIT) != 0) {
Mike Lockwood3a322132009-11-24 00:30:52 -05001737 mLightsService.setLightBrightness(LightsService.LIGHT_ID_KEYBOARD, value,
Mike Lockwoodcc9a63d2009-11-10 07:50:28 -05001738 brightnessMode);
The Android Open Source Project10592532009-03-18 17:39:46 -07001739 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001740 }
1741
1742 class BrightnessState {
1743 final int mask;
1744
1745 boolean initialized;
1746 int targetValue;
1747 float curValue;
1748 float delta;
1749 boolean animating;
1750
1751 BrightnessState(int m) {
1752 mask = m;
1753 }
1754
1755 public void dump(PrintWriter pw, String prefix) {
1756 pw.println(prefix + "animating=" + animating
1757 + " targetValue=" + targetValue
1758 + " curValue=" + curValue
1759 + " delta=" + delta);
1760 }
1761
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001762 boolean setTargetLocked(int target, int stepsToTarget, int initialValue,
Joe Onorato128e7292009-03-24 18:41:31 -07001763 int nominalCurrentValue) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001764 if (!initialized) {
1765 initialized = true;
1766 curValue = (float)initialValue;
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001767 } else if (targetValue == target) {
1768 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001769 }
1770 targetValue = target;
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001771 delta = (targetValue -
1772 (nominalCurrentValue >= 0 ? nominalCurrentValue : curValue))
1773 / stepsToTarget;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001774 if (mSpew) {
Joe Onorato128e7292009-03-24 18:41:31 -07001775 String noticeMe = nominalCurrentValue == curValue ? "" : " ******************";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001776 Log.i(TAG, "Setting target " + mask + ": cur=" + curValue
Joe Onorato128e7292009-03-24 18:41:31 -07001777 + " target=" + targetValue + " delta=" + delta
1778 + " nominalCurrentValue=" + nominalCurrentValue
1779 + noticeMe);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001780 }
1781 animating = true;
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001782 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001783 }
1784
1785 boolean stepLocked() {
1786 if (!animating) return false;
1787 if (false && mSpew) {
1788 Log.i(TAG, "Step target " + mask + ": cur=" + curValue
1789 + " target=" + targetValue + " delta=" + delta);
1790 }
1791 curValue += delta;
1792 int curIntValue = (int)curValue;
1793 boolean more = true;
1794 if (delta == 0) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001795 curValue = curIntValue = targetValue;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001796 more = false;
1797 } else if (delta > 0) {
1798 if (curIntValue >= targetValue) {
1799 curValue = curIntValue = targetValue;
1800 more = false;
1801 }
1802 } else {
1803 if (curIntValue <= targetValue) {
1804 curValue = curIntValue = targetValue;
1805 more = false;
1806 }
1807 }
1808 //Log.i(TAG, "Animating brightess " + curIntValue + ": " + mask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001809 setLightBrightness(mask, curIntValue);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001810 animating = more;
1811 if (!more) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001812 if (mask == SCREEN_BRIGHT_BIT && curIntValue == Power.BRIGHTNESS_OFF) {
Joe Onorato128e7292009-03-24 18:41:31 -07001813 screenOffFinishedAnimatingLocked(mOffBecauseOfUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001814 }
1815 }
1816 return more;
1817 }
1818 }
1819
1820 private class LightAnimator implements Runnable {
1821 public void run() {
1822 synchronized (mLocks) {
1823 long now = SystemClock.uptimeMillis();
1824 boolean more = mScreenBrightness.stepLocked();
1825 if (mKeyboardBrightness.stepLocked()) {
1826 more = true;
1827 }
1828 if (mButtonBrightness.stepLocked()) {
1829 more = true;
1830 }
1831 if (more) {
1832 mHandler.postAtTime(mLightAnimator, now+(1000/60));
1833 }
1834 }
1835 }
1836 }
1837
1838 private int getPreferredBrightness() {
1839 try {
1840 if (mScreenBrightnessOverride >= 0) {
1841 return mScreenBrightnessOverride;
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001842 } else if (mLightSensorScreenBrightness >= 0 && mUseSoftwareAutoBrightness
Mike Lockwood27c6dd72009-11-04 08:57:07 -05001843 && mAutoBrightessEnabled) {
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001844 return mLightSensorScreenBrightness;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001845 }
1846 final int brightness = Settings.System.getInt(mContext.getContentResolver(),
1847 SCREEN_BRIGHTNESS);
1848 // Don't let applications turn the screen all the way off
1849 return Math.max(brightness, Power.BRIGHTNESS_DIM);
1850 } catch (SettingNotFoundException snfe) {
1851 return Power.BRIGHTNESS_ON;
1852 }
1853 }
1854
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001855 private int applyButtonState(int state) {
1856 int brightness = -1;
1857 if (mButtonBrightnessOverride >= 0) {
1858 brightness = mButtonBrightnessOverride;
1859 } else if (mLightSensorButtonBrightness >= 0 && mUseSoftwareAutoBrightness) {
1860 brightness = mLightSensorButtonBrightness;
1861 }
1862 if (brightness > 0) {
1863 return state | BUTTON_BRIGHT_BIT;
1864 } else if (brightness == 0) {
1865 return state & ~BUTTON_BRIGHT_BIT;
1866 } else {
1867 return state;
1868 }
1869 }
1870
1871 private int applyKeyboardState(int state) {
1872 int brightness = -1;
1873 if (!mKeyboardVisible) {
1874 brightness = 0;
1875 } else if (mButtonBrightnessOverride >= 0) {
1876 brightness = mButtonBrightnessOverride;
1877 } else if (mLightSensorKeyboardBrightness >= 0 && mUseSoftwareAutoBrightness) {
1878 brightness = mLightSensorKeyboardBrightness;
1879 }
1880 if (brightness > 0) {
1881 return state | KEYBOARD_BRIGHT_BIT;
1882 } else if (brightness == 0) {
1883 return state & ~KEYBOARD_BRIGHT_BIT;
1884 } else {
1885 return state;
1886 }
1887 }
1888
Charles Mendis322591c2009-10-29 11:06:59 -07001889 public boolean isScreenOn() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001890 synchronized (mLocks) {
1891 return (mPowerState & SCREEN_ON_BIT) != 0;
1892 }
1893 }
1894
Charles Mendis322591c2009-10-29 11:06:59 -07001895 boolean isScreenBright() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001896 synchronized (mLocks) {
1897 return (mPowerState & SCREEN_BRIGHT) == SCREEN_BRIGHT;
1898 }
1899 }
1900
Mike Lockwood497087e32009-11-08 18:33:03 -05001901 private boolean isScreenTurningOffLocked() {
1902 return (mScreenBrightness.animating && mScreenBrightness.targetValue == 0);
1903 }
1904
Mike Lockwood200b30b2009-09-20 00:23:59 -04001905 private void forceUserActivityLocked() {
Mike Lockwoode090281422009-11-14 21:02:56 -05001906 if (isScreenTurningOffLocked()) {
1907 // cancel animation so userActivity will succeed
1908 mScreenBrightness.animating = false;
1909 }
Mike Lockwood200b30b2009-09-20 00:23:59 -04001910 boolean savedActivityAllowed = mUserActivityAllowed;
1911 mUserActivityAllowed = true;
1912 userActivity(SystemClock.uptimeMillis(), false);
1913 mUserActivityAllowed = savedActivityAllowed;
1914 }
1915
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001916 public void userActivityWithForce(long time, boolean noChangeLights, boolean force) {
1917 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1918 userActivity(time, noChangeLights, OTHER_EVENT, force);
1919 }
1920
1921 public void userActivity(long time, boolean noChangeLights) {
1922 userActivity(time, noChangeLights, OTHER_EVENT, false);
1923 }
1924
1925 public void userActivity(long time, boolean noChangeLights, int eventType) {
1926 userActivity(time, noChangeLights, eventType, false);
1927 }
1928
1929 public void userActivity(long time, boolean noChangeLights, int eventType, boolean force) {
1930 //mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1931
1932 if (((mPokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0)
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07001933 && (eventType == CHEEK_EVENT || eventType == TOUCH_EVENT)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001934 if (false) {
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07001935 Log.d(TAG, "dropping cheek or short event mPokey=0x" + Integer.toHexString(mPokey));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001936 }
1937 return;
1938 }
1939
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07001940 if (((mPokey & POKE_LOCK_IGNORE_TOUCH_AND_CHEEK_EVENTS) != 0)
1941 && (eventType == TOUCH_EVENT || eventType == TOUCH_UP_EVENT
1942 || eventType == LONG_TOUCH_EVENT || eventType == CHEEK_EVENT)) {
1943 if (false) {
1944 Log.d(TAG, "dropping touch mPokey=0x" + Integer.toHexString(mPokey));
1945 }
1946 return;
1947 }
1948
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001949 if (false) {
1950 if (((mPokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0)) {
1951 Log.d(TAG, "userActivity !!!");//, new RuntimeException());
1952 } else {
1953 Log.d(TAG, "mPokey=0x" + Integer.toHexString(mPokey));
1954 }
1955 }
1956
1957 synchronized (mLocks) {
1958 if (mSpew) {
1959 Log.d(TAG, "userActivity mLastEventTime=" + mLastEventTime + " time=" + time
1960 + " mUserActivityAllowed=" + mUserActivityAllowed
1961 + " mUserState=0x" + Integer.toHexString(mUserState)
Mike Lockwood36fc3022009-08-25 16:49:06 -07001962 + " mWakeLockState=0x" + Integer.toHexString(mWakeLockState)
1963 + " mProximitySensorActive=" + mProximitySensorActive
1964 + " force=" + force);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001965 }
Mike Lockwood05067122009-10-27 23:07:25 -04001966 // ignore user activity if we are in the process of turning off the screen
Mike Lockwood497087e32009-11-08 18:33:03 -05001967 if (isScreenTurningOffLocked()) {
Mike Lockwood05067122009-10-27 23:07:25 -04001968 Log.d(TAG, "ignoring user activity while turning off screen");
1969 return;
1970 }
Mike Lockwood0e39ea82009-11-18 15:37:10 -05001971 // Disable proximity sensor if if user presses power key while we are in the
1972 // "waiting for proximity sensor to go negative" state.
1973 if (mProximitySensorActive && mProximityWakeLockCount == 0) {
1974 mProximitySensorActive = false;
1975 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001976 if (mLastEventTime <= time || force) {
1977 mLastEventTime = time;
Mike Lockwood36fc3022009-08-25 16:49:06 -07001978 if ((mUserActivityAllowed && !mProximitySensorActive) || force) {
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001979 // Only turn on button backlights if a button was pressed
1980 // and auto brightness is disabled
Mike Lockwood4984e732009-11-01 08:16:33 -05001981 if (eventType == BUTTON_EVENT && !mUseSoftwareAutoBrightness) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001982 mUserState = (mKeyboardVisible ? ALL_BRIGHT : SCREEN_BUTTON_BRIGHT);
1983 } else {
1984 // don't clear button/keyboard backlights when the screen is touched.
1985 mUserState |= SCREEN_BRIGHT;
1986 }
1987
Dianne Hackborn617f8772009-03-31 15:04:46 -07001988 int uid = Binder.getCallingUid();
1989 long ident = Binder.clearCallingIdentity();
1990 try {
1991 mBatteryStats.noteUserActivity(uid, eventType);
1992 } catch (RemoteException e) {
1993 // Ignore
1994 } finally {
1995 Binder.restoreCallingIdentity(ident);
1996 }
1997
Michael Chane96440f2009-05-06 10:27:36 -07001998 mWakeLockState = mLocks.reactivateScreenLocksLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001999 setPowerState(mUserState | mWakeLockState, noChangeLights, true);
2000 setTimeoutLocked(time, SCREEN_BRIGHT);
2001 }
2002 }
2003 }
2004 }
2005
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002006 private int getAutoBrightnessValue(int sensorValue, int[] values) {
2007 try {
2008 int i;
2009 for (i = 0; i < mAutoBrightnessLevels.length; i++) {
2010 if (sensorValue < mAutoBrightnessLevels[i]) {
2011 break;
2012 }
2013 }
2014 return values[i];
2015 } catch (Exception e) {
2016 // guard against null pointer or index out of bounds errors
2017 Log.e(TAG, "getAutoBrightnessValue", e);
2018 return 255;
2019 }
2020 }
2021
Mike Lockwood20f87d72009-11-05 16:08:51 -05002022 private Runnable mProximityTask = new Runnable() {
2023 public void run() {
2024 synchronized (mLocks) {
2025 if (mProximityPendingValue != -1) {
2026 proximityChangedLocked(mProximityPendingValue == 1);
2027 mProximityPendingValue = -1;
2028 }
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002029 if (mProximityPartialLock.isHeld()) {
2030 mProximityPartialLock.release();
2031 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002032 }
2033 }
2034 };
2035
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002036 private Runnable mAutoBrightnessTask = new Runnable() {
2037 public void run() {
Mike Lockwoodfa68ab42009-10-20 11:08:49 -04002038 synchronized (mLocks) {
2039 int value = (int)mLightSensorPendingValue;
2040 if (value >= 0) {
2041 mLightSensorPendingValue = -1;
2042 lightSensorChangedLocked(value);
2043 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002044 }
2045 }
2046 };
2047
2048 private void lightSensorChangedLocked(int value) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002049 if (mDebugLightSensor) {
2050 Log.d(TAG, "lightSensorChangedLocked " + value);
2051 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002052
2053 if (mLightSensorValue != value) {
2054 mLightSensorValue = value;
2055 if ((mPowerState & BATTERY_LOW_BIT) == 0) {
2056 int lcdValue = getAutoBrightnessValue(value, mLcdBacklightValues);
2057 int buttonValue = getAutoBrightnessValue(value, mButtonBacklightValues);
Mike Lockwooddf024922009-10-29 21:29:15 -04002058 int keyboardValue;
2059 if (mKeyboardVisible) {
2060 keyboardValue = getAutoBrightnessValue(value, mKeyboardBacklightValues);
2061 } else {
2062 keyboardValue = 0;
2063 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002064 mLightSensorScreenBrightness = lcdValue;
2065 mLightSensorButtonBrightness = buttonValue;
2066 mLightSensorKeyboardBrightness = keyboardValue;
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002067
2068 if (mDebugLightSensor) {
2069 Log.d(TAG, "lcdValue " + lcdValue);
2070 Log.d(TAG, "buttonValue " + buttonValue);
2071 Log.d(TAG, "keyboardValue " + keyboardValue);
2072 }
2073
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002074 boolean startAnimation = false;
Mike Lockwood4984e732009-11-01 08:16:33 -05002075 if (mAutoBrightessEnabled && mScreenBrightnessOverride < 0) {
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002076 if (ANIMATE_SCREEN_LIGHTS) {
2077 if (mScreenBrightness.setTargetLocked(lcdValue,
2078 AUTOBRIGHTNESS_ANIM_STEPS, INITIAL_SCREEN_BRIGHTNESS,
2079 (int)mScreenBrightness.curValue)) {
2080 startAnimation = true;
2081 }
2082 } else {
Mike Lockwoodcc9a63d2009-11-10 07:50:28 -05002083 int brightnessMode = (mAutoBrightessEnabled
Mike Lockwood3a322132009-11-24 00:30:52 -05002084 ? LightsService.BRIGHTNESS_MODE_SENSOR
2085 : LightsService.BRIGHTNESS_MODE_USER);
2086 mLightsService.setLightBrightness(LightsService.LIGHT_ID_BACKLIGHT,
Mike Lockwoodcc9a63d2009-11-10 07:50:28 -05002087 lcdValue, brightnessMode);
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002088 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002089 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002090 if (mButtonBrightnessOverride < 0) {
2091 if (ANIMATE_BUTTON_LIGHTS) {
2092 if (mButtonBrightness.setTargetLocked(buttonValue,
2093 AUTOBRIGHTNESS_ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
2094 (int)mButtonBrightness.curValue)) {
2095 startAnimation = true;
2096 }
2097 } else {
2098 int brightnessMode = (mUseSoftwareAutoBrightness
Mike Lockwood3a322132009-11-24 00:30:52 -05002099 ? LightsService.BRIGHTNESS_MODE_SENSOR
2100 : LightsService.BRIGHTNESS_MODE_USER);
2101 mLightsService.setLightBrightness(LightsService.LIGHT_ID_BUTTONS,
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002102 buttonValue, brightnessMode);
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002103 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002104 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002105 if (mButtonBrightnessOverride < 0 || !mKeyboardVisible) {
2106 if (ANIMATE_KEYBOARD_LIGHTS) {
2107 if (mKeyboardBrightness.setTargetLocked(keyboardValue,
2108 AUTOBRIGHTNESS_ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
2109 (int)mKeyboardBrightness.curValue)) {
2110 startAnimation = true;
2111 }
2112 } else {
2113 int brightnessMode = (mUseSoftwareAutoBrightness
Mike Lockwood3a322132009-11-24 00:30:52 -05002114 ? LightsService.BRIGHTNESS_MODE_SENSOR
2115 : LightsService.BRIGHTNESS_MODE_USER);
2116 mLightsService.setLightBrightness(LightsService.LIGHT_ID_KEYBOARD,
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002117 keyboardValue, brightnessMode);
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002118 }
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002119 }
2120 if (startAnimation) {
2121 if (mDebugLightSensor) {
2122 Log.i(TAG, "lightSensorChangedLocked scheduling light animator");
2123 }
2124 mHandler.removeCallbacks(mLightAnimator);
2125 mHandler.post(mLightAnimator);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002126 }
2127 }
2128 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002129 }
2130
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002131 /**
2132 * The user requested that we go to sleep (probably with the power button).
2133 * This overrides all wake locks that are held.
2134 */
2135 public void goToSleep(long time)
2136 {
2137 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
2138 synchronized (mLocks) {
2139 goToSleepLocked(time);
2140 }
2141 }
2142
2143 /**
Doug Zongker50a21f42009-11-19 12:49:53 -08002144 * Reboot the device immediately, passing 'reason' (may be null)
2145 * to the underlying __reboot system call. Should not return.
2146 */
2147 public void reboot(String reason)
2148 {
2149 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
2150 try {
2151 Power.reboot(reason);
2152 } catch (IOException e) {
2153 Log.e(TAG, "reboot failed", e);
2154 }
2155 }
2156
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002157 private void goToSleepLocked(long time) {
2158
2159 if (mLastEventTime <= time) {
2160 mLastEventTime = time;
2161 // cancel all of the wake locks
2162 mWakeLockState = SCREEN_OFF;
2163 int N = mLocks.size();
2164 int numCleared = 0;
2165 for (int i=0; i<N; i++) {
2166 WakeLock wl = mLocks.get(i);
2167 if (isScreenLock(wl.flags)) {
2168 mLocks.get(i).activated = false;
2169 numCleared++;
2170 }
2171 }
2172 EventLog.writeEvent(LOG_POWER_SLEEP_REQUESTED, numCleared);
Joe Onorato128e7292009-03-24 18:41:31 -07002173 mStillNeedSleepNotification = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002174 mUserState = SCREEN_OFF;
2175 setPowerState(SCREEN_OFF, false, true);
2176 cancelTimerLocked();
2177 }
2178 }
2179
2180 public long timeSinceScreenOn() {
2181 synchronized (mLocks) {
2182 if ((mPowerState & SCREEN_ON_BIT) != 0) {
2183 return 0;
2184 }
2185 return SystemClock.elapsedRealtime() - mScreenOffTime;
2186 }
2187 }
2188
2189 public void setKeyboardVisibility(boolean visible) {
Mike Lockwooda625b382009-09-12 17:36:03 -07002190 synchronized (mLocks) {
2191 if (mSpew) {
2192 Log.d(TAG, "setKeyboardVisibility: " + visible);
2193 }
Mike Lockwood3c9435a2009-10-22 15:45:37 -04002194 if (mKeyboardVisible != visible) {
2195 mKeyboardVisible = visible;
2196 // don't signal user activity if the screen is off; other code
2197 // will take care of turning on due to a true change to the lid
2198 // switch and synchronized with the lock screen.
2199 if ((mPowerState & SCREEN_ON_BIT) != 0) {
Mike Lockwood4984e732009-11-01 08:16:33 -05002200 if (mUseSoftwareAutoBrightness) {
Mike Lockwooddf024922009-10-29 21:29:15 -04002201 // force recompute of backlight values
2202 if (mLightSensorValue >= 0) {
2203 int value = (int)mLightSensorValue;
2204 mLightSensorValue = -1;
2205 lightSensorChangedLocked(value);
2206 }
2207 }
Mike Lockwood3c9435a2009-10-22 15:45:37 -04002208 userActivity(SystemClock.uptimeMillis(), false, BUTTON_EVENT, true);
2209 }
Mike Lockwooda625b382009-09-12 17:36:03 -07002210 }
2211 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002212 }
2213
2214 /**
2215 * When the keyguard is up, it manages the power state, and userActivity doesn't do anything.
Mike Lockwood50c548d2009-11-09 16:02:06 -05002216 * When disabling user activity we also reset user power state so the keyguard can reset its
2217 * short screen timeout when keyguard is unhidden.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002218 */
2219 public void enableUserActivity(boolean enabled) {
Mike Lockwood50c548d2009-11-09 16:02:06 -05002220 if (mSpew) {
2221 Log.d(TAG, "enableUserActivity " + enabled);
2222 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002223 synchronized (mLocks) {
2224 mUserActivityAllowed = enabled;
Mike Lockwood50c548d2009-11-09 16:02:06 -05002225 if (!enabled) {
2226 // cancel timeout and clear mUserState so the keyguard can set a short timeout
2227 setTimeoutLocked(SystemClock.uptimeMillis(), 0);
2228 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002229 }
2230 }
2231
Mike Lockwooddc3494e2009-10-14 21:17:09 -07002232 private void setScreenBrightnessMode(int mode) {
Mike Lockwood2d155d22009-10-27 09:32:30 -04002233 boolean enabled = (mode == SCREEN_BRIGHTNESS_MODE_AUTOMATIC);
Mike Lockwoodf90ffcc2009-11-03 11:41:27 -05002234 if (mUseSoftwareAutoBrightness && mAutoBrightessEnabled != enabled) {
Mike Lockwood2d155d22009-10-27 09:32:30 -04002235 mAutoBrightessEnabled = enabled;
Charles Mendis322591c2009-10-29 11:06:59 -07002236 if (isScreenOn()) {
Mike Lockwood4984e732009-11-01 08:16:33 -05002237 // force recompute of backlight values
2238 if (mLightSensorValue >= 0) {
2239 int value = (int)mLightSensorValue;
2240 mLightSensorValue = -1;
2241 lightSensorChangedLocked(value);
2242 }
Mike Lockwood2d155d22009-10-27 09:32:30 -04002243 }
Mike Lockwooddc3494e2009-10-14 21:17:09 -07002244 }
2245 }
2246
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002247 /** Sets the screen off timeouts:
2248 * mKeylightDelay
2249 * mDimDelay
2250 * mScreenOffDelay
2251 * */
2252 private void setScreenOffTimeoutsLocked() {
2253 if ((mPokey & POKE_LOCK_SHORT_TIMEOUT) != 0) {
2254 mKeylightDelay = mShortKeylightDelay; // Configurable via Gservices
2255 mDimDelay = -1;
2256 mScreenOffDelay = 0;
2257 } else if ((mPokey & POKE_LOCK_MEDIUM_TIMEOUT) != 0) {
2258 mKeylightDelay = MEDIUM_KEYLIGHT_DELAY;
2259 mDimDelay = -1;
2260 mScreenOffDelay = 0;
2261 } else {
2262 int totalDelay = mTotalDelaySetting;
2263 mKeylightDelay = LONG_KEYLIGHT_DELAY;
2264 if (totalDelay < 0) {
2265 mScreenOffDelay = Integer.MAX_VALUE;
2266 } else if (mKeylightDelay < totalDelay) {
2267 // subtract the time that the keylight delay. This will give us the
2268 // remainder of the time that we need to sleep to get the accurate
2269 // screen off timeout.
2270 mScreenOffDelay = totalDelay - mKeylightDelay;
2271 } else {
2272 mScreenOffDelay = 0;
2273 }
2274 if (mDimScreen && totalDelay >= (LONG_KEYLIGHT_DELAY + LONG_DIM_TIME)) {
2275 mDimDelay = mScreenOffDelay - LONG_DIM_TIME;
2276 mScreenOffDelay = LONG_DIM_TIME;
2277 } else {
2278 mDimDelay = -1;
2279 }
2280 }
2281 if (mSpew) {
2282 Log.d(TAG, "setScreenOffTimeouts mKeylightDelay=" + mKeylightDelay
2283 + " mDimDelay=" + mDimDelay + " mScreenOffDelay=" + mScreenOffDelay
2284 + " mDimScreen=" + mDimScreen);
2285 }
2286 }
2287
2288 /**
2289 * Refreshes cached Gservices settings. Called once on startup, and
2290 * on subsequent Settings.Gservices.CHANGED_ACTION broadcasts (see
2291 * GservicesChangedReceiver).
2292 */
2293 private void updateGservicesValues() {
2294 mShortKeylightDelay = Settings.Gservices.getInt(
2295 mContext.getContentResolver(),
2296 Settings.Gservices.SHORT_KEYLIGHT_DELAY_MS,
2297 SHORT_KEYLIGHT_DELAY_DEFAULT);
2298 // Log.i(TAG, "updateGservicesValues(): mShortKeylightDelay now " + mShortKeylightDelay);
2299 }
2300
2301 /**
2302 * Receiver for the Gservices.CHANGED_ACTION broadcast intent,
2303 * which tells us we need to refresh our cached Gservices settings.
2304 */
2305 private class GservicesChangedReceiver extends BroadcastReceiver {
2306 @Override
2307 public void onReceive(Context context, Intent intent) {
2308 // Log.i(TAG, "GservicesChangedReceiver.onReceive(): " + intent);
2309 updateGservicesValues();
2310 }
2311 }
2312
2313 private class LockList extends ArrayList<WakeLock>
2314 {
2315 void addLock(WakeLock wl)
2316 {
2317 int index = getIndex(wl.binder);
2318 if (index < 0) {
2319 this.add(wl);
2320 }
2321 }
2322
2323 WakeLock removeLock(IBinder binder)
2324 {
2325 int index = getIndex(binder);
2326 if (index >= 0) {
2327 return this.remove(index);
2328 } else {
2329 return null;
2330 }
2331 }
2332
2333 int getIndex(IBinder binder)
2334 {
2335 int N = this.size();
2336 for (int i=0; i<N; i++) {
2337 if (this.get(i).binder == binder) {
2338 return i;
2339 }
2340 }
2341 return -1;
2342 }
2343
2344 int gatherState()
2345 {
2346 int result = 0;
2347 int N = this.size();
2348 for (int i=0; i<N; i++) {
2349 WakeLock wl = this.get(i);
2350 if (wl.activated) {
2351 if (isScreenLock(wl.flags)) {
2352 result |= wl.minState;
2353 }
2354 }
2355 }
2356 return result;
2357 }
Michael Chane96440f2009-05-06 10:27:36 -07002358
2359 int reactivateScreenLocksLocked()
2360 {
2361 int result = 0;
2362 int N = this.size();
2363 for (int i=0; i<N; i++) {
2364 WakeLock wl = this.get(i);
2365 if (isScreenLock(wl.flags)) {
2366 wl.activated = true;
2367 result |= wl.minState;
2368 }
2369 }
2370 return result;
2371 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002372 }
2373
2374 void setPolicy(WindowManagerPolicy p) {
2375 synchronized (mLocks) {
2376 mPolicy = p;
2377 mLocks.notifyAll();
2378 }
2379 }
2380
2381 WindowManagerPolicy getPolicyLocked() {
2382 while (mPolicy == null || !mDoneBooting) {
2383 try {
2384 mLocks.wait();
2385 } catch (InterruptedException e) {
2386 // Ignore
2387 }
2388 }
2389 return mPolicy;
2390 }
2391
2392 void systemReady() {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002393 mSensorManager = new SensorManager(mHandlerThread.getLooper());
2394 mProximitySensor = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
2395 // don't bother with the light sensor if auto brightness is handled in hardware
Mike Lockwoodaa66ea82009-10-31 16:31:27 -04002396 if (mUseSoftwareAutoBrightness) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002397 mLightSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
Mike Lockwood4984e732009-11-01 08:16:33 -05002398 enableLightSensor(true);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002399 }
2400
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002401 synchronized (mLocks) {
2402 Log.d(TAG, "system ready!");
2403 mDoneBooting = true;
Dianne Hackborn617f8772009-03-31 15:04:46 -07002404 long identity = Binder.clearCallingIdentity();
2405 try {
2406 mBatteryStats.noteScreenBrightness(getPreferredBrightness());
2407 mBatteryStats.noteScreenOn();
2408 } catch (RemoteException e) {
2409 // Nothing interesting to do.
2410 } finally {
2411 Binder.restoreCallingIdentity(identity);
2412 }
Mike Lockwood2d7bb812009-11-15 18:12:22 -05002413 }
2414 }
2415
2416 void bootCompleted() {
2417 Log.d(TAG, "bootCompleted");
2418 synchronized (mLocks) {
2419 mBootCompleted = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002420 userActivity(SystemClock.uptimeMillis(), false, BUTTON_EVENT, true);
2421 updateWakeLockLocked();
2422 mLocks.notifyAll();
2423 }
2424 }
2425
2426 public void monitor() {
2427 synchronized (mLocks) { }
2428 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002429
2430 public int getSupportedWakeLockFlags() {
2431 int result = PowerManager.PARTIAL_WAKE_LOCK
2432 | PowerManager.FULL_WAKE_LOCK
2433 | PowerManager.SCREEN_DIM_WAKE_LOCK;
2434
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002435 if (mProximitySensor != null) {
2436 result |= PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK;
2437 }
2438
2439 return result;
2440 }
2441
Mike Lockwood237a2992009-09-15 14:42:16 -04002442 public void setBacklightBrightness(int brightness) {
2443 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
2444 // Don't let applications turn the screen all the way off
2445 brightness = Math.max(brightness, Power.BRIGHTNESS_DIM);
Mike Lockwood3a322132009-11-24 00:30:52 -05002446 mLightsService.setLightBrightness(LightsService.LIGHT_ID_BACKLIGHT, brightness,
2447 LightsService.BRIGHTNESS_MODE_USER);
2448 mLightsService.setLightBrightness(LightsService.LIGHT_ID_KEYBOARD,
2449 (mKeyboardVisible ? brightness : 0), LightsService.BRIGHTNESS_MODE_USER);
2450 mLightsService.setLightBrightness(LightsService.LIGHT_ID_BUTTONS, brightness,
2451 LightsService.BRIGHTNESS_MODE_USER);
Mike Lockwood237a2992009-09-15 14:42:16 -04002452 long identity = Binder.clearCallingIdentity();
2453 try {
2454 mBatteryStats.noteScreenBrightness(brightness);
2455 } catch (RemoteException e) {
2456 Log.w(TAG, "RemoteException calling noteScreenBrightness on BatteryStatsService", e);
2457 } finally {
2458 Binder.restoreCallingIdentity(identity);
2459 }
2460
2461 // update our animation state
2462 if (ANIMATE_SCREEN_LIGHTS) {
2463 mScreenBrightness.curValue = brightness;
2464 mScreenBrightness.animating = false;
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002465 mScreenBrightness.targetValue = -1;
Mike Lockwood237a2992009-09-15 14:42:16 -04002466 }
2467 if (ANIMATE_KEYBOARD_LIGHTS) {
2468 mKeyboardBrightness.curValue = brightness;
2469 mKeyboardBrightness.animating = false;
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002470 mKeyboardBrightness.targetValue = -1;
Mike Lockwood237a2992009-09-15 14:42:16 -04002471 }
2472 if (ANIMATE_BUTTON_LIGHTS) {
2473 mButtonBrightness.curValue = brightness;
2474 mButtonBrightness.animating = false;
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002475 mButtonBrightness.targetValue = -1;
Mike Lockwood237a2992009-09-15 14:42:16 -04002476 }
2477 }
2478
Mike Lockwoodb11832d2009-11-25 15:25:55 -05002479 public void setAttentionLight(boolean on, int color) {
2480 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
2481 mLightsService.setAttentionLight(on, color);
2482 }
2483
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002484 private void enableProximityLockLocked() {
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002485 if (mDebugProximitySensor) {
Mike Lockwood36fc3022009-08-25 16:49:06 -07002486 Log.d(TAG, "enableProximityLockLocked");
2487 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002488 if (!mProximitySensorEnabled) {
2489 // clear calling identity so sensor manager battery stats are accurate
2490 long identity = Binder.clearCallingIdentity();
2491 try {
2492 mSensorManager.registerListener(mProximityListener, mProximitySensor,
2493 SensorManager.SENSOR_DELAY_NORMAL);
2494 mProximitySensorEnabled = true;
2495 } finally {
2496 Binder.restoreCallingIdentity(identity);
2497 }
Mike Lockwood809ad0f2009-10-26 22:10:33 -04002498 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002499 }
2500
2501 private void disableProximityLockLocked() {
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002502 if (mDebugProximitySensor) {
Mike Lockwood36fc3022009-08-25 16:49:06 -07002503 Log.d(TAG, "disableProximityLockLocked");
2504 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002505 if (mProximitySensorEnabled) {
2506 // clear calling identity so sensor manager battery stats are accurate
2507 long identity = Binder.clearCallingIdentity();
2508 try {
2509 mSensorManager.unregisterListener(mProximityListener);
2510 mHandler.removeCallbacks(mProximityTask);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002511 if (mProximityPartialLock.isHeld()) {
2512 mProximityPartialLock.release();
2513 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002514 mProximitySensorEnabled = false;
2515 } finally {
2516 Binder.restoreCallingIdentity(identity);
2517 }
2518 if (mProximitySensorActive) {
2519 mProximitySensorActive = false;
2520 forceUserActivityLocked();
2521 }
Mike Lockwood200b30b2009-09-20 00:23:59 -04002522 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002523 }
2524
Mike Lockwood20f87d72009-11-05 16:08:51 -05002525 private void proximityChangedLocked(boolean active) {
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002526 if (mDebugProximitySensor) {
Mike Lockwood20f87d72009-11-05 16:08:51 -05002527 Log.d(TAG, "proximityChangedLocked, active: " + active);
2528 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002529 if (!mProximitySensorEnabled) {
2530 Log.d(TAG, "Ignoring proximity change after sensor is disabled");
Mike Lockwood0d72f7e2009-11-05 20:53:00 -05002531 return;
2532 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002533 if (active) {
2534 goToSleepLocked(SystemClock.uptimeMillis());
2535 mProximitySensorActive = true;
2536 } else {
2537 // proximity sensor negative events trigger as user activity.
2538 // temporarily set mUserActivityAllowed to true so this will work
2539 // even when the keyguard is on.
2540 mProximitySensorActive = false;
2541 forceUserActivityLocked();
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002542
2543 if (mProximityWakeLockCount == 0) {
2544 // disable sensor if we have no listeners left after proximity negative
2545 disableProximityLockLocked();
2546 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002547 }
2548 }
2549
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002550 private void enableLightSensor(boolean enable) {
2551 if (mDebugLightSensor) {
2552 Log.d(TAG, "enableLightSensor " + enable);
2553 }
2554 if (mSensorManager != null && mLightSensorEnabled != enable) {
2555 mLightSensorEnabled = enable;
Mike Lockwood809ad0f2009-10-26 22:10:33 -04002556 // clear calling identity so sensor manager battery stats are accurate
2557 long identity = Binder.clearCallingIdentity();
2558 try {
2559 if (enable) {
2560 mSensorManager.registerListener(mLightListener, mLightSensor,
2561 SensorManager.SENSOR_DELAY_NORMAL);
2562 } else {
2563 mSensorManager.unregisterListener(mLightListener);
2564 mHandler.removeCallbacks(mAutoBrightnessTask);
2565 }
2566 } finally {
2567 Binder.restoreCallingIdentity(identity);
Mike Lockwood06952d92009-08-13 16:05:38 -04002568 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002569 }
2570 }
2571
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002572 SensorEventListener mProximityListener = new SensorEventListener() {
2573 public void onSensorChanged(SensorEvent event) {
Mike Lockwoodba8eb1e2009-11-08 19:31:18 -05002574 long milliseconds = SystemClock.elapsedRealtime();
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002575 synchronized (mLocks) {
2576 float distance = event.values[0];
Mike Lockwood20f87d72009-11-05 16:08:51 -05002577 long timeSinceLastEvent = milliseconds - mLastProximityEventTime;
2578 mLastProximityEventTime = milliseconds;
2579 mHandler.removeCallbacks(mProximityTask);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002580 boolean proximityTaskQueued = false;
Mike Lockwood20f87d72009-11-05 16:08:51 -05002581
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002582 // compare against getMaximumRange to support sensors that only return 0 or 1
Mike Lockwood20f87d72009-11-05 16:08:51 -05002583 boolean active = (distance >= 0.0 && distance < PROXIMITY_THRESHOLD &&
2584 distance < mProximitySensor.getMaximumRange());
2585
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002586 if (mDebugProximitySensor) {
2587 Log.d(TAG, "mProximityListener.onSensorChanged active: " + active);
2588 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002589 if (timeSinceLastEvent < PROXIMITY_SENSOR_DELAY) {
2590 // enforce delaying atleast PROXIMITY_SENSOR_DELAY before processing
2591 mProximityPendingValue = (active ? 1 : 0);
2592 mHandler.postDelayed(mProximityTask, PROXIMITY_SENSOR_DELAY - timeSinceLastEvent);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002593 proximityTaskQueued = true;
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002594 } else {
Mike Lockwood20f87d72009-11-05 16:08:51 -05002595 // process the value immediately
2596 mProximityPendingValue = -1;
2597 proximityChangedLocked(active);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002598 }
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002599
2600 // update mProximityPartialLock state
2601 boolean held = mProximityPartialLock.isHeld();
2602 if (!held && proximityTaskQueued) {
2603 // hold wakelock until mProximityTask runs
2604 mProximityPartialLock.acquire();
2605 } else if (held && !proximityTaskQueued) {
2606 mProximityPartialLock.release();
2607 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002608 }
2609 }
2610
2611 public void onAccuracyChanged(Sensor sensor, int accuracy) {
2612 // ignore
2613 }
2614 };
2615
2616 SensorEventListener mLightListener = new SensorEventListener() {
2617 public void onSensorChanged(SensorEvent event) {
2618 synchronized (mLocks) {
Mike Lockwood497087e32009-11-08 18:33:03 -05002619 // ignore light sensor while screen is turning off
2620 if (isScreenTurningOffLocked()) {
2621 return;
2622 }
2623
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002624 int value = (int)event.values[0];
Mike Lockwoodba8eb1e2009-11-08 19:31:18 -05002625 long milliseconds = SystemClock.elapsedRealtime();
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002626 if (mDebugLightSensor) {
2627 Log.d(TAG, "onSensorChanged: light value: " + value);
2628 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002629 mHandler.removeCallbacks(mAutoBrightnessTask);
2630 if (mLightSensorValue != value) {
Mike Lockwood20ee6f22009-11-07 20:33:47 -05002631 if (mLightSensorValue == -1 ||
2632 milliseconds < mLastScreenOnTime + mLightSensorWarmupTime) {
2633 // process the value immediately if screen has just turned on
Mike Lockwood6c97fca2009-10-20 08:10:00 -04002634 lightSensorChangedLocked(value);
2635 } else {
2636 // delay processing to debounce the sensor
2637 mLightSensorPendingValue = value;
2638 mHandler.postDelayed(mAutoBrightnessTask, LIGHT_SENSOR_DELAY);
2639 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002640 } else {
2641 mLightSensorPendingValue = -1;
2642 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002643 }
2644 }
2645
2646 public void onAccuracyChanged(Sensor sensor, int accuracy) {
2647 // ignore
2648 }
2649 };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002650}