blob: 927c1b38d26b8e3f39d4129b8c7e716e709de265 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
19import com.android.internal.app.IBatteryStats;
20import com.android.server.am.BatteryStatsService;
21
22import android.app.ActivityManagerNative;
23import android.app.IActivityManager;
24import android.content.BroadcastReceiver;
25import android.content.ContentQueryMap;
26import android.content.ContentResolver;
27import android.content.Context;
28import android.content.Intent;
29import android.content.IntentFilter;
30import android.content.pm.PackageManager;
Mike Lockwoodd7786b42009-10-15 17:09:16 -070031import android.content.res.Resources;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080032import android.database.Cursor;
Mike Lockwoodbc706a02009-07-27 13:50:57 -070033import android.hardware.Sensor;
34import android.hardware.SensorEvent;
35import android.hardware.SensorEventListener;
36import android.hardware.SensorManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080037import android.os.BatteryStats;
38import android.os.Binder;
39import android.os.Handler;
40import android.os.HandlerThread;
41import android.os.IBinder;
42import android.os.IPowerManager;
43import android.os.LocalPowerManager;
44import android.os.Power;
45import android.os.PowerManager;
46import android.os.Process;
47import android.os.RemoteException;
48import android.os.SystemClock;
49import android.provider.Settings.SettingNotFoundException;
50import android.provider.Settings;
51import android.util.EventLog;
52import android.util.Log;
53import android.view.WindowManagerPolicy;
54import static android.provider.Settings.System.DIM_SCREEN;
55import static android.provider.Settings.System.SCREEN_BRIGHTNESS;
Dan Murphy951764b2009-08-27 14:59:03 -050056import static android.provider.Settings.System.SCREEN_BRIGHTNESS_MODE;
Mike Lockwooddc3494e2009-10-14 21:17:09 -070057import static android.provider.Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080058import static android.provider.Settings.System.SCREEN_OFF_TIMEOUT;
59import static android.provider.Settings.System.STAY_ON_WHILE_PLUGGED_IN;
60
61import java.io.FileDescriptor;
62import java.io.PrintWriter;
63import java.util.ArrayList;
64import java.util.HashMap;
65import java.util.Observable;
66import java.util.Observer;
67
Mike Lockwoodbc706a02009-07-27 13:50:57 -070068class PowerManagerService extends IPowerManager.Stub
Mike Lockwood8738e0c2009-10-04 08:44:47 -040069 implements LocalPowerManager, Watchdog.Monitor {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080070
71 private static final String TAG = "PowerManagerService";
72 static final String PARTIAL_NAME = "PowerManagerService";
73
74 private static final boolean LOG_PARTIAL_WL = false;
75
76 // Indicates whether touch-down cycles should be logged as part of the
77 // LOG_POWER_SCREEN_STATE log events
78 private static final boolean LOG_TOUCH_DOWNS = true;
79
80 private static final int LOCK_MASK = PowerManager.PARTIAL_WAKE_LOCK
81 | PowerManager.SCREEN_DIM_WAKE_LOCK
82 | PowerManager.SCREEN_BRIGHT_WAKE_LOCK
Mike Lockwoodbc706a02009-07-27 13:50:57 -070083 | PowerManager.FULL_WAKE_LOCK
84 | PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080085
86 // time since last state: time since last event:
87 // The short keylight delay comes from Gservices; this is the default.
88 private static final int SHORT_KEYLIGHT_DELAY_DEFAULT = 6000; // t+6 sec
89 private static final int MEDIUM_KEYLIGHT_DELAY = 15000; // t+15 sec
90 private static final int LONG_KEYLIGHT_DELAY = 6000; // t+6 sec
91 private static final int LONG_DIM_TIME = 7000; // t+N-5 sec
92
Mike Lockwoodd7786b42009-10-15 17:09:16 -070093 // How long to wait to debounce light sensor changes.
94 private static final int LIGHT_SENSOR_DELAY = 1000;
95
Mike Lockwoodd20ea362009-09-15 00:13:38 -040096 // trigger proximity if distance is less than 5 cm
97 private static final float PROXIMITY_THRESHOLD = 5.0f;
98
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080099 // Cached Gservices settings; see updateGservicesValues()
100 private int mShortKeylightDelay = SHORT_KEYLIGHT_DELAY_DEFAULT;
101
102 // flags for setPowerState
103 private static final int SCREEN_ON_BIT = 0x00000001;
104 private static final int SCREEN_BRIGHT_BIT = 0x00000002;
105 private static final int BUTTON_BRIGHT_BIT = 0x00000004;
106 private static final int KEYBOARD_BRIGHT_BIT = 0x00000008;
107 private static final int BATTERY_LOW_BIT = 0x00000010;
108
109 // values for setPowerState
110
111 // SCREEN_OFF == everything off
112 private static final int SCREEN_OFF = 0x00000000;
113
114 // SCREEN_DIM == screen on, screen backlight dim
115 private static final int SCREEN_DIM = SCREEN_ON_BIT;
116
117 // SCREEN_BRIGHT == screen on, screen backlight bright
118 private static final int SCREEN_BRIGHT = SCREEN_ON_BIT | SCREEN_BRIGHT_BIT;
119
120 // SCREEN_BUTTON_BRIGHT == screen on, screen and button backlights bright
121 private static final int SCREEN_BUTTON_BRIGHT = SCREEN_BRIGHT | BUTTON_BRIGHT_BIT;
122
123 // SCREEN_BUTTON_BRIGHT == screen on, screen, button and keyboard backlights bright
124 private static final int ALL_BRIGHT = SCREEN_BUTTON_BRIGHT | KEYBOARD_BRIGHT_BIT;
125
126 // used for noChangeLights in setPowerState()
127 private static final int LIGHTS_MASK = SCREEN_BRIGHT_BIT | BUTTON_BRIGHT_BIT | KEYBOARD_BRIGHT_BIT;
128
129 static final boolean ANIMATE_SCREEN_LIGHTS = true;
130 static final boolean ANIMATE_BUTTON_LIGHTS = false;
131 static final boolean ANIMATE_KEYBOARD_LIGHTS = false;
132
133 static final int ANIM_STEPS = 60/4;
Mike Lockwooddd9668e2009-10-27 15:47:02 -0400134 // Slower animation for autobrightness changes
135 static final int AUTOBRIGHTNESS_ANIM_STEPS = 60;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800136
137 // These magic numbers are the initial state of the LEDs at boot. Ideally
138 // we should read them from the driver, but our current hardware returns 0
139 // for the initial value. Oops!
140 static final int INITIAL_SCREEN_BRIGHTNESS = 255;
141 static final int INITIAL_BUTTON_BRIGHTNESS = Power.BRIGHTNESS_OFF;
142 static final int INITIAL_KEYBOARD_BRIGHTNESS = Power.BRIGHTNESS_OFF;
143
144 static final int LOG_POWER_SLEEP_REQUESTED = 2724;
145 static final int LOG_POWER_SCREEN_BROADCAST_SEND = 2725;
146 static final int LOG_POWER_SCREEN_BROADCAST_DONE = 2726;
147 static final int LOG_POWER_SCREEN_BROADCAST_STOP = 2727;
148 static final int LOG_POWER_SCREEN_STATE = 2728;
149 static final int LOG_POWER_PARTIAL_WAKE_STATE = 2729;
150
151 private final int MY_UID;
152
153 private boolean mDoneBooting = false;
154 private int mStayOnConditions = 0;
Joe Onorato128e7292009-03-24 18:41:31 -0700155 private int[] mBroadcastQueue = new int[] { -1, -1, -1 };
156 private int[] mBroadcastWhy = new int[3];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800157 private int mPartialCount = 0;
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700158 private int mProximityCount = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800159 private int mPowerState;
160 private boolean mOffBecauseOfUser;
Mike Lockwoodf003c0c2009-10-21 16:03:18 -0400161 private boolean mAnimatingScreenOff;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800162 private int mUserState;
163 private boolean mKeyboardVisible = false;
164 private boolean mUserActivityAllowed = true;
Mike Lockwood36fc3022009-08-25 16:49:06 -0700165 private boolean mProximitySensorActive = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800166 private int mTotalDelaySetting;
167 private int mKeylightDelay;
168 private int mDimDelay;
169 private int mScreenOffDelay;
170 private int mWakeLockState;
171 private long mLastEventTime = 0;
172 private long mScreenOffTime;
173 private volatile WindowManagerPolicy mPolicy;
174 private final LockList mLocks = new LockList();
175 private Intent mScreenOffIntent;
176 private Intent mScreenOnIntent;
The Android Open Source Project10592532009-03-18 17:39:46 -0700177 private HardwareService mHardware;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800178 private Context mContext;
179 private UnsynchronizedWakeLock mBroadcastWakeLock;
180 private UnsynchronizedWakeLock mStayOnWhilePluggedInScreenDimLock;
181 private UnsynchronizedWakeLock mStayOnWhilePluggedInPartialLock;
182 private UnsynchronizedWakeLock mPreventScreenOnPartialLock;
183 private HandlerThread mHandlerThread;
184 private Handler mHandler;
185 private TimeoutTask mTimeoutTask = new TimeoutTask();
186 private LightAnimator mLightAnimator = new LightAnimator();
187 private final BrightnessState mScreenBrightness
The Android Open Source Project10592532009-03-18 17:39:46 -0700188 = new BrightnessState(SCREEN_BRIGHT_BIT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800189 private final BrightnessState mKeyboardBrightness
The Android Open Source Project10592532009-03-18 17:39:46 -0700190 = new BrightnessState(KEYBOARD_BRIGHT_BIT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800191 private final BrightnessState mButtonBrightness
The Android Open Source Project10592532009-03-18 17:39:46 -0700192 = new BrightnessState(BUTTON_BRIGHT_BIT);
Joe Onorato128e7292009-03-24 18:41:31 -0700193 private boolean mStillNeedSleepNotification;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800194 private boolean mIsPowered = false;
195 private IActivityManager mActivityService;
196 private IBatteryStats mBatteryStats;
197 private BatteryService mBatteryService;
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700198 private SensorManager mSensorManager;
199 private Sensor mProximitySensor;
Mike Lockwood8738e0c2009-10-04 08:44:47 -0400200 private Sensor mLightSensor;
201 private boolean mLightSensorEnabled;
202 private float mLightSensorValue = -1;
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700203 private float mLightSensorPendingValue = -1;
204 private int mLightSensorBrightness = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800205 private boolean mDimScreen = true;
206 private long mNextTimeout;
207 private volatile int mPokey = 0;
208 private volatile boolean mPokeAwakeOnSet = false;
209 private volatile boolean mInitComplete = false;
210 private HashMap<IBinder,PokeLock> mPokeLocks = new HashMap<IBinder,PokeLock>();
211 private long mScreenOnTime;
212 private long mScreenOnStartTime;
213 private boolean mPreventScreenOn;
214 private int mScreenBrightnessOverride = -1;
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700215 private boolean mHasHardwareAutoBrightness;
216 private boolean mAutoBrightessEnabled;
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700217 private int[] mAutoBrightnessLevels;
218 private int[] mLcdBacklightValues;
219 private int[] mButtonBacklightValues;
220 private int[] mKeyboardBacklightValues;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800221
222 // Used when logging number and duration of touch-down cycles
223 private long mTotalTouchDownTime;
224 private long mLastTouchDown;
225 private int mTouchCycles;
226
227 // could be either static or controllable at runtime
228 private static final boolean mSpew = false;
Mike Lockwooddd9668e2009-10-27 15:47:02 -0400229 private static final boolean mDebugLightSensor = (false || mSpew);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800230
231 /*
232 static PrintStream mLog;
233 static {
234 try {
235 mLog = new PrintStream("/data/power.log");
236 }
237 catch (FileNotFoundException e) {
238 android.util.Log.e(TAG, "Life is hard", e);
239 }
240 }
241 static class Log {
242 static void d(String tag, String s) {
243 mLog.println(s);
244 android.util.Log.d(tag, s);
245 }
246 static void i(String tag, String s) {
247 mLog.println(s);
248 android.util.Log.i(tag, s);
249 }
250 static void w(String tag, String s) {
251 mLog.println(s);
252 android.util.Log.w(tag, s);
253 }
254 static void e(String tag, String s) {
255 mLog.println(s);
256 android.util.Log.e(tag, s);
257 }
258 }
259 */
260
261 /**
262 * This class works around a deadlock between the lock in PowerManager.WakeLock
263 * and our synchronizing on mLocks. PowerManager.WakeLock synchronizes on its
264 * mToken object so it can be accessed from any thread, but it calls into here
265 * with its lock held. This class is essentially a reimplementation of
266 * PowerManager.WakeLock, but without that extra synchronized block, because we'll
267 * only call it with our own locks held.
268 */
269 private class UnsynchronizedWakeLock {
270 int mFlags;
271 String mTag;
272 IBinder mToken;
273 int mCount = 0;
274 boolean mRefCounted;
275
276 UnsynchronizedWakeLock(int flags, String tag, boolean refCounted) {
277 mFlags = flags;
278 mTag = tag;
279 mToken = new Binder();
280 mRefCounted = refCounted;
281 }
282
283 public void acquire() {
284 if (!mRefCounted || mCount++ == 0) {
285 long ident = Binder.clearCallingIdentity();
286 try {
287 PowerManagerService.this.acquireWakeLockLocked(mFlags, mToken,
288 MY_UID, mTag);
289 } finally {
290 Binder.restoreCallingIdentity(ident);
291 }
292 }
293 }
294
295 public void release() {
296 if (!mRefCounted || --mCount == 0) {
297 PowerManagerService.this.releaseWakeLockLocked(mToken, false);
298 }
299 if (mCount < 0) {
300 throw new RuntimeException("WakeLock under-locked " + mTag);
301 }
302 }
303
304 public String toString() {
305 return "UnsynchronizedWakeLock(mFlags=0x" + Integer.toHexString(mFlags)
306 + " mCount=" + mCount + ")";
307 }
308 }
309
310 private final class BatteryReceiver extends BroadcastReceiver {
311 @Override
312 public void onReceive(Context context, Intent intent) {
313 synchronized (mLocks) {
314 boolean wasPowered = mIsPowered;
315 mIsPowered = mBatteryService.isPowered();
316
317 if (mIsPowered != wasPowered) {
318 // update mStayOnWhilePluggedIn wake lock
319 updateWakeLockLocked();
320
321 // treat plugging and unplugging the devices as a user activity.
322 // users find it disconcerting when they unplug the device
323 // and it shuts off right away.
324 // temporarily set mUserActivityAllowed to true so this will work
325 // even when the keyguard is on.
326 synchronized (mLocks) {
Mike Lockwood200b30b2009-09-20 00:23:59 -0400327 forceUserActivityLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800328 }
329 }
330 }
331 }
332 }
333
334 /**
335 * Set the setting that determines whether the device stays on when plugged in.
336 * The argument is a bit string, with each bit specifying a power source that,
337 * when the device is connected to that source, causes the device to stay on.
338 * See {@link android.os.BatteryManager} for the list of power sources that
339 * can be specified. Current values include {@link android.os.BatteryManager#BATTERY_PLUGGED_AC}
340 * and {@link android.os.BatteryManager#BATTERY_PLUGGED_USB}
341 * @param val an {@code int} containing the bits that specify which power sources
342 * should cause the device to stay on.
343 */
344 public void setStayOnSetting(int val) {
345 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SETTINGS, null);
346 Settings.System.putInt(mContext.getContentResolver(),
347 Settings.System.STAY_ON_WHILE_PLUGGED_IN, val);
348 }
349
350 private class SettingsObserver implements Observer {
351 private int getInt(String name) {
352 return mSettings.getValues(name).getAsInteger(Settings.System.VALUE);
353 }
354
355 public void update(Observable o, Object arg) {
356 synchronized (mLocks) {
357 // STAY_ON_WHILE_PLUGGED_IN
358 mStayOnConditions = getInt(STAY_ON_WHILE_PLUGGED_IN);
359 updateWakeLockLocked();
360
361 // SCREEN_OFF_TIMEOUT
362 mTotalDelaySetting = getInt(SCREEN_OFF_TIMEOUT);
363
364 // DIM_SCREEN
365 //mDimScreen = getInt(DIM_SCREEN) != 0;
366
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700367 // SCREEN_BRIGHTNESS_MODE
368 setScreenBrightnessMode(getInt(SCREEN_BRIGHTNESS_MODE));
369
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800370 // recalculate everything
371 setScreenOffTimeoutsLocked();
372 }
373 }
374 }
375
376 PowerManagerService()
377 {
378 // Hack to get our uid... should have a func for this.
379 long token = Binder.clearCallingIdentity();
380 MY_UID = Binder.getCallingUid();
381 Binder.restoreCallingIdentity(token);
382
383 // XXX remove this when the kernel doesn't timeout wake locks
384 Power.setLastUserActivityTimeout(7*24*3600*1000); // one week
385
386 // assume nothing is on yet
387 mUserState = mPowerState = 0;
388
389 // Add ourself to the Watchdog monitors.
390 Watchdog.getInstance().addMonitor(this);
391 mScreenOnStartTime = SystemClock.elapsedRealtime();
392 }
393
394 private ContentQueryMap mSettings;
395
The Android Open Source Project10592532009-03-18 17:39:46 -0700396 void init(Context context, HardwareService hardware, IActivityManager activity,
397 BatteryService battery) {
398 mHardware = hardware;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800399 mContext = context;
400 mActivityService = activity;
401 mBatteryStats = BatteryStatsService.getService();
402 mBatteryService = battery;
403
404 mHandlerThread = new HandlerThread("PowerManagerService") {
405 @Override
406 protected void onLooperPrepared() {
407 super.onLooperPrepared();
408 initInThread();
409 }
410 };
411 mHandlerThread.start();
412
413 synchronized (mHandlerThread) {
414 while (!mInitComplete) {
415 try {
416 mHandlerThread.wait();
417 } catch (InterruptedException e) {
418 // Ignore
419 }
420 }
421 }
422 }
423
424 void initInThread() {
425 mHandler = new Handler();
426
427 mBroadcastWakeLock = new UnsynchronizedWakeLock(
Joe Onorato128e7292009-03-24 18:41:31 -0700428 PowerManager.PARTIAL_WAKE_LOCK, "sleep_broadcast", true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800429 mStayOnWhilePluggedInScreenDimLock = new UnsynchronizedWakeLock(
430 PowerManager.SCREEN_DIM_WAKE_LOCK, "StayOnWhilePluggedIn Screen Dim", false);
431 mStayOnWhilePluggedInPartialLock = new UnsynchronizedWakeLock(
432 PowerManager.PARTIAL_WAKE_LOCK, "StayOnWhilePluggedIn Partial", false);
433 mPreventScreenOnPartialLock = new UnsynchronizedWakeLock(
434 PowerManager.PARTIAL_WAKE_LOCK, "PreventScreenOn Partial", false);
435
436 mScreenOnIntent = new Intent(Intent.ACTION_SCREEN_ON);
437 mScreenOnIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
438 mScreenOffIntent = new Intent(Intent.ACTION_SCREEN_OFF);
439 mScreenOffIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
440
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700441 Resources resources = mContext.getResources();
442 mHasHardwareAutoBrightness = resources.getBoolean(
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700443 com.android.internal.R.bool.config_hardware_automatic_brightness_available);
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700444 if (!mHasHardwareAutoBrightness) {
445 mAutoBrightnessLevels = resources.getIntArray(
446 com.android.internal.R.array.config_autoBrightnessLevels);
447 mLcdBacklightValues = resources.getIntArray(
448 com.android.internal.R.array.config_autoBrightnessLcdBacklightValues);
449 mButtonBacklightValues = resources.getIntArray(
450 com.android.internal.R.array.config_autoBrightnessButtonBacklightValues);
451 mKeyboardBacklightValues = resources.getIntArray(
452 com.android.internal.R.array.config_autoBrightnessKeyboardBacklightValues);
453 }
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700454
455 ContentResolver resolver = mContext.getContentResolver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800456 Cursor settingsCursor = resolver.query(Settings.System.CONTENT_URI, null,
457 "(" + Settings.System.NAME + "=?) or ("
458 + Settings.System.NAME + "=?) or ("
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700459 + Settings.System.NAME + "=?) or ("
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800460 + Settings.System.NAME + "=?)",
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700461 new String[]{STAY_ON_WHILE_PLUGGED_IN, SCREEN_OFF_TIMEOUT, DIM_SCREEN,
462 SCREEN_BRIGHTNESS_MODE},
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800463 null);
464 mSettings = new ContentQueryMap(settingsCursor, Settings.System.NAME, true, mHandler);
465 SettingsObserver settingsObserver = new SettingsObserver();
466 mSettings.addObserver(settingsObserver);
467
468 // pretend that the settings changed so we will get their initial state
469 settingsObserver.update(mSettings, null);
470
471 // register for the battery changed notifications
472 IntentFilter filter = new IntentFilter();
473 filter.addAction(Intent.ACTION_BATTERY_CHANGED);
474 mContext.registerReceiver(new BatteryReceiver(), filter);
475
476 // Listen for Gservices changes
477 IntentFilter gservicesChangedFilter =
478 new IntentFilter(Settings.Gservices.CHANGED_ACTION);
479 mContext.registerReceiver(new GservicesChangedReceiver(), gservicesChangedFilter);
480 // And explicitly do the initial update of our cached settings
481 updateGservicesValues();
482
Mike Lockwood3333fa42009-10-26 14:50:42 -0400483 if (mAutoBrightessEnabled && !mHasHardwareAutoBrightness) {
Mike Lockwood6c97fca2009-10-20 08:10:00 -0400484 // turn the screen on
485 setPowerState(SCREEN_BRIGHT);
486 } else {
487 // turn everything on
488 setPowerState(ALL_BRIGHT);
489 }
Dan Murphy951764b2009-08-27 14:59:03 -0500490
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800491 synchronized (mHandlerThread) {
492 mInitComplete = true;
493 mHandlerThread.notifyAll();
494 }
495 }
496
497 private class WakeLock implements IBinder.DeathRecipient
498 {
499 WakeLock(int f, IBinder b, String t, int u) {
500 super();
501 flags = f;
502 binder = b;
503 tag = t;
504 uid = u == MY_UID ? Process.SYSTEM_UID : u;
505 if (u != MY_UID || (
506 !"KEEP_SCREEN_ON_FLAG".equals(tag)
507 && !"KeyInputQueue".equals(tag))) {
508 monitorType = (f & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK
509 ? BatteryStats.WAKE_TYPE_PARTIAL
510 : BatteryStats.WAKE_TYPE_FULL;
511 } else {
512 monitorType = -1;
513 }
514 try {
515 b.linkToDeath(this, 0);
516 } catch (RemoteException e) {
517 binderDied();
518 }
519 }
520 public void binderDied() {
521 synchronized (mLocks) {
522 releaseWakeLockLocked(this.binder, true);
523 }
524 }
525 final int flags;
526 final IBinder binder;
527 final String tag;
528 final int uid;
529 final int monitorType;
530 boolean activated = true;
531 int minState;
532 }
533
534 private void updateWakeLockLocked() {
535 if (mStayOnConditions != 0 && mBatteryService.isPowered(mStayOnConditions)) {
536 // keep the device on if we're plugged in and mStayOnWhilePluggedIn is set.
537 mStayOnWhilePluggedInScreenDimLock.acquire();
538 mStayOnWhilePluggedInPartialLock.acquire();
539 } else {
540 mStayOnWhilePluggedInScreenDimLock.release();
541 mStayOnWhilePluggedInPartialLock.release();
542 }
543 }
544
545 private boolean isScreenLock(int flags)
546 {
547 int n = flags & LOCK_MASK;
548 return n == PowerManager.FULL_WAKE_LOCK
549 || n == PowerManager.SCREEN_BRIGHT_WAKE_LOCK
550 || n == PowerManager.SCREEN_DIM_WAKE_LOCK;
551 }
552
553 public void acquireWakeLock(int flags, IBinder lock, String tag) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800554 int uid = Binder.getCallingUid();
Michael Chane96440f2009-05-06 10:27:36 -0700555 if (uid != Process.myUid()) {
556 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
557 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800558 long ident = Binder.clearCallingIdentity();
559 try {
560 synchronized (mLocks) {
561 acquireWakeLockLocked(flags, lock, uid, tag);
562 }
563 } finally {
564 Binder.restoreCallingIdentity(ident);
565 }
566 }
567
568 public void acquireWakeLockLocked(int flags, IBinder lock, int uid, String tag) {
569 int acquireUid = -1;
570 String acquireName = null;
571 int acquireType = -1;
572
573 if (mSpew) {
574 Log.d(TAG, "acquireWakeLock flags=0x" + Integer.toHexString(flags) + " tag=" + tag);
575 }
576
577 int index = mLocks.getIndex(lock);
578 WakeLock wl;
579 boolean newlock;
580 if (index < 0) {
581 wl = new WakeLock(flags, lock, tag, uid);
582 switch (wl.flags & LOCK_MASK)
583 {
584 case PowerManager.FULL_WAKE_LOCK:
Mike Lockwood3333fa42009-10-26 14:50:42 -0400585 if (mAutoBrightessEnabled && !mHasHardwareAutoBrightness) {
586 wl.minState = SCREEN_BRIGHT;
587 } else {
588 wl.minState = (mKeyboardVisible ? ALL_BRIGHT : SCREEN_BUTTON_BRIGHT);
589 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800590 break;
591 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
592 wl.minState = SCREEN_BRIGHT;
593 break;
594 case PowerManager.SCREEN_DIM_WAKE_LOCK:
595 wl.minState = SCREEN_DIM;
596 break;
597 case PowerManager.PARTIAL_WAKE_LOCK:
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700598 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800599 break;
600 default:
601 // just log and bail. we're in the server, so don't
602 // throw an exception.
603 Log.e(TAG, "bad wakelock type for lock '" + tag + "' "
604 + " flags=" + flags);
605 return;
606 }
607 mLocks.addLock(wl);
608 newlock = true;
609 } else {
610 wl = mLocks.get(index);
611 newlock = false;
612 }
613 if (isScreenLock(flags)) {
614 // if this causes a wakeup, we reactivate all of the locks and
615 // set it to whatever they want. otherwise, we modulate that
616 // by the current state so we never turn it more on than
617 // it already is.
618 if ((wl.flags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) {
Michael Chane96440f2009-05-06 10:27:36 -0700619 int oldWakeLockState = mWakeLockState;
620 mWakeLockState = mLocks.reactivateScreenLocksLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800621 if (mSpew) {
622 Log.d(TAG, "wakeup here mUserState=0x" + Integer.toHexString(mUserState)
Michael Chane96440f2009-05-06 10:27:36 -0700623 + " mWakeLockState=0x"
624 + Integer.toHexString(mWakeLockState)
625 + " previous wakeLockState=0x" + Integer.toHexString(oldWakeLockState));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800626 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800627 } else {
628 if (mSpew) {
629 Log.d(TAG, "here mUserState=0x" + Integer.toHexString(mUserState)
630 + " mLocks.gatherState()=0x"
631 + Integer.toHexString(mLocks.gatherState())
632 + " mWakeLockState=0x" + Integer.toHexString(mWakeLockState));
633 }
634 mWakeLockState = (mUserState | mWakeLockState) & mLocks.gatherState();
635 }
636 setPowerState(mWakeLockState | mUserState);
637 }
638 else if ((flags & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK) {
639 if (newlock) {
640 mPartialCount++;
641 if (mPartialCount == 1) {
642 if (LOG_PARTIAL_WL) EventLog.writeEvent(LOG_POWER_PARTIAL_WAKE_STATE, 1, tag);
643 }
644 }
645 Power.acquireWakeLock(Power.PARTIAL_WAKE_LOCK,PARTIAL_NAME);
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700646 } else if ((flags & LOCK_MASK) == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK) {
647 mProximityCount++;
648 if (mProximityCount == 1) {
649 enableProximityLockLocked();
650 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800651 }
652 if (newlock) {
653 acquireUid = wl.uid;
654 acquireName = wl.tag;
655 acquireType = wl.monitorType;
656 }
657
658 if (acquireType >= 0) {
659 try {
660 mBatteryStats.noteStartWakelock(acquireUid, acquireName, acquireType);
661 } catch (RemoteException e) {
662 // Ignore
663 }
664 }
665 }
666
667 public void releaseWakeLock(IBinder lock) {
Michael Chane96440f2009-05-06 10:27:36 -0700668 int uid = Binder.getCallingUid();
669 if (uid != Process.myUid()) {
670 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
671 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800672
673 synchronized (mLocks) {
674 releaseWakeLockLocked(lock, false);
675 }
676 }
677
678 private void releaseWakeLockLocked(IBinder lock, boolean death) {
679 int releaseUid;
680 String releaseName;
681 int releaseType;
682
683 WakeLock wl = mLocks.removeLock(lock);
684 if (wl == null) {
685 return;
686 }
687
688 if (mSpew) {
689 Log.d(TAG, "releaseWakeLock flags=0x"
690 + Integer.toHexString(wl.flags) + " tag=" + wl.tag);
691 }
692
693 if (isScreenLock(wl.flags)) {
694 mWakeLockState = mLocks.gatherState();
695 // goes in the middle to reduce flicker
696 if ((wl.flags & PowerManager.ON_AFTER_RELEASE) != 0) {
697 userActivity(SystemClock.uptimeMillis(), false);
698 }
699 setPowerState(mWakeLockState | mUserState);
700 }
701 else if ((wl.flags & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK) {
702 mPartialCount--;
703 if (mPartialCount == 0) {
704 if (LOG_PARTIAL_WL) EventLog.writeEvent(LOG_POWER_PARTIAL_WAKE_STATE, 0, wl.tag);
705 Power.releaseWakeLock(PARTIAL_NAME);
706 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700707 } else if ((wl.flags & LOCK_MASK) == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK) {
708 mProximityCount--;
709 if (mProximityCount == 0) {
710 disableProximityLockLocked();
711 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800712 }
713 // Unlink the lock from the binder.
714 wl.binder.unlinkToDeath(wl, 0);
715 releaseUid = wl.uid;
716 releaseName = wl.tag;
717 releaseType = wl.monitorType;
718
719 if (releaseType >= 0) {
720 long origId = Binder.clearCallingIdentity();
721 try {
722 mBatteryStats.noteStopWakelock(releaseUid, releaseName, releaseType);
723 } catch (RemoteException e) {
724 // Ignore
725 } finally {
726 Binder.restoreCallingIdentity(origId);
727 }
728 }
729 }
730
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800731 private class PokeLock implements IBinder.DeathRecipient
732 {
733 PokeLock(int p, IBinder b, String t) {
734 super();
735 this.pokey = p;
736 this.binder = b;
737 this.tag = t;
738 try {
739 b.linkToDeath(this, 0);
740 } catch (RemoteException e) {
741 binderDied();
742 }
743 }
744 public void binderDied() {
745 setPokeLock(0, this.binder, this.tag);
746 }
747 int pokey;
748 IBinder binder;
749 String tag;
750 boolean awakeOnSet;
751 }
752
753 public void setPokeLock(int pokey, IBinder token, String tag) {
754 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
755 if (token == null) {
756 Log.e(TAG, "setPokeLock got null token for tag='" + tag + "'");
757 return;
758 }
759
760 if ((pokey & POKE_LOCK_TIMEOUT_MASK) == POKE_LOCK_TIMEOUT_MASK) {
761 throw new IllegalArgumentException("setPokeLock can't have both POKE_LOCK_SHORT_TIMEOUT"
762 + " and POKE_LOCK_MEDIUM_TIMEOUT");
763 }
764
765 synchronized (mLocks) {
766 if (pokey != 0) {
767 PokeLock p = mPokeLocks.get(token);
768 int oldPokey = 0;
769 if (p != null) {
770 oldPokey = p.pokey;
771 p.pokey = pokey;
772 } else {
773 p = new PokeLock(pokey, token, tag);
774 mPokeLocks.put(token, p);
775 }
776 int oldTimeout = oldPokey & POKE_LOCK_TIMEOUT_MASK;
777 int newTimeout = pokey & POKE_LOCK_TIMEOUT_MASK;
778 if (((mPowerState & SCREEN_ON_BIT) == 0) && (oldTimeout != newTimeout)) {
779 p.awakeOnSet = true;
780 }
781 } else {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -0700782 PokeLock rLock = mPokeLocks.remove(token);
783 if (rLock != null) {
784 token.unlinkToDeath(rLock, 0);
785 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800786 }
787
788 int oldPokey = mPokey;
789 int cumulative = 0;
790 boolean oldAwakeOnSet = mPokeAwakeOnSet;
791 boolean awakeOnSet = false;
792 for (PokeLock p: mPokeLocks.values()) {
793 cumulative |= p.pokey;
794 if (p.awakeOnSet) {
795 awakeOnSet = true;
796 }
797 }
798 mPokey = cumulative;
799 mPokeAwakeOnSet = awakeOnSet;
800
801 int oldCumulativeTimeout = oldPokey & POKE_LOCK_TIMEOUT_MASK;
802 int newCumulativeTimeout = pokey & POKE_LOCK_TIMEOUT_MASK;
803
804 if (oldCumulativeTimeout != newCumulativeTimeout) {
805 setScreenOffTimeoutsLocked();
806 // reset the countdown timer, but use the existing nextState so it doesn't
807 // change anything
808 setTimeoutLocked(SystemClock.uptimeMillis(), mTimeoutTask.nextState);
809 }
810 }
811 }
812
813 private static String lockType(int type)
814 {
815 switch (type)
816 {
817 case PowerManager.FULL_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -0700818 return "FULL_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800819 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -0700820 return "SCREEN_BRIGHT_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800821 case PowerManager.SCREEN_DIM_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -0700822 return "SCREEN_DIM_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800823 case PowerManager.PARTIAL_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -0700824 return "PARTIAL_WAKE_LOCK ";
825 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
826 return "PROXIMITY_SCREEN_OFF_WAKE_LOCK";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800827 default:
David Brown251faa62009-08-02 22:04:36 -0700828 return "??? ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800829 }
830 }
831
832 private static String dumpPowerState(int state) {
833 return (((state & KEYBOARD_BRIGHT_BIT) != 0)
834 ? "KEYBOARD_BRIGHT_BIT " : "")
835 + (((state & SCREEN_BRIGHT_BIT) != 0)
836 ? "SCREEN_BRIGHT_BIT " : "")
837 + (((state & SCREEN_ON_BIT) != 0)
838 ? "SCREEN_ON_BIT " : "")
839 + (((state & BATTERY_LOW_BIT) != 0)
840 ? "BATTERY_LOW_BIT " : "");
841 }
842
843 @Override
844 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
845 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
846 != PackageManager.PERMISSION_GRANTED) {
847 pw.println("Permission Denial: can't dump PowerManager from from pid="
848 + Binder.getCallingPid()
849 + ", uid=" + Binder.getCallingUid());
850 return;
851 }
852
853 long now = SystemClock.uptimeMillis();
854
855 pw.println("Power Manager State:");
856 pw.println(" mIsPowered=" + mIsPowered
857 + " mPowerState=" + mPowerState
858 + " mScreenOffTime=" + (SystemClock.elapsedRealtime()-mScreenOffTime)
859 + " ms");
860 pw.println(" mPartialCount=" + mPartialCount);
861 pw.println(" mWakeLockState=" + dumpPowerState(mWakeLockState));
862 pw.println(" mUserState=" + dumpPowerState(mUserState));
863 pw.println(" mPowerState=" + dumpPowerState(mPowerState));
864 pw.println(" mLocks.gather=" + dumpPowerState(mLocks.gatherState()));
865 pw.println(" mNextTimeout=" + mNextTimeout + " now=" + now
866 + " " + ((mNextTimeout-now)/1000) + "s from now");
867 pw.println(" mDimScreen=" + mDimScreen
868 + " mStayOnConditions=" + mStayOnConditions);
869 pw.println(" mOffBecauseOfUser=" + mOffBecauseOfUser
870 + " mUserState=" + mUserState);
Joe Onorato128e7292009-03-24 18:41:31 -0700871 pw.println(" mBroadcastQueue={" + mBroadcastQueue[0] + ',' + mBroadcastQueue[1]
872 + ',' + mBroadcastQueue[2] + "}");
873 pw.println(" mBroadcastWhy={" + mBroadcastWhy[0] + ',' + mBroadcastWhy[1]
874 + ',' + mBroadcastWhy[2] + "}");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800875 pw.println(" mPokey=" + mPokey + " mPokeAwakeonSet=" + mPokeAwakeOnSet);
876 pw.println(" mKeyboardVisible=" + mKeyboardVisible
877 + " mUserActivityAllowed=" + mUserActivityAllowed);
878 pw.println(" mKeylightDelay=" + mKeylightDelay + " mDimDelay=" + mDimDelay
879 + " mScreenOffDelay=" + mScreenOffDelay);
880 pw.println(" mPreventScreenOn=" + mPreventScreenOn
881 + " mScreenBrightnessOverride=" + mScreenBrightnessOverride);
882 pw.println(" mTotalDelaySetting=" + mTotalDelaySetting);
883 pw.println(" mBroadcastWakeLock=" + mBroadcastWakeLock);
884 pw.println(" mStayOnWhilePluggedInScreenDimLock=" + mStayOnWhilePluggedInScreenDimLock);
885 pw.println(" mStayOnWhilePluggedInPartialLock=" + mStayOnWhilePluggedInPartialLock);
886 pw.println(" mPreventScreenOnPartialLock=" + mPreventScreenOnPartialLock);
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700887 pw.println(" mProximitySensorActive=" + mProximitySensorActive);
888 pw.println(" mLightSensorEnabled=" + mLightSensorEnabled);
889 pw.println(" mLightSensorValue=" + mLightSensorValue);
890 pw.println(" mLightSensorPendingValue=" + mLightSensorPendingValue);
891 pw.println(" mHasHardwareAutoBrightness=" + mHasHardwareAutoBrightness);
892 pw.println(" mAutoBrightessEnabled=" + mAutoBrightessEnabled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800893 mScreenBrightness.dump(pw, " mScreenBrightness: ");
894 mKeyboardBrightness.dump(pw, " mKeyboardBrightness: ");
895 mButtonBrightness.dump(pw, " mButtonBrightness: ");
896
897 int N = mLocks.size();
898 pw.println();
899 pw.println("mLocks.size=" + N + ":");
900 for (int i=0; i<N; i++) {
901 WakeLock wl = mLocks.get(i);
902 String type = lockType(wl.flags & LOCK_MASK);
903 String acquireCausesWakeup = "";
904 if ((wl.flags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) {
905 acquireCausesWakeup = "ACQUIRE_CAUSES_WAKEUP ";
906 }
907 String activated = "";
908 if (wl.activated) {
909 activated = " activated";
910 }
911 pw.println(" " + type + " '" + wl.tag + "'" + acquireCausesWakeup
912 + activated + " (minState=" + wl.minState + ")");
913 }
914
915 pw.println();
916 pw.println("mPokeLocks.size=" + mPokeLocks.size() + ":");
917 for (PokeLock p: mPokeLocks.values()) {
918 pw.println(" poke lock '" + p.tag + "':"
919 + ((p.pokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0
920 ? " POKE_LOCK_IGNORE_CHEEK_EVENTS" : "")
Joe Onoratoe68ffcb2009-03-24 19:11:13 -0700921 + ((p.pokey & POKE_LOCK_IGNORE_TOUCH_AND_CHEEK_EVENTS) != 0
922 ? " POKE_LOCK_IGNORE_TOUCH_AND_CHEEK_EVENTS" : "")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800923 + ((p.pokey & POKE_LOCK_SHORT_TIMEOUT) != 0
924 ? " POKE_LOCK_SHORT_TIMEOUT" : "")
925 + ((p.pokey & POKE_LOCK_MEDIUM_TIMEOUT) != 0
926 ? " POKE_LOCK_MEDIUM_TIMEOUT" : ""));
927 }
928
929 pw.println();
930 }
931
932 private void setTimeoutLocked(long now, int nextState)
933 {
934 if (mDoneBooting) {
935 mHandler.removeCallbacks(mTimeoutTask);
936 mTimeoutTask.nextState = nextState;
937 long when = now;
938 switch (nextState)
939 {
940 case SCREEN_BRIGHT:
941 when += mKeylightDelay;
942 break;
943 case SCREEN_DIM:
944 if (mDimDelay >= 0) {
945 when += mDimDelay;
946 break;
947 } else {
948 Log.w(TAG, "mDimDelay=" + mDimDelay + " while trying to dim");
949 }
950 case SCREEN_OFF:
951 synchronized (mLocks) {
952 when += mScreenOffDelay;
953 }
954 break;
955 }
956 if (mSpew) {
957 Log.d(TAG, "setTimeoutLocked now=" + now + " nextState=" + nextState
958 + " when=" + when);
959 }
960 mHandler.postAtTime(mTimeoutTask, when);
961 mNextTimeout = when; // for debugging
962 }
963 }
964
965 private void cancelTimerLocked()
966 {
967 mHandler.removeCallbacks(mTimeoutTask);
968 mTimeoutTask.nextState = -1;
969 }
970
971 private class TimeoutTask implements Runnable
972 {
973 int nextState; // access should be synchronized on mLocks
974 public void run()
975 {
976 synchronized (mLocks) {
977 if (mSpew) {
978 Log.d(TAG, "user activity timeout timed out nextState=" + this.nextState);
979 }
980
981 if (nextState == -1) {
982 return;
983 }
984
985 mUserState = this.nextState;
986 setPowerState(this.nextState | mWakeLockState);
987
988 long now = SystemClock.uptimeMillis();
989
990 switch (this.nextState)
991 {
992 case SCREEN_BRIGHT:
993 if (mDimDelay >= 0) {
994 setTimeoutLocked(now, SCREEN_DIM);
995 break;
996 }
997 case SCREEN_DIM:
998 setTimeoutLocked(now, SCREEN_OFF);
999 break;
1000 }
1001 }
1002 }
1003 }
1004
1005 private void sendNotificationLocked(boolean on, int why)
1006 {
Joe Onorato64c62ba2009-03-24 20:13:57 -07001007 if (!on) {
1008 mStillNeedSleepNotification = false;
1009 }
1010
Joe Onorato128e7292009-03-24 18:41:31 -07001011 // Add to the queue.
1012 int index = 0;
1013 while (mBroadcastQueue[index] != -1) {
1014 index++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001015 }
Joe Onorato128e7292009-03-24 18:41:31 -07001016 mBroadcastQueue[index] = on ? 1 : 0;
1017 mBroadcastWhy[index] = why;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001018
Joe Onorato128e7292009-03-24 18:41:31 -07001019 // If we added it position 2, then there is a pair that can be stripped.
1020 // If we added it position 1 and we're turning the screen off, we can strip
1021 // the pair and do nothing, because the screen is already off, and therefore
1022 // keyguard has already been enabled.
1023 // However, if we added it at position 1 and we're turning it on, then position
1024 // 0 was to turn it off, and we can't strip that, because keyguard needs to come
1025 // on, so have to run the queue then.
1026 if (index == 2) {
1027 // Also, while we're collapsing them, if it's going to be an "off," and one
1028 // is off because of user, then use that, regardless of whether it's the first
1029 // or second one.
1030 if (!on && why == WindowManagerPolicy.OFF_BECAUSE_OF_USER) {
1031 mBroadcastWhy[0] = WindowManagerPolicy.OFF_BECAUSE_OF_USER;
1032 }
1033 mBroadcastQueue[0] = on ? 1 : 0;
1034 mBroadcastQueue[1] = -1;
1035 mBroadcastQueue[2] = -1;
1036 index = 0;
1037 }
1038 if (index == 1 && !on) {
1039 mBroadcastQueue[0] = -1;
1040 mBroadcastQueue[1] = -1;
1041 index = -1;
1042 // The wake lock was being held, but we're not actually going to do any
1043 // broadcasts, so release the wake lock.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001044 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_STOP, 1, mBroadcastWakeLock.mCount);
1045 mBroadcastWakeLock.release();
Joe Onorato128e7292009-03-24 18:41:31 -07001046 }
1047
1048 // Now send the message.
1049 if (index >= 0) {
1050 // Acquire the broadcast wake lock before changing the power
1051 // state. It will be release after the broadcast is sent.
1052 // We always increment the ref count for each notification in the queue
1053 // and always decrement when that notification is handled.
1054 mBroadcastWakeLock.acquire();
1055 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_SEND, mBroadcastWakeLock.mCount);
1056 mHandler.post(mNotificationTask);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001057 }
1058 }
1059
1060 private Runnable mNotificationTask = new Runnable()
1061 {
1062 public void run()
1063 {
Joe Onorato128e7292009-03-24 18:41:31 -07001064 while (true) {
1065 int value;
1066 int why;
1067 WindowManagerPolicy policy;
1068 synchronized (mLocks) {
1069 value = mBroadcastQueue[0];
1070 why = mBroadcastWhy[0];
1071 for (int i=0; i<2; i++) {
1072 mBroadcastQueue[i] = mBroadcastQueue[i+1];
1073 mBroadcastWhy[i] = mBroadcastWhy[i+1];
1074 }
1075 policy = getPolicyLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001076 }
Joe Onorato128e7292009-03-24 18:41:31 -07001077 if (value == 1) {
1078 mScreenOnStart = SystemClock.uptimeMillis();
1079
1080 policy.screenTurnedOn();
1081 try {
1082 ActivityManagerNative.getDefault().wakingUp();
1083 } catch (RemoteException e) {
1084 // ignore it
1085 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001086
Joe Onorato128e7292009-03-24 18:41:31 -07001087 if (mSpew) {
1088 Log.d(TAG, "mBroadcastWakeLock=" + mBroadcastWakeLock);
1089 }
1090 if (mContext != null && ActivityManagerNative.isSystemReady()) {
1091 mContext.sendOrderedBroadcast(mScreenOnIntent, null,
1092 mScreenOnBroadcastDone, mHandler, 0, null, null);
1093 } else {
1094 synchronized (mLocks) {
1095 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_STOP, 2,
1096 mBroadcastWakeLock.mCount);
1097 mBroadcastWakeLock.release();
1098 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001099 }
1100 }
Joe Onorato128e7292009-03-24 18:41:31 -07001101 else if (value == 0) {
1102 mScreenOffStart = SystemClock.uptimeMillis();
1103
1104 policy.screenTurnedOff(why);
1105 try {
1106 ActivityManagerNative.getDefault().goingToSleep();
1107 } catch (RemoteException e) {
1108 // ignore it.
1109 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001110
Joe Onorato128e7292009-03-24 18:41:31 -07001111 if (mContext != null && ActivityManagerNative.isSystemReady()) {
1112 mContext.sendOrderedBroadcast(mScreenOffIntent, null,
1113 mScreenOffBroadcastDone, mHandler, 0, null, null);
1114 } else {
1115 synchronized (mLocks) {
1116 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_STOP, 3,
1117 mBroadcastWakeLock.mCount);
1118 mBroadcastWakeLock.release();
1119 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001120 }
1121 }
Joe Onorato128e7292009-03-24 18:41:31 -07001122 else {
1123 // If we're in this case, then this handler is running for a previous
1124 // paired transaction. mBroadcastWakeLock will already have been released.
1125 break;
1126 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001127 }
1128 }
1129 };
1130
1131 long mScreenOnStart;
1132 private BroadcastReceiver mScreenOnBroadcastDone = new BroadcastReceiver() {
1133 public void onReceive(Context context, Intent intent) {
1134 synchronized (mLocks) {
1135 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_DONE, 1,
1136 SystemClock.uptimeMillis() - mScreenOnStart, mBroadcastWakeLock.mCount);
1137 mBroadcastWakeLock.release();
1138 }
1139 }
1140 };
1141
1142 long mScreenOffStart;
1143 private BroadcastReceiver mScreenOffBroadcastDone = new BroadcastReceiver() {
1144 public void onReceive(Context context, Intent intent) {
1145 synchronized (mLocks) {
1146 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_DONE, 0,
1147 SystemClock.uptimeMillis() - mScreenOffStart, mBroadcastWakeLock.mCount);
1148 mBroadcastWakeLock.release();
1149 }
1150 }
1151 };
1152
1153 void logPointerUpEvent() {
1154 if (LOG_TOUCH_DOWNS) {
1155 mTotalTouchDownTime += SystemClock.elapsedRealtime() - mLastTouchDown;
1156 mLastTouchDown = 0;
1157 }
1158 }
1159
1160 void logPointerDownEvent() {
1161 if (LOG_TOUCH_DOWNS) {
1162 // If we are not already timing a down/up sequence
1163 if (mLastTouchDown == 0) {
1164 mLastTouchDown = SystemClock.elapsedRealtime();
1165 mTouchCycles++;
1166 }
1167 }
1168 }
1169
1170 /**
1171 * Prevents the screen from turning on even if it *should* turn on due
1172 * to a subsequent full wake lock being acquired.
1173 * <p>
1174 * This is a temporary hack that allows an activity to "cover up" any
1175 * display glitches that happen during the activity's startup
1176 * sequence. (Specifically, this API was added to work around a
1177 * cosmetic bug in the "incoming call" sequence, where the lock screen
1178 * would flicker briefly before the incoming call UI became visible.)
1179 * TODO: There ought to be a more elegant way of doing this,
1180 * probably by having the PowerManager and ActivityManager
1181 * work together to let apps specify that the screen on/off
1182 * state should be synchronized with the Activity lifecycle.
1183 * <p>
1184 * Note that calling preventScreenOn(true) will NOT turn the screen
1185 * off if it's currently on. (This API only affects *future*
1186 * acquisitions of full wake locks.)
1187 * But calling preventScreenOn(false) WILL turn the screen on if
1188 * it's currently off because of a prior preventScreenOn(true) call.
1189 * <p>
1190 * Any call to preventScreenOn(true) MUST be followed promptly by a call
1191 * to preventScreenOn(false). In fact, if the preventScreenOn(false)
1192 * call doesn't occur within 5 seconds, we'll turn the screen back on
1193 * ourselves (and log a warning about it); this prevents a buggy app
1194 * from disabling the screen forever.)
1195 * <p>
1196 * TODO: this feature should really be controlled by a new type of poke
1197 * lock (rather than an IPowerManager call).
1198 */
1199 public void preventScreenOn(boolean prevent) {
1200 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1201
1202 synchronized (mLocks) {
1203 if (prevent) {
1204 // First of all, grab a partial wake lock to
1205 // make sure the CPU stays on during the entire
1206 // preventScreenOn(true) -> preventScreenOn(false) sequence.
1207 mPreventScreenOnPartialLock.acquire();
1208
1209 // Post a forceReenableScreen() call (for 5 seconds in the
1210 // future) to make sure the matching preventScreenOn(false) call
1211 // has happened by then.
1212 mHandler.removeCallbacks(mForceReenableScreenTask);
1213 mHandler.postDelayed(mForceReenableScreenTask, 5000);
1214
1215 // Finally, set the flag that prevents the screen from turning on.
1216 // (Below, in setPowerState(), we'll check mPreventScreenOn and
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001217 // we *won't* call setScreenStateLocked(true) if it's set.)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001218 mPreventScreenOn = true;
1219 } else {
1220 // (Re)enable the screen.
1221 mPreventScreenOn = false;
1222
1223 // We're "undoing" a the prior preventScreenOn(true) call, so we
1224 // no longer need the 5-second safeguard.
1225 mHandler.removeCallbacks(mForceReenableScreenTask);
1226
1227 // Forcibly turn on the screen if it's supposed to be on. (This
1228 // handles the case where the screen is currently off because of
1229 // a prior preventScreenOn(true) call.)
1230 if ((mPowerState & SCREEN_ON_BIT) != 0) {
1231 if (mSpew) {
1232 Log.d(TAG,
1233 "preventScreenOn: turning on after a prior preventScreenOn(true)!");
1234 }
Mike Lockwoodf003c0c2009-10-21 16:03:18 -04001235 mAnimatingScreenOff = false;
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001236 int err = setScreenStateLocked(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001237 if (err != 0) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001238 Log.w(TAG, "preventScreenOn: error from setScreenStateLocked(): " + err);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001239 }
1240 }
1241
1242 // Release the partial wake lock that we held during the
1243 // preventScreenOn(true) -> preventScreenOn(false) sequence.
1244 mPreventScreenOnPartialLock.release();
1245 }
1246 }
1247 }
1248
1249 public void setScreenBrightnessOverride(int brightness) {
1250 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1251
1252 synchronized (mLocks) {
1253 if (mScreenBrightnessOverride != brightness) {
1254 mScreenBrightnessOverride = brightness;
1255 updateLightsLocked(mPowerState, SCREEN_ON_BIT);
1256 }
1257 }
1258 }
1259
1260 /**
1261 * Sanity-check that gets called 5 seconds after any call to
1262 * preventScreenOn(true). This ensures that the original call
1263 * is followed promptly by a call to preventScreenOn(false).
1264 */
1265 private void forceReenableScreen() {
1266 // We shouldn't get here at all if mPreventScreenOn is false, since
1267 // we should have already removed any existing
1268 // mForceReenableScreenTask messages...
1269 if (!mPreventScreenOn) {
1270 Log.w(TAG, "forceReenableScreen: mPreventScreenOn is false, nothing to do");
1271 return;
1272 }
1273
1274 // Uh oh. It's been 5 seconds since a call to
1275 // preventScreenOn(true) and we haven't re-enabled the screen yet.
1276 // This means the app that called preventScreenOn(true) is either
1277 // slow (i.e. it took more than 5 seconds to call preventScreenOn(false)),
1278 // or buggy (i.e. it forgot to call preventScreenOn(false), or
1279 // crashed before doing so.)
1280
1281 // Log a warning, and forcibly turn the screen back on.
1282 Log.w(TAG, "App called preventScreenOn(true) but didn't promptly reenable the screen! "
1283 + "Forcing the screen back on...");
1284 preventScreenOn(false);
1285 }
1286
1287 private Runnable mForceReenableScreenTask = new Runnable() {
1288 public void run() {
1289 forceReenableScreen();
1290 }
1291 };
1292
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001293 private int setScreenStateLocked(boolean on) {
1294 int err = Power.setScreenState(on);
Mike Lockwood6eb14c32009-10-24 19:43:38 -04001295 if (err == 0 && !mHasHardwareAutoBrightness) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001296 enableLightSensor(on && mAutoBrightessEnabled);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001297 if (!on) {
1298 // make sure button and key backlights are off too
1299 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_BUTTONS, 0);
1300 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_KEYBOARD, 0);
Mike Lockwood6c97fca2009-10-20 08:10:00 -04001301 // clear current value so we will update based on the new conditions
1302 // when the sensor is reenabled.
1303 mLightSensorValue = -1;
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001304 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001305 }
1306 return err;
1307 }
1308
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001309 private void setPowerState(int state)
1310 {
1311 setPowerState(state, false, false);
1312 }
1313
1314 private void setPowerState(int newState, boolean noChangeLights, boolean becauseOfUser)
1315 {
1316 synchronized (mLocks) {
1317 int err;
1318
1319 if (mSpew) {
1320 Log.d(TAG, "setPowerState: mPowerState=0x" + Integer.toHexString(mPowerState)
1321 + " newState=0x" + Integer.toHexString(newState)
1322 + " noChangeLights=" + noChangeLights);
1323 }
1324
1325 if (noChangeLights) {
1326 newState = (newState & ~LIGHTS_MASK) | (mPowerState & LIGHTS_MASK);
1327 }
Mike Lockwood36fc3022009-08-25 16:49:06 -07001328 if (mProximitySensorActive) {
1329 // don't turn on the screen when the proximity sensor lock is held
1330 newState = (newState & ~SCREEN_BRIGHT);
1331 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001332
1333 if (batteryIsLow()) {
1334 newState |= BATTERY_LOW_BIT;
1335 } else {
1336 newState &= ~BATTERY_LOW_BIT;
1337 }
1338 if (newState == mPowerState) {
1339 return;
1340 }
Mike Lockwood3333fa42009-10-26 14:50:42 -04001341
1342 if (!mDoneBooting && !(mAutoBrightessEnabled && !mHasHardwareAutoBrightness)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001343 newState |= ALL_BRIGHT;
1344 }
1345
1346 boolean oldScreenOn = (mPowerState & SCREEN_ON_BIT) != 0;
1347 boolean newScreenOn = (newState & SCREEN_ON_BIT) != 0;
1348
1349 if (mSpew) {
1350 Log.d(TAG, "setPowerState: mPowerState=" + mPowerState
1351 + " newState=" + newState + " noChangeLights=" + noChangeLights);
1352 Log.d(TAG, " oldKeyboardBright=" + ((mPowerState & KEYBOARD_BRIGHT_BIT) != 0)
1353 + " newKeyboardBright=" + ((newState & KEYBOARD_BRIGHT_BIT) != 0));
1354 Log.d(TAG, " oldScreenBright=" + ((mPowerState & SCREEN_BRIGHT_BIT) != 0)
1355 + " newScreenBright=" + ((newState & SCREEN_BRIGHT_BIT) != 0));
1356 Log.d(TAG, " oldButtonBright=" + ((mPowerState & BUTTON_BRIGHT_BIT) != 0)
1357 + " newButtonBright=" + ((newState & BUTTON_BRIGHT_BIT) != 0));
1358 Log.d(TAG, " oldScreenOn=" + oldScreenOn
1359 + " newScreenOn=" + newScreenOn);
1360 Log.d(TAG, " oldBatteryLow=" + ((mPowerState & BATTERY_LOW_BIT) != 0)
1361 + " newBatteryLow=" + ((newState & BATTERY_LOW_BIT) != 0));
1362 }
1363
1364 if (mPowerState != newState) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001365 updateLightsLocked(newState, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001366 mPowerState = (mPowerState & ~LIGHTS_MASK) | (newState & LIGHTS_MASK);
1367 }
1368
1369 if (oldScreenOn != newScreenOn) {
1370 if (newScreenOn) {
Joe Onorato128e7292009-03-24 18:41:31 -07001371 // When the user presses the power button, we need to always send out the
1372 // notification that it's going to sleep so the keyguard goes on. But
1373 // we can't do that until the screen fades out, so we don't show the keyguard
1374 // too early.
1375 if (mStillNeedSleepNotification) {
1376 sendNotificationLocked(false, WindowManagerPolicy.OFF_BECAUSE_OF_USER);
1377 }
1378
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001379 // Turn on the screen UNLESS there was a prior
1380 // preventScreenOn(true) request. (Note that the lifetime
1381 // of a single preventScreenOn() request is limited to 5
1382 // seconds to prevent a buggy app from disabling the
1383 // screen forever; see forceReenableScreen().)
1384 boolean reallyTurnScreenOn = true;
1385 if (mSpew) {
1386 Log.d(TAG, "- turning screen on... mPreventScreenOn = "
1387 + mPreventScreenOn);
1388 }
1389
1390 if (mPreventScreenOn) {
1391 if (mSpew) {
1392 Log.d(TAG, "- PREVENTING screen from really turning on!");
1393 }
1394 reallyTurnScreenOn = false;
1395 }
1396 if (reallyTurnScreenOn) {
Mike Lockwoodf003c0c2009-10-21 16:03:18 -04001397 mAnimatingScreenOff = false;
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001398 err = setScreenStateLocked(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001399 long identity = Binder.clearCallingIdentity();
1400 try {
Dianne Hackborn617f8772009-03-31 15:04:46 -07001401 mBatteryStats.noteScreenBrightness(
1402 getPreferredBrightness());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001403 mBatteryStats.noteScreenOn();
1404 } catch (RemoteException e) {
1405 Log.w(TAG, "RemoteException calling noteScreenOn on BatteryStatsService", e);
1406 } finally {
1407 Binder.restoreCallingIdentity(identity);
1408 }
1409 } else {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001410 setScreenStateLocked(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001411 // But continue as if we really did turn the screen on...
1412 err = 0;
1413 }
1414
1415 mScreenOnStartTime = SystemClock.elapsedRealtime();
1416 mLastTouchDown = 0;
1417 mTotalTouchDownTime = 0;
1418 mTouchCycles = 0;
1419 EventLog.writeEvent(LOG_POWER_SCREEN_STATE, 1, becauseOfUser ? 1 : 0,
1420 mTotalTouchDownTime, mTouchCycles);
1421 if (err == 0) {
1422 mPowerState |= SCREEN_ON_BIT;
1423 sendNotificationLocked(true, -1);
1424 }
1425 } else {
1426 mScreenOffTime = SystemClock.elapsedRealtime();
1427 long identity = Binder.clearCallingIdentity();
1428 try {
1429 mBatteryStats.noteScreenOff();
1430 } catch (RemoteException e) {
1431 Log.w(TAG, "RemoteException calling noteScreenOff on BatteryStatsService", e);
1432 } finally {
1433 Binder.restoreCallingIdentity(identity);
1434 }
1435 mPowerState &= ~SCREEN_ON_BIT;
1436 if (!mScreenBrightness.animating) {
Joe Onorato128e7292009-03-24 18:41:31 -07001437 err = screenOffFinishedAnimatingLocked(becauseOfUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001438 } else {
Mike Lockwoodf003c0c2009-10-21 16:03:18 -04001439 mAnimatingScreenOff = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001440 mOffBecauseOfUser = becauseOfUser;
1441 err = 0;
1442 mLastTouchDown = 0;
1443 }
1444 }
1445 }
1446 }
1447 }
1448
Joe Onorato128e7292009-03-24 18:41:31 -07001449 private int screenOffFinishedAnimatingLocked(boolean becauseOfUser) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001450 // I don't think we need to check the current state here because all of these
1451 // Power.setScreenState and sendNotificationLocked can both handle being
1452 // called multiple times in the same state. -joeo
1453 EventLog.writeEvent(LOG_POWER_SCREEN_STATE, 0, becauseOfUser ? 1 : 0,
1454 mTotalTouchDownTime, mTouchCycles);
1455 mLastTouchDown = 0;
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001456 int err = setScreenStateLocked(false);
Mike Lockwoodf003c0c2009-10-21 16:03:18 -04001457 mAnimatingScreenOff = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001458 if (mScreenOnStartTime != 0) {
1459 mScreenOnTime += SystemClock.elapsedRealtime() - mScreenOnStartTime;
1460 mScreenOnStartTime = 0;
1461 }
1462 if (err == 0) {
1463 int why = becauseOfUser
1464 ? WindowManagerPolicy.OFF_BECAUSE_OF_USER
1465 : WindowManagerPolicy.OFF_BECAUSE_OF_TIMEOUT;
1466 sendNotificationLocked(false, why);
1467 }
1468 return err;
1469 }
1470
1471 private boolean batteryIsLow() {
1472 return (!mIsPowered &&
1473 mBatteryService.getBatteryLevel() <= Power.LOW_BATTERY_THRESHOLD);
1474 }
1475
The Android Open Source Project10592532009-03-18 17:39:46 -07001476 private void updateLightsLocked(int newState, int forceState) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001477 final int oldState = mPowerState;
1478 final int realDifference = (newState ^ oldState);
1479 final int difference = realDifference | forceState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001480 if (difference == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001481 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001482 }
1483
1484 int offMask = 0;
1485 int dimMask = 0;
1486 int onMask = 0;
1487
1488 int preferredBrightness = getPreferredBrightness();
1489 boolean startAnimation = false;
1490
1491 if ((difference & KEYBOARD_BRIGHT_BIT) != 0) {
1492 if (ANIMATE_KEYBOARD_LIGHTS) {
1493 if ((newState & KEYBOARD_BRIGHT_BIT) == 0) {
1494 mKeyboardBrightness.setTargetLocked(Power.BRIGHTNESS_OFF,
Joe Onorato128e7292009-03-24 18:41:31 -07001495 ANIM_STEPS, INITIAL_KEYBOARD_BRIGHTNESS,
1496 preferredBrightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001497 } else {
1498 mKeyboardBrightness.setTargetLocked(preferredBrightness,
Joe Onorato128e7292009-03-24 18:41:31 -07001499 ANIM_STEPS, INITIAL_KEYBOARD_BRIGHTNESS,
1500 Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001501 }
1502 startAnimation = true;
1503 } else {
1504 if ((newState & KEYBOARD_BRIGHT_BIT) == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001505 offMask |= KEYBOARD_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001506 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001507 onMask |= KEYBOARD_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001508 }
1509 }
1510 }
1511
1512 if ((difference & BUTTON_BRIGHT_BIT) != 0) {
1513 if (ANIMATE_BUTTON_LIGHTS) {
1514 if ((newState & BUTTON_BRIGHT_BIT) == 0) {
1515 mButtonBrightness.setTargetLocked(Power.BRIGHTNESS_OFF,
Joe Onorato128e7292009-03-24 18:41:31 -07001516 ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
1517 preferredBrightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001518 } else {
1519 mButtonBrightness.setTargetLocked(preferredBrightness,
Joe Onorato128e7292009-03-24 18:41:31 -07001520 ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
1521 Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001522 }
1523 startAnimation = true;
1524 } else {
1525 if ((newState & BUTTON_BRIGHT_BIT) == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001526 offMask |= BUTTON_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001527 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001528 onMask |= BUTTON_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001529 }
1530 }
1531 }
1532
1533 if ((difference & (SCREEN_ON_BIT | SCREEN_BRIGHT_BIT)) != 0) {
1534 if (ANIMATE_SCREEN_LIGHTS) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001535 int nominalCurrentValue = -1;
1536 // If there was an actual difference in the light state, then
1537 // figure out the "ideal" current value based on the previous
1538 // state. Otherwise, this is a change due to the brightness
1539 // override, so we want to animate from whatever the current
1540 // value is.
1541 if ((realDifference & (SCREEN_ON_BIT | SCREEN_BRIGHT_BIT)) != 0) {
1542 switch (oldState & (SCREEN_BRIGHT_BIT|SCREEN_ON_BIT)) {
1543 case SCREEN_BRIGHT_BIT | SCREEN_ON_BIT:
1544 nominalCurrentValue = preferredBrightness;
1545 break;
1546 case SCREEN_ON_BIT:
1547 nominalCurrentValue = Power.BRIGHTNESS_DIM;
1548 break;
1549 case 0:
1550 nominalCurrentValue = Power.BRIGHTNESS_OFF;
1551 break;
1552 case SCREEN_BRIGHT_BIT:
1553 default:
1554 // not possible
1555 nominalCurrentValue = (int)mScreenBrightness.curValue;
1556 break;
1557 }
Joe Onorato128e7292009-03-24 18:41:31 -07001558 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001559 int brightness = preferredBrightness;
1560 int steps = ANIM_STEPS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001561 if ((newState & SCREEN_BRIGHT_BIT) == 0) {
1562 // dim or turn off backlight, depending on if the screen is on
1563 // the scale is because the brightness ramp isn't linear and this biases
1564 // it so the later parts take longer.
1565 final float scale = 1.5f;
1566 float ratio = (((float)Power.BRIGHTNESS_DIM)/preferredBrightness);
1567 if (ratio > 1.0f) ratio = 1.0f;
1568 if ((newState & SCREEN_ON_BIT) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001569 if ((oldState & SCREEN_BRIGHT_BIT) != 0) {
1570 // was bright
1571 steps = ANIM_STEPS;
1572 } else {
1573 // was dim
1574 steps = (int)(ANIM_STEPS*ratio*scale);
1575 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001576 brightness = Power.BRIGHTNESS_OFF;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001577 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001578 if ((oldState & SCREEN_ON_BIT) != 0) {
1579 // was bright
1580 steps = (int)(ANIM_STEPS*(1.0f-ratio)*scale);
1581 } else {
1582 // was dim
1583 steps = (int)(ANIM_STEPS*ratio);
1584 }
1585 if (mStayOnConditions != 0 && mBatteryService.isPowered(mStayOnConditions)) {
1586 // If the "stay on while plugged in" option is
1587 // turned on, then the screen will often not
1588 // automatically turn off while plugged in. To
1589 // still have a sense of when it is inactive, we
1590 // will then count going dim as turning off.
1591 mScreenOffTime = SystemClock.elapsedRealtime();
1592 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001593 brightness = Power.BRIGHTNESS_DIM;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001594 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001595 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001596 long identity = Binder.clearCallingIdentity();
1597 try {
1598 mBatteryStats.noteScreenBrightness(brightness);
1599 } catch (RemoteException e) {
1600 // Nothing interesting to do.
1601 } finally {
1602 Binder.restoreCallingIdentity(identity);
1603 }
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001604 if (mScreenBrightness.setTargetLocked(brightness,
1605 steps, INITIAL_SCREEN_BRIGHTNESS, nominalCurrentValue)) {
1606 startAnimation = true;
1607 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001608 } else {
1609 if ((newState & SCREEN_BRIGHT_BIT) == 0) {
1610 // dim or turn off backlight, depending on if the screen is on
1611 if ((newState & SCREEN_ON_BIT) == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001612 offMask |= SCREEN_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001613 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001614 dimMask |= SCREEN_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001615 }
1616 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001617 onMask |= SCREEN_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001618 }
1619 }
1620 }
1621
1622 if (startAnimation) {
1623 if (mSpew) {
1624 Log.i(TAG, "Scheduling light animator!");
1625 }
1626 mHandler.removeCallbacks(mLightAnimator);
1627 mHandler.post(mLightAnimator);
1628 }
1629
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001630 if (offMask != 0) {
1631 //Log.i(TAG, "Setting brightess off: " + offMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001632 setLightBrightness(offMask, Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001633 }
1634 if (dimMask != 0) {
1635 int brightness = Power.BRIGHTNESS_DIM;
1636 if ((newState & BATTERY_LOW_BIT) != 0 &&
1637 brightness > Power.BRIGHTNESS_LOW_BATTERY) {
1638 brightness = Power.BRIGHTNESS_LOW_BATTERY;
1639 }
1640 //Log.i(TAG, "Setting brightess dim " + brightness + ": " + offMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001641 setLightBrightness(dimMask, brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001642 }
1643 if (onMask != 0) {
1644 int brightness = getPreferredBrightness();
1645 if ((newState & BATTERY_LOW_BIT) != 0 &&
1646 brightness > Power.BRIGHTNESS_LOW_BATTERY) {
1647 brightness = Power.BRIGHTNESS_LOW_BATTERY;
1648 }
1649 //Log.i(TAG, "Setting brightess on " + brightness + ": " + onMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001650 setLightBrightness(onMask, brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001651 }
The Android Open Source Project10592532009-03-18 17:39:46 -07001652 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001653
The Android Open Source Project10592532009-03-18 17:39:46 -07001654 private void setLightBrightness(int mask, int value) {
1655 if ((mask & SCREEN_BRIGHT_BIT) != 0) {
1656 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_BACKLIGHT, value);
1657 }
1658 if ((mask & BUTTON_BRIGHT_BIT) != 0) {
1659 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_BUTTONS, value);
1660 }
1661 if ((mask & KEYBOARD_BRIGHT_BIT) != 0) {
1662 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_KEYBOARD, value);
1663 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001664 }
1665
1666 class BrightnessState {
1667 final int mask;
1668
1669 boolean initialized;
1670 int targetValue;
1671 float curValue;
1672 float delta;
1673 boolean animating;
1674
1675 BrightnessState(int m) {
1676 mask = m;
1677 }
1678
1679 public void dump(PrintWriter pw, String prefix) {
1680 pw.println(prefix + "animating=" + animating
1681 + " targetValue=" + targetValue
1682 + " curValue=" + curValue
1683 + " delta=" + delta);
1684 }
1685
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001686 boolean setTargetLocked(int target, int stepsToTarget, int initialValue,
Joe Onorato128e7292009-03-24 18:41:31 -07001687 int nominalCurrentValue) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001688 if (!initialized) {
1689 initialized = true;
1690 curValue = (float)initialValue;
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001691 } else if (targetValue == target) {
1692 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001693 }
1694 targetValue = target;
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001695 delta = (targetValue -
1696 (nominalCurrentValue >= 0 ? nominalCurrentValue : curValue))
1697 / stepsToTarget;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001698 if (mSpew) {
Joe Onorato128e7292009-03-24 18:41:31 -07001699 String noticeMe = nominalCurrentValue == curValue ? "" : " ******************";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001700 Log.i(TAG, "Setting target " + mask + ": cur=" + curValue
Joe Onorato128e7292009-03-24 18:41:31 -07001701 + " target=" + targetValue + " delta=" + delta
1702 + " nominalCurrentValue=" + nominalCurrentValue
1703 + noticeMe);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001704 }
1705 animating = true;
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001706 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001707 }
1708
1709 boolean stepLocked() {
1710 if (!animating) return false;
1711 if (false && mSpew) {
1712 Log.i(TAG, "Step target " + mask + ": cur=" + curValue
1713 + " target=" + targetValue + " delta=" + delta);
1714 }
1715 curValue += delta;
1716 int curIntValue = (int)curValue;
1717 boolean more = true;
1718 if (delta == 0) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001719 curValue = curIntValue = targetValue;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001720 more = false;
1721 } else if (delta > 0) {
1722 if (curIntValue >= targetValue) {
1723 curValue = curIntValue = targetValue;
1724 more = false;
1725 }
1726 } else {
1727 if (curIntValue <= targetValue) {
1728 curValue = curIntValue = targetValue;
1729 more = false;
1730 }
1731 }
1732 //Log.i(TAG, "Animating brightess " + curIntValue + ": " + mask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001733 setLightBrightness(mask, curIntValue);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001734 animating = more;
1735 if (!more) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001736 if (mask == SCREEN_BRIGHT_BIT && curIntValue == Power.BRIGHTNESS_OFF) {
Joe Onorato128e7292009-03-24 18:41:31 -07001737 screenOffFinishedAnimatingLocked(mOffBecauseOfUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001738 }
1739 }
1740 return more;
1741 }
1742 }
1743
1744 private class LightAnimator implements Runnable {
1745 public void run() {
1746 synchronized (mLocks) {
1747 long now = SystemClock.uptimeMillis();
1748 boolean more = mScreenBrightness.stepLocked();
1749 if (mKeyboardBrightness.stepLocked()) {
1750 more = true;
1751 }
1752 if (mButtonBrightness.stepLocked()) {
1753 more = true;
1754 }
1755 if (more) {
1756 mHandler.postAtTime(mLightAnimator, now+(1000/60));
1757 }
1758 }
1759 }
1760 }
1761
1762 private int getPreferredBrightness() {
1763 try {
1764 if (mScreenBrightnessOverride >= 0) {
1765 return mScreenBrightnessOverride;
Mike Lockwood3333fa42009-10-26 14:50:42 -04001766 } else if (mLightSensorBrightness >= 0 && !mHasHardwareAutoBrightness) {
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001767 return mLightSensorBrightness;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001768 }
1769 final int brightness = Settings.System.getInt(mContext.getContentResolver(),
1770 SCREEN_BRIGHTNESS);
1771 // Don't let applications turn the screen all the way off
1772 return Math.max(brightness, Power.BRIGHTNESS_DIM);
1773 } catch (SettingNotFoundException snfe) {
1774 return Power.BRIGHTNESS_ON;
1775 }
1776 }
1777
1778 boolean screenIsOn() {
1779 synchronized (mLocks) {
1780 return (mPowerState & SCREEN_ON_BIT) != 0;
1781 }
1782 }
1783
1784 boolean screenIsBright() {
1785 synchronized (mLocks) {
1786 return (mPowerState & SCREEN_BRIGHT) == SCREEN_BRIGHT;
1787 }
1788 }
1789
Mike Lockwood200b30b2009-09-20 00:23:59 -04001790 private void forceUserActivityLocked() {
1791 boolean savedActivityAllowed = mUserActivityAllowed;
1792 mUserActivityAllowed = true;
1793 userActivity(SystemClock.uptimeMillis(), false);
1794 mUserActivityAllowed = savedActivityAllowed;
1795 }
1796
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001797 public void userActivityWithForce(long time, boolean noChangeLights, boolean force) {
1798 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1799 userActivity(time, noChangeLights, OTHER_EVENT, force);
1800 }
1801
1802 public void userActivity(long time, boolean noChangeLights) {
1803 userActivity(time, noChangeLights, OTHER_EVENT, false);
1804 }
1805
1806 public void userActivity(long time, boolean noChangeLights, int eventType) {
1807 userActivity(time, noChangeLights, eventType, false);
1808 }
1809
1810 public void userActivity(long time, boolean noChangeLights, int eventType, boolean force) {
1811 //mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1812
1813 if (((mPokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0)
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07001814 && (eventType == CHEEK_EVENT || eventType == TOUCH_EVENT)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001815 if (false) {
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07001816 Log.d(TAG, "dropping cheek or short event mPokey=0x" + Integer.toHexString(mPokey));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001817 }
1818 return;
1819 }
1820
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07001821 if (((mPokey & POKE_LOCK_IGNORE_TOUCH_AND_CHEEK_EVENTS) != 0)
1822 && (eventType == TOUCH_EVENT || eventType == TOUCH_UP_EVENT
1823 || eventType == LONG_TOUCH_EVENT || eventType == CHEEK_EVENT)) {
1824 if (false) {
1825 Log.d(TAG, "dropping touch mPokey=0x" + Integer.toHexString(mPokey));
1826 }
1827 return;
1828 }
1829
Mike Lockwoodf003c0c2009-10-21 16:03:18 -04001830 if (mAnimatingScreenOff) {
1831 return;
1832 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001833 if (false) {
1834 if (((mPokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0)) {
1835 Log.d(TAG, "userActivity !!!");//, new RuntimeException());
1836 } else {
1837 Log.d(TAG, "mPokey=0x" + Integer.toHexString(mPokey));
1838 }
1839 }
1840
1841 synchronized (mLocks) {
1842 if (mSpew) {
1843 Log.d(TAG, "userActivity mLastEventTime=" + mLastEventTime + " time=" + time
1844 + " mUserActivityAllowed=" + mUserActivityAllowed
1845 + " mUserState=0x" + Integer.toHexString(mUserState)
Mike Lockwood36fc3022009-08-25 16:49:06 -07001846 + " mWakeLockState=0x" + Integer.toHexString(mWakeLockState)
1847 + " mProximitySensorActive=" + mProximitySensorActive
1848 + " force=" + force);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001849 }
1850 if (mLastEventTime <= time || force) {
1851 mLastEventTime = time;
Mike Lockwood36fc3022009-08-25 16:49:06 -07001852 if ((mUserActivityAllowed && !mProximitySensorActive) || force) {
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001853 // Only turn on button backlights if a button was pressed
1854 // and auto brightness is disabled
Mike Lockwood3333fa42009-10-26 14:50:42 -04001855 if (eventType == BUTTON_EVENT &&
1856 !(mAutoBrightessEnabled && !mHasHardwareAutoBrightness)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001857 mUserState = (mKeyboardVisible ? ALL_BRIGHT : SCREEN_BUTTON_BRIGHT);
1858 } else {
1859 // don't clear button/keyboard backlights when the screen is touched.
1860 mUserState |= SCREEN_BRIGHT;
1861 }
1862
Dianne Hackborn617f8772009-03-31 15:04:46 -07001863 int uid = Binder.getCallingUid();
1864 long ident = Binder.clearCallingIdentity();
1865 try {
1866 mBatteryStats.noteUserActivity(uid, eventType);
1867 } catch (RemoteException e) {
1868 // Ignore
1869 } finally {
1870 Binder.restoreCallingIdentity(ident);
1871 }
1872
Michael Chane96440f2009-05-06 10:27:36 -07001873 mWakeLockState = mLocks.reactivateScreenLocksLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001874 setPowerState(mUserState | mWakeLockState, noChangeLights, true);
1875 setTimeoutLocked(time, SCREEN_BRIGHT);
1876 }
1877 }
1878 }
1879 }
1880
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001881 private int getAutoBrightnessValue(int sensorValue, int[] values) {
1882 try {
1883 int i;
1884 for (i = 0; i < mAutoBrightnessLevels.length; i++) {
1885 if (sensorValue < mAutoBrightnessLevels[i]) {
1886 break;
1887 }
1888 }
1889 return values[i];
1890 } catch (Exception e) {
1891 // guard against null pointer or index out of bounds errors
1892 Log.e(TAG, "getAutoBrightnessValue", e);
1893 return 255;
1894 }
1895 }
1896
1897 private Runnable mAutoBrightnessTask = new Runnable() {
1898 public void run() {
Mike Lockwoodfa68ab42009-10-20 11:08:49 -04001899 synchronized (mLocks) {
1900 int value = (int)mLightSensorPendingValue;
1901 if (value >= 0) {
1902 mLightSensorPendingValue = -1;
1903 lightSensorChangedLocked(value);
1904 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001905 }
1906 }
1907 };
1908
1909 private void lightSensorChangedLocked(int value) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001910 if (mDebugLightSensor) {
1911 Log.d(TAG, "lightSensorChangedLocked " + value);
1912 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001913
Mike Lockwood3333fa42009-10-26 14:50:42 -04001914 if (mHasHardwareAutoBrightness) return;
1915
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001916 if (mLightSensorValue != value) {
1917 mLightSensorValue = value;
1918 if ((mPowerState & BATTERY_LOW_BIT) == 0) {
1919 int lcdValue = getAutoBrightnessValue(value, mLcdBacklightValues);
1920 int buttonValue = getAutoBrightnessValue(value, mButtonBacklightValues);
1921 int keyboardValue = getAutoBrightnessValue(value, mKeyboardBacklightValues);
1922 mLightSensorBrightness = lcdValue;
1923
1924 if (mDebugLightSensor) {
1925 Log.d(TAG, "lcdValue " + lcdValue);
1926 Log.d(TAG, "buttonValue " + buttonValue);
1927 Log.d(TAG, "keyboardValue " + keyboardValue);
1928 }
1929
Mike Lockwooddd9668e2009-10-27 15:47:02 -04001930 boolean startAnimation = false;
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001931 if (mScreenBrightnessOverride < 0) {
Mike Lockwooddd9668e2009-10-27 15:47:02 -04001932 if (ANIMATE_SCREEN_LIGHTS) {
1933 if (mScreenBrightness.setTargetLocked(lcdValue,
1934 AUTOBRIGHTNESS_ANIM_STEPS, INITIAL_SCREEN_BRIGHTNESS,
1935 (int)mScreenBrightness.curValue)) {
1936 startAnimation = true;
1937 }
1938 } else {
1939 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_BACKLIGHT,
1940 lcdValue);
1941 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001942 }
1943 if (ANIMATE_BUTTON_LIGHTS) {
Mike Lockwooddd9668e2009-10-27 15:47:02 -04001944 if (mButtonBrightness.setTargetLocked(buttonValue,
1945 AUTOBRIGHTNESS_ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
1946 (int)mButtonBrightness.curValue)) {
1947 startAnimation = true;
1948 }
1949 } else {
1950 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_BUTTONS,
1951 buttonValue);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001952 }
1953 if (ANIMATE_KEYBOARD_LIGHTS) {
Mike Lockwooddd9668e2009-10-27 15:47:02 -04001954 if (mKeyboardBrightness.setTargetLocked(keyboardValue,
1955 AUTOBRIGHTNESS_ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
1956 (int)mKeyboardBrightness.curValue)) {
1957 startAnimation = true;
1958 }
1959 } else {
1960 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_KEYBOARD,
1961 keyboardValue);
1962 }
1963 if (startAnimation) {
1964 if (mDebugLightSensor) {
1965 Log.i(TAG, "lightSensorChangedLocked scheduling light animator");
1966 }
1967 mHandler.removeCallbacks(mLightAnimator);
1968 mHandler.post(mLightAnimator);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001969 }
1970 }
1971 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001972 }
1973
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001974 /**
1975 * The user requested that we go to sleep (probably with the power button).
1976 * This overrides all wake locks that are held.
1977 */
1978 public void goToSleep(long time)
1979 {
1980 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1981 synchronized (mLocks) {
1982 goToSleepLocked(time);
1983 }
1984 }
1985
1986 /**
1987 * Returns the time the screen has been on since boot, in millis.
1988 * @return screen on time
1989 */
1990 public long getScreenOnTime() {
1991 synchronized (mLocks) {
1992 if (mScreenOnStartTime == 0) {
1993 return mScreenOnTime;
1994 } else {
1995 return SystemClock.elapsedRealtime() - mScreenOnStartTime + mScreenOnTime;
1996 }
1997 }
1998 }
1999
2000 private void goToSleepLocked(long time) {
2001
2002 if (mLastEventTime <= time) {
2003 mLastEventTime = time;
2004 // cancel all of the wake locks
2005 mWakeLockState = SCREEN_OFF;
2006 int N = mLocks.size();
2007 int numCleared = 0;
2008 for (int i=0; i<N; i++) {
2009 WakeLock wl = mLocks.get(i);
2010 if (isScreenLock(wl.flags)) {
2011 mLocks.get(i).activated = false;
2012 numCleared++;
2013 }
2014 }
2015 EventLog.writeEvent(LOG_POWER_SLEEP_REQUESTED, numCleared);
Joe Onorato128e7292009-03-24 18:41:31 -07002016 mStillNeedSleepNotification = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002017 mUserState = SCREEN_OFF;
2018 setPowerState(SCREEN_OFF, false, true);
2019 cancelTimerLocked();
2020 }
2021 }
2022
2023 public long timeSinceScreenOn() {
2024 synchronized (mLocks) {
2025 if ((mPowerState & SCREEN_ON_BIT) != 0) {
2026 return 0;
2027 }
2028 return SystemClock.elapsedRealtime() - mScreenOffTime;
2029 }
2030 }
2031
2032 public void setKeyboardVisibility(boolean visible) {
Mike Lockwooda625b382009-09-12 17:36:03 -07002033 synchronized (mLocks) {
2034 if (mSpew) {
2035 Log.d(TAG, "setKeyboardVisibility: " + visible);
2036 }
Mike Lockwood3c9435a2009-10-22 15:45:37 -04002037 if (mKeyboardVisible != visible) {
2038 mKeyboardVisible = visible;
2039 // don't signal user activity if the screen is off; other code
2040 // will take care of turning on due to a true change to the lid
2041 // switch and synchronized with the lock screen.
2042 if ((mPowerState & SCREEN_ON_BIT) != 0) {
2043 userActivity(SystemClock.uptimeMillis(), false, BUTTON_EVENT, true);
2044 }
Mike Lockwooda625b382009-09-12 17:36:03 -07002045 }
2046 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002047 }
2048
2049 /**
2050 * When the keyguard is up, it manages the power state, and userActivity doesn't do anything.
2051 */
2052 public void enableUserActivity(boolean enabled) {
2053 synchronized (mLocks) {
2054 mUserActivityAllowed = enabled;
2055 mLastEventTime = SystemClock.uptimeMillis(); // we might need to pass this in
2056 }
2057 }
2058
Mike Lockwooddc3494e2009-10-14 21:17:09 -07002059 private void setScreenBrightnessMode(int mode) {
Mike Lockwood2d155d22009-10-27 09:32:30 -04002060 boolean enabled = (mode == SCREEN_BRIGHTNESS_MODE_AUTOMATIC);
2061 if (mAutoBrightessEnabled != enabled) {
2062 mAutoBrightessEnabled = enabled;
2063 // reset computed brightness
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002064 mLightSensorValue = -1;
Mike Lockwood2d155d22009-10-27 09:32:30 -04002065 mLightSensorBrightness = -1;
Mike Lockwooddc3494e2009-10-14 21:17:09 -07002066
Mike Lockwood2d155d22009-10-27 09:32:30 -04002067 if (mHasHardwareAutoBrightness) {
2068 // When setting auto-brightness, must reset the brightness afterwards
2069 mHardware.setAutoBrightness_UNCHECKED(enabled);
2070 if (screenIsOn()) {
2071 setBacklightBrightness((int)mScreenBrightness.curValue);
2072 }
2073 } else {
2074 enableLightSensor(screenIsOn() && enabled);
2075 }
Mike Lockwooddc3494e2009-10-14 21:17:09 -07002076 }
2077 }
2078
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002079 /** Sets the screen off timeouts:
2080 * mKeylightDelay
2081 * mDimDelay
2082 * mScreenOffDelay
2083 * */
2084 private void setScreenOffTimeoutsLocked() {
2085 if ((mPokey & POKE_LOCK_SHORT_TIMEOUT) != 0) {
2086 mKeylightDelay = mShortKeylightDelay; // Configurable via Gservices
2087 mDimDelay = -1;
2088 mScreenOffDelay = 0;
2089 } else if ((mPokey & POKE_LOCK_MEDIUM_TIMEOUT) != 0) {
2090 mKeylightDelay = MEDIUM_KEYLIGHT_DELAY;
2091 mDimDelay = -1;
2092 mScreenOffDelay = 0;
2093 } else {
2094 int totalDelay = mTotalDelaySetting;
2095 mKeylightDelay = LONG_KEYLIGHT_DELAY;
2096 if (totalDelay < 0) {
2097 mScreenOffDelay = Integer.MAX_VALUE;
2098 } else if (mKeylightDelay < totalDelay) {
2099 // subtract the time that the keylight delay. This will give us the
2100 // remainder of the time that we need to sleep to get the accurate
2101 // screen off timeout.
2102 mScreenOffDelay = totalDelay - mKeylightDelay;
2103 } else {
2104 mScreenOffDelay = 0;
2105 }
2106 if (mDimScreen && totalDelay >= (LONG_KEYLIGHT_DELAY + LONG_DIM_TIME)) {
2107 mDimDelay = mScreenOffDelay - LONG_DIM_TIME;
2108 mScreenOffDelay = LONG_DIM_TIME;
2109 } else {
2110 mDimDelay = -1;
2111 }
2112 }
2113 if (mSpew) {
2114 Log.d(TAG, "setScreenOffTimeouts mKeylightDelay=" + mKeylightDelay
2115 + " mDimDelay=" + mDimDelay + " mScreenOffDelay=" + mScreenOffDelay
2116 + " mDimScreen=" + mDimScreen);
2117 }
2118 }
2119
2120 /**
2121 * Refreshes cached Gservices settings. Called once on startup, and
2122 * on subsequent Settings.Gservices.CHANGED_ACTION broadcasts (see
2123 * GservicesChangedReceiver).
2124 */
2125 private void updateGservicesValues() {
2126 mShortKeylightDelay = Settings.Gservices.getInt(
2127 mContext.getContentResolver(),
2128 Settings.Gservices.SHORT_KEYLIGHT_DELAY_MS,
2129 SHORT_KEYLIGHT_DELAY_DEFAULT);
2130 // Log.i(TAG, "updateGservicesValues(): mShortKeylightDelay now " + mShortKeylightDelay);
2131 }
2132
2133 /**
2134 * Receiver for the Gservices.CHANGED_ACTION broadcast intent,
2135 * which tells us we need to refresh our cached Gservices settings.
2136 */
2137 private class GservicesChangedReceiver extends BroadcastReceiver {
2138 @Override
2139 public void onReceive(Context context, Intent intent) {
2140 // Log.i(TAG, "GservicesChangedReceiver.onReceive(): " + intent);
2141 updateGservicesValues();
2142 }
2143 }
2144
2145 private class LockList extends ArrayList<WakeLock>
2146 {
2147 void addLock(WakeLock wl)
2148 {
2149 int index = getIndex(wl.binder);
2150 if (index < 0) {
2151 this.add(wl);
2152 }
2153 }
2154
2155 WakeLock removeLock(IBinder binder)
2156 {
2157 int index = getIndex(binder);
2158 if (index >= 0) {
2159 return this.remove(index);
2160 } else {
2161 return null;
2162 }
2163 }
2164
2165 int getIndex(IBinder binder)
2166 {
2167 int N = this.size();
2168 for (int i=0; i<N; i++) {
2169 if (this.get(i).binder == binder) {
2170 return i;
2171 }
2172 }
2173 return -1;
2174 }
2175
2176 int gatherState()
2177 {
2178 int result = 0;
2179 int N = this.size();
2180 for (int i=0; i<N; i++) {
2181 WakeLock wl = this.get(i);
2182 if (wl.activated) {
2183 if (isScreenLock(wl.flags)) {
2184 result |= wl.minState;
2185 }
2186 }
2187 }
2188 return result;
2189 }
Michael Chane96440f2009-05-06 10:27:36 -07002190
2191 int reactivateScreenLocksLocked()
2192 {
2193 int result = 0;
2194 int N = this.size();
2195 for (int i=0; i<N; i++) {
2196 WakeLock wl = this.get(i);
2197 if (isScreenLock(wl.flags)) {
2198 wl.activated = true;
2199 result |= wl.minState;
2200 }
2201 }
2202 return result;
2203 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002204 }
2205
2206 void setPolicy(WindowManagerPolicy p) {
2207 synchronized (mLocks) {
2208 mPolicy = p;
2209 mLocks.notifyAll();
2210 }
2211 }
2212
2213 WindowManagerPolicy getPolicyLocked() {
2214 while (mPolicy == null || !mDoneBooting) {
2215 try {
2216 mLocks.wait();
2217 } catch (InterruptedException e) {
2218 // Ignore
2219 }
2220 }
2221 return mPolicy;
2222 }
2223
2224 void systemReady() {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002225 mSensorManager = new SensorManager(mHandlerThread.getLooper());
2226 mProximitySensor = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
2227 // don't bother with the light sensor if auto brightness is handled in hardware
2228 if (!mHasHardwareAutoBrightness) {
2229 mLightSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
2230 enableLightSensor(mAutoBrightessEnabled);
2231 }
2232
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002233 synchronized (mLocks) {
2234 Log.d(TAG, "system ready!");
2235 mDoneBooting = true;
Dianne Hackborn617f8772009-03-31 15:04:46 -07002236 long identity = Binder.clearCallingIdentity();
2237 try {
2238 mBatteryStats.noteScreenBrightness(getPreferredBrightness());
2239 mBatteryStats.noteScreenOn();
2240 } catch (RemoteException e) {
2241 // Nothing interesting to do.
2242 } finally {
2243 Binder.restoreCallingIdentity(identity);
2244 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002245 userActivity(SystemClock.uptimeMillis(), false, BUTTON_EVENT, true);
2246 updateWakeLockLocked();
2247 mLocks.notifyAll();
2248 }
2249 }
2250
2251 public void monitor() {
2252 synchronized (mLocks) { }
2253 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002254
2255 public int getSupportedWakeLockFlags() {
2256 int result = PowerManager.PARTIAL_WAKE_LOCK
2257 | PowerManager.FULL_WAKE_LOCK
2258 | PowerManager.SCREEN_DIM_WAKE_LOCK;
2259
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002260 if (mProximitySensor != null) {
2261 result |= PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK;
2262 }
2263
2264 return result;
2265 }
2266
Mike Lockwood237a2992009-09-15 14:42:16 -04002267 public void setBacklightBrightness(int brightness) {
2268 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
2269 // Don't let applications turn the screen all the way off
2270 brightness = Math.max(brightness, Power.BRIGHTNESS_DIM);
2271 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_BACKLIGHT, brightness);
2272 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_KEYBOARD, brightness);
2273 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_BUTTONS, brightness);
2274 long identity = Binder.clearCallingIdentity();
2275 try {
2276 mBatteryStats.noteScreenBrightness(brightness);
2277 } catch (RemoteException e) {
2278 Log.w(TAG, "RemoteException calling noteScreenBrightness on BatteryStatsService", e);
2279 } finally {
2280 Binder.restoreCallingIdentity(identity);
2281 }
2282
2283 // update our animation state
2284 if (ANIMATE_SCREEN_LIGHTS) {
2285 mScreenBrightness.curValue = brightness;
2286 mScreenBrightness.animating = false;
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002287 mScreenBrightness.targetValue = -1;
Mike Lockwood237a2992009-09-15 14:42:16 -04002288 }
2289 if (ANIMATE_KEYBOARD_LIGHTS) {
2290 mKeyboardBrightness.curValue = brightness;
2291 mKeyboardBrightness.animating = false;
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002292 mKeyboardBrightness.targetValue = -1;
Mike Lockwood237a2992009-09-15 14:42:16 -04002293 }
2294 if (ANIMATE_BUTTON_LIGHTS) {
2295 mButtonBrightness.curValue = brightness;
2296 mButtonBrightness.animating = false;
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002297 mButtonBrightness.targetValue = -1;
Mike Lockwood237a2992009-09-15 14:42:16 -04002298 }
2299 }
2300
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002301 private void enableProximityLockLocked() {
Mike Lockwood36fc3022009-08-25 16:49:06 -07002302 if (mSpew) {
2303 Log.d(TAG, "enableProximityLockLocked");
2304 }
Mike Lockwood809ad0f2009-10-26 22:10:33 -04002305 // clear calling identity so sensor manager battery stats are accurate
2306 long identity = Binder.clearCallingIdentity();
2307 try {
2308 mSensorManager.registerListener(mProximityListener, mProximitySensor,
2309 SensorManager.SENSOR_DELAY_NORMAL);
2310 } finally {
2311 Binder.restoreCallingIdentity(identity);
2312 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002313 }
2314
2315 private void disableProximityLockLocked() {
Mike Lockwood36fc3022009-08-25 16:49:06 -07002316 if (mSpew) {
2317 Log.d(TAG, "disableProximityLockLocked");
2318 }
Mike Lockwood809ad0f2009-10-26 22:10:33 -04002319 // clear calling identity so sensor manager battery stats are accurate
2320 long identity = Binder.clearCallingIdentity();
2321 try {
2322 mSensorManager.unregisterListener(mProximityListener);
2323 } finally {
2324 Binder.restoreCallingIdentity(identity);
2325 }
Mike Lockwood200b30b2009-09-20 00:23:59 -04002326 synchronized (mLocks) {
2327 if (mProximitySensorActive) {
2328 mProximitySensorActive = false;
2329 forceUserActivityLocked();
2330 }
2331 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002332 }
2333
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002334 private void enableLightSensor(boolean enable) {
2335 if (mDebugLightSensor) {
2336 Log.d(TAG, "enableLightSensor " + enable);
2337 }
2338 if (mSensorManager != null && mLightSensorEnabled != enable) {
2339 mLightSensorEnabled = enable;
Mike Lockwood809ad0f2009-10-26 22:10:33 -04002340 // clear calling identity so sensor manager battery stats are accurate
2341 long identity = Binder.clearCallingIdentity();
2342 try {
2343 if (enable) {
2344 mSensorManager.registerListener(mLightListener, mLightSensor,
2345 SensorManager.SENSOR_DELAY_NORMAL);
2346 } else {
2347 mSensorManager.unregisterListener(mLightListener);
2348 mHandler.removeCallbacks(mAutoBrightnessTask);
2349 }
2350 } finally {
2351 Binder.restoreCallingIdentity(identity);
Mike Lockwood06952d92009-08-13 16:05:38 -04002352 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002353 }
2354 }
2355
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002356 SensorEventListener mProximityListener = new SensorEventListener() {
2357 public void onSensorChanged(SensorEvent event) {
2358 long milliseconds = event.timestamp / 1000000;
2359 synchronized (mLocks) {
2360 float distance = event.values[0];
2361 // compare against getMaximumRange to support sensors that only return 0 or 1
2362 if (distance >= 0.0 && distance < PROXIMITY_THRESHOLD &&
2363 distance < mProximitySensor.getMaximumRange()) {
2364 if (mSpew) {
2365 Log.d(TAG, "onSensorChanged: proximity active, distance: " + distance);
2366 }
2367 goToSleepLocked(milliseconds);
2368 mProximitySensorActive = true;
2369 } else {
2370 // proximity sensor negative events trigger as user activity.
2371 // temporarily set mUserActivityAllowed to true so this will work
2372 // even when the keyguard is on.
2373 if (mSpew) {
2374 Log.d(TAG, "onSensorChanged: proximity inactive, distance: " + distance);
2375 }
2376 mProximitySensorActive = false;
2377 forceUserActivityLocked();
2378 }
2379 }
2380 }
2381
2382 public void onAccuracyChanged(Sensor sensor, int accuracy) {
2383 // ignore
2384 }
2385 };
2386
2387 SensorEventListener mLightListener = new SensorEventListener() {
2388 public void onSensorChanged(SensorEvent event) {
2389 synchronized (mLocks) {
2390 int value = (int)event.values[0];
2391 if (mDebugLightSensor) {
2392 Log.d(TAG, "onSensorChanged: light value: " + value);
2393 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002394 mHandler.removeCallbacks(mAutoBrightnessTask);
2395 if (mLightSensorValue != value) {
Mike Lockwood6c97fca2009-10-20 08:10:00 -04002396 if (mLightSensorValue == -1) {
2397 // process the value immediately
2398 lightSensorChangedLocked(value);
2399 } else {
2400 // delay processing to debounce the sensor
2401 mLightSensorPendingValue = value;
2402 mHandler.postDelayed(mAutoBrightnessTask, LIGHT_SENSOR_DELAY);
2403 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002404 } else {
2405 mLightSensorPendingValue = -1;
2406 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002407 }
2408 }
2409
2410 public void onAccuracyChanged(Sensor sensor, int accuracy) {
2411 // ignore
2412 }
2413 };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002414}