blob: 890c58c197f837e96c5961f5dcd795a4a2fc9d42 [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;
31import android.database.Cursor;
32import android.os.BatteryStats;
33import android.os.Binder;
34import android.os.Handler;
35import android.os.HandlerThread;
36import android.os.IBinder;
37import android.os.IPowerManager;
38import android.os.LocalPowerManager;
39import android.os.Power;
40import android.os.PowerManager;
41import android.os.Process;
42import android.os.RemoteException;
43import android.os.SystemClock;
44import android.provider.Settings.SettingNotFoundException;
45import android.provider.Settings;
46import android.util.EventLog;
47import android.util.Log;
48import android.view.WindowManagerPolicy;
49import static android.provider.Settings.System.DIM_SCREEN;
50import static android.provider.Settings.System.SCREEN_BRIGHTNESS;
51import static android.provider.Settings.System.SCREEN_OFF_TIMEOUT;
52import static android.provider.Settings.System.STAY_ON_WHILE_PLUGGED_IN;
53
54import java.io.FileDescriptor;
55import java.io.PrintWriter;
56import java.util.ArrayList;
57import java.util.HashMap;
58import java.util.Observable;
59import java.util.Observer;
60
61class PowerManagerService extends IPowerManager.Stub implements LocalPowerManager, Watchdog.Monitor {
62
63 private static final String TAG = "PowerManagerService";
64 static final String PARTIAL_NAME = "PowerManagerService";
65
66 private static final boolean LOG_PARTIAL_WL = false;
67
68 // Indicates whether touch-down cycles should be logged as part of the
69 // LOG_POWER_SCREEN_STATE log events
70 private static final boolean LOG_TOUCH_DOWNS = true;
71
72 private static final int LOCK_MASK = PowerManager.PARTIAL_WAKE_LOCK
73 | PowerManager.SCREEN_DIM_WAKE_LOCK
74 | PowerManager.SCREEN_BRIGHT_WAKE_LOCK
75 | PowerManager.FULL_WAKE_LOCK;
76
77 // time since last state: time since last event:
78 // The short keylight delay comes from Gservices; this is the default.
79 private static final int SHORT_KEYLIGHT_DELAY_DEFAULT = 6000; // t+6 sec
80 private static final int MEDIUM_KEYLIGHT_DELAY = 15000; // t+15 sec
81 private static final int LONG_KEYLIGHT_DELAY = 6000; // t+6 sec
82 private static final int LONG_DIM_TIME = 7000; // t+N-5 sec
83
84 // Cached Gservices settings; see updateGservicesValues()
85 private int mShortKeylightDelay = SHORT_KEYLIGHT_DELAY_DEFAULT;
86
87 // flags for setPowerState
88 private static final int SCREEN_ON_BIT = 0x00000001;
89 private static final int SCREEN_BRIGHT_BIT = 0x00000002;
90 private static final int BUTTON_BRIGHT_BIT = 0x00000004;
91 private static final int KEYBOARD_BRIGHT_BIT = 0x00000008;
92 private static final int BATTERY_LOW_BIT = 0x00000010;
93
94 // values for setPowerState
95
96 // SCREEN_OFF == everything off
97 private static final int SCREEN_OFF = 0x00000000;
98
99 // SCREEN_DIM == screen on, screen backlight dim
100 private static final int SCREEN_DIM = SCREEN_ON_BIT;
101
102 // SCREEN_BRIGHT == screen on, screen backlight bright
103 private static final int SCREEN_BRIGHT = SCREEN_ON_BIT | SCREEN_BRIGHT_BIT;
104
105 // SCREEN_BUTTON_BRIGHT == screen on, screen and button backlights bright
106 private static final int SCREEN_BUTTON_BRIGHT = SCREEN_BRIGHT | BUTTON_BRIGHT_BIT;
107
108 // SCREEN_BUTTON_BRIGHT == screen on, screen, button and keyboard backlights bright
109 private static final int ALL_BRIGHT = SCREEN_BUTTON_BRIGHT | KEYBOARD_BRIGHT_BIT;
110
111 // used for noChangeLights in setPowerState()
112 private static final int LIGHTS_MASK = SCREEN_BRIGHT_BIT | BUTTON_BRIGHT_BIT | KEYBOARD_BRIGHT_BIT;
113
114 static final boolean ANIMATE_SCREEN_LIGHTS = true;
115 static final boolean ANIMATE_BUTTON_LIGHTS = false;
116 static final boolean ANIMATE_KEYBOARD_LIGHTS = false;
117
118 static final int ANIM_STEPS = 60/4;
119
120 // These magic numbers are the initial state of the LEDs at boot. Ideally
121 // we should read them from the driver, but our current hardware returns 0
122 // for the initial value. Oops!
123 static final int INITIAL_SCREEN_BRIGHTNESS = 255;
124 static final int INITIAL_BUTTON_BRIGHTNESS = Power.BRIGHTNESS_OFF;
125 static final int INITIAL_KEYBOARD_BRIGHTNESS = Power.BRIGHTNESS_OFF;
126
127 static final int LOG_POWER_SLEEP_REQUESTED = 2724;
128 static final int LOG_POWER_SCREEN_BROADCAST_SEND = 2725;
129 static final int LOG_POWER_SCREEN_BROADCAST_DONE = 2726;
130 static final int LOG_POWER_SCREEN_BROADCAST_STOP = 2727;
131 static final int LOG_POWER_SCREEN_STATE = 2728;
132 static final int LOG_POWER_PARTIAL_WAKE_STATE = 2729;
133
134 private final int MY_UID;
135
136 private boolean mDoneBooting = false;
137 private int mStayOnConditions = 0;
Joe Onorato128e7292009-03-24 18:41:31 -0700138 private int[] mBroadcastQueue = new int[] { -1, -1, -1 };
139 private int[] mBroadcastWhy = new int[3];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800140 private int mPartialCount = 0;
141 private int mPowerState;
142 private boolean mOffBecauseOfUser;
143 private int mUserState;
144 private boolean mKeyboardVisible = false;
145 private boolean mUserActivityAllowed = true;
146 private int mTotalDelaySetting;
147 private int mKeylightDelay;
148 private int mDimDelay;
149 private int mScreenOffDelay;
150 private int mWakeLockState;
151 private long mLastEventTime = 0;
152 private long mScreenOffTime;
153 private volatile WindowManagerPolicy mPolicy;
154 private final LockList mLocks = new LockList();
155 private Intent mScreenOffIntent;
156 private Intent mScreenOnIntent;
The Android Open Source Project10592532009-03-18 17:39:46 -0700157 private HardwareService mHardware;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800158 private Context mContext;
159 private UnsynchronizedWakeLock mBroadcastWakeLock;
160 private UnsynchronizedWakeLock mStayOnWhilePluggedInScreenDimLock;
161 private UnsynchronizedWakeLock mStayOnWhilePluggedInPartialLock;
162 private UnsynchronizedWakeLock mPreventScreenOnPartialLock;
163 private HandlerThread mHandlerThread;
164 private Handler mHandler;
165 private TimeoutTask mTimeoutTask = new TimeoutTask();
166 private LightAnimator mLightAnimator = new LightAnimator();
167 private final BrightnessState mScreenBrightness
The Android Open Source Project10592532009-03-18 17:39:46 -0700168 = new BrightnessState(SCREEN_BRIGHT_BIT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800169 private final BrightnessState mKeyboardBrightness
The Android Open Source Project10592532009-03-18 17:39:46 -0700170 = new BrightnessState(KEYBOARD_BRIGHT_BIT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800171 private final BrightnessState mButtonBrightness
The Android Open Source Project10592532009-03-18 17:39:46 -0700172 = new BrightnessState(BUTTON_BRIGHT_BIT);
Joe Onorato128e7292009-03-24 18:41:31 -0700173 private boolean mStillNeedSleepNotification;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800174 private boolean mIsPowered = false;
175 private IActivityManager mActivityService;
176 private IBatteryStats mBatteryStats;
177 private BatteryService mBatteryService;
178 private boolean mDimScreen = true;
179 private long mNextTimeout;
180 private volatile int mPokey = 0;
181 private volatile boolean mPokeAwakeOnSet = false;
182 private volatile boolean mInitComplete = false;
183 private HashMap<IBinder,PokeLock> mPokeLocks = new HashMap<IBinder,PokeLock>();
184 private long mScreenOnTime;
185 private long mScreenOnStartTime;
186 private boolean mPreventScreenOn;
187 private int mScreenBrightnessOverride = -1;
188
189 // Used when logging number and duration of touch-down cycles
190 private long mTotalTouchDownTime;
191 private long mLastTouchDown;
192 private int mTouchCycles;
193
194 // could be either static or controllable at runtime
195 private static final boolean mSpew = false;
196
197 /*
198 static PrintStream mLog;
199 static {
200 try {
201 mLog = new PrintStream("/data/power.log");
202 }
203 catch (FileNotFoundException e) {
204 android.util.Log.e(TAG, "Life is hard", e);
205 }
206 }
207 static class Log {
208 static void d(String tag, String s) {
209 mLog.println(s);
210 android.util.Log.d(tag, s);
211 }
212 static void i(String tag, String s) {
213 mLog.println(s);
214 android.util.Log.i(tag, s);
215 }
216 static void w(String tag, String s) {
217 mLog.println(s);
218 android.util.Log.w(tag, s);
219 }
220 static void e(String tag, String s) {
221 mLog.println(s);
222 android.util.Log.e(tag, s);
223 }
224 }
225 */
226
227 /**
228 * This class works around a deadlock between the lock in PowerManager.WakeLock
229 * and our synchronizing on mLocks. PowerManager.WakeLock synchronizes on its
230 * mToken object so it can be accessed from any thread, but it calls into here
231 * with its lock held. This class is essentially a reimplementation of
232 * PowerManager.WakeLock, but without that extra synchronized block, because we'll
233 * only call it with our own locks held.
234 */
235 private class UnsynchronizedWakeLock {
236 int mFlags;
237 String mTag;
238 IBinder mToken;
239 int mCount = 0;
240 boolean mRefCounted;
241
242 UnsynchronizedWakeLock(int flags, String tag, boolean refCounted) {
243 mFlags = flags;
244 mTag = tag;
245 mToken = new Binder();
246 mRefCounted = refCounted;
247 }
248
249 public void acquire() {
250 if (!mRefCounted || mCount++ == 0) {
251 long ident = Binder.clearCallingIdentity();
252 try {
253 PowerManagerService.this.acquireWakeLockLocked(mFlags, mToken,
254 MY_UID, mTag);
255 } finally {
256 Binder.restoreCallingIdentity(ident);
257 }
258 }
259 }
260
261 public void release() {
262 if (!mRefCounted || --mCount == 0) {
263 PowerManagerService.this.releaseWakeLockLocked(mToken, false);
264 }
265 if (mCount < 0) {
266 throw new RuntimeException("WakeLock under-locked " + mTag);
267 }
268 }
269
270 public String toString() {
271 return "UnsynchronizedWakeLock(mFlags=0x" + Integer.toHexString(mFlags)
272 + " mCount=" + mCount + ")";
273 }
274 }
275
276 private final class BatteryReceiver extends BroadcastReceiver {
277 @Override
278 public void onReceive(Context context, Intent intent) {
279 synchronized (mLocks) {
280 boolean wasPowered = mIsPowered;
281 mIsPowered = mBatteryService.isPowered();
282
283 if (mIsPowered != wasPowered) {
284 // update mStayOnWhilePluggedIn wake lock
285 updateWakeLockLocked();
286
287 // treat plugging and unplugging the devices as a user activity.
288 // users find it disconcerting when they unplug the device
289 // and it shuts off right away.
290 // temporarily set mUserActivityAllowed to true so this will work
291 // even when the keyguard is on.
292 synchronized (mLocks) {
293 boolean savedActivityAllowed = mUserActivityAllowed;
294 mUserActivityAllowed = true;
295 userActivity(SystemClock.uptimeMillis(), false);
296 mUserActivityAllowed = savedActivityAllowed;
297 }
298 }
299 }
300 }
301 }
302
303 /**
304 * Set the setting that determines whether the device stays on when plugged in.
305 * The argument is a bit string, with each bit specifying a power source that,
306 * when the device is connected to that source, causes the device to stay on.
307 * See {@link android.os.BatteryManager} for the list of power sources that
308 * can be specified. Current values include {@link android.os.BatteryManager#BATTERY_PLUGGED_AC}
309 * and {@link android.os.BatteryManager#BATTERY_PLUGGED_USB}
310 * @param val an {@code int} containing the bits that specify which power sources
311 * should cause the device to stay on.
312 */
313 public void setStayOnSetting(int val) {
314 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SETTINGS, null);
315 Settings.System.putInt(mContext.getContentResolver(),
316 Settings.System.STAY_ON_WHILE_PLUGGED_IN, val);
317 }
318
319 private class SettingsObserver implements Observer {
320 private int getInt(String name) {
321 return mSettings.getValues(name).getAsInteger(Settings.System.VALUE);
322 }
323
324 public void update(Observable o, Object arg) {
325 synchronized (mLocks) {
326 // STAY_ON_WHILE_PLUGGED_IN
327 mStayOnConditions = getInt(STAY_ON_WHILE_PLUGGED_IN);
328 updateWakeLockLocked();
329
330 // SCREEN_OFF_TIMEOUT
331 mTotalDelaySetting = getInt(SCREEN_OFF_TIMEOUT);
332
333 // DIM_SCREEN
334 //mDimScreen = getInt(DIM_SCREEN) != 0;
335
336 // recalculate everything
337 setScreenOffTimeoutsLocked();
338 }
339 }
340 }
341
342 PowerManagerService()
343 {
344 // Hack to get our uid... should have a func for this.
345 long token = Binder.clearCallingIdentity();
346 MY_UID = Binder.getCallingUid();
347 Binder.restoreCallingIdentity(token);
348
349 // XXX remove this when the kernel doesn't timeout wake locks
350 Power.setLastUserActivityTimeout(7*24*3600*1000); // one week
351
352 // assume nothing is on yet
353 mUserState = mPowerState = 0;
354
355 // Add ourself to the Watchdog monitors.
356 Watchdog.getInstance().addMonitor(this);
357 mScreenOnStartTime = SystemClock.elapsedRealtime();
358 }
359
360 private ContentQueryMap mSettings;
361
The Android Open Source Project10592532009-03-18 17:39:46 -0700362 void init(Context context, HardwareService hardware, IActivityManager activity,
363 BatteryService battery) {
364 mHardware = hardware;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800365 mContext = context;
366 mActivityService = activity;
367 mBatteryStats = BatteryStatsService.getService();
368 mBatteryService = battery;
369
370 mHandlerThread = new HandlerThread("PowerManagerService") {
371 @Override
372 protected void onLooperPrepared() {
373 super.onLooperPrepared();
374 initInThread();
375 }
376 };
377 mHandlerThread.start();
378
379 synchronized (mHandlerThread) {
380 while (!mInitComplete) {
381 try {
382 mHandlerThread.wait();
383 } catch (InterruptedException e) {
384 // Ignore
385 }
386 }
387 }
388 }
389
390 void initInThread() {
391 mHandler = new Handler();
392
393 mBroadcastWakeLock = new UnsynchronizedWakeLock(
Joe Onorato128e7292009-03-24 18:41:31 -0700394 PowerManager.PARTIAL_WAKE_LOCK, "sleep_broadcast", true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800395 mStayOnWhilePluggedInScreenDimLock = new UnsynchronizedWakeLock(
396 PowerManager.SCREEN_DIM_WAKE_LOCK, "StayOnWhilePluggedIn Screen Dim", false);
397 mStayOnWhilePluggedInPartialLock = new UnsynchronizedWakeLock(
398 PowerManager.PARTIAL_WAKE_LOCK, "StayOnWhilePluggedIn Partial", false);
399 mPreventScreenOnPartialLock = new UnsynchronizedWakeLock(
400 PowerManager.PARTIAL_WAKE_LOCK, "PreventScreenOn Partial", false);
401
402 mScreenOnIntent = new Intent(Intent.ACTION_SCREEN_ON);
403 mScreenOnIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
404 mScreenOffIntent = new Intent(Intent.ACTION_SCREEN_OFF);
405 mScreenOffIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
406
407 ContentResolver resolver = mContext.getContentResolver();
408 Cursor settingsCursor = resolver.query(Settings.System.CONTENT_URI, null,
409 "(" + Settings.System.NAME + "=?) or ("
410 + Settings.System.NAME + "=?) or ("
411 + Settings.System.NAME + "=?)",
412 new String[]{STAY_ON_WHILE_PLUGGED_IN, SCREEN_OFF_TIMEOUT, DIM_SCREEN},
413 null);
414 mSettings = new ContentQueryMap(settingsCursor, Settings.System.NAME, true, mHandler);
415 SettingsObserver settingsObserver = new SettingsObserver();
416 mSettings.addObserver(settingsObserver);
417
418 // pretend that the settings changed so we will get their initial state
419 settingsObserver.update(mSettings, null);
420
421 // register for the battery changed notifications
422 IntentFilter filter = new IntentFilter();
423 filter.addAction(Intent.ACTION_BATTERY_CHANGED);
424 mContext.registerReceiver(new BatteryReceiver(), filter);
425
426 // Listen for Gservices changes
427 IntentFilter gservicesChangedFilter =
428 new IntentFilter(Settings.Gservices.CHANGED_ACTION);
429 mContext.registerReceiver(new GservicesChangedReceiver(), gservicesChangedFilter);
430 // And explicitly do the initial update of our cached settings
431 updateGservicesValues();
432
433 // turn everything on
434 setPowerState(ALL_BRIGHT);
435
436 synchronized (mHandlerThread) {
437 mInitComplete = true;
438 mHandlerThread.notifyAll();
439 }
440 }
441
442 private class WakeLock implements IBinder.DeathRecipient
443 {
444 WakeLock(int f, IBinder b, String t, int u) {
445 super();
446 flags = f;
447 binder = b;
448 tag = t;
449 uid = u == MY_UID ? Process.SYSTEM_UID : u;
450 if (u != MY_UID || (
451 !"KEEP_SCREEN_ON_FLAG".equals(tag)
452 && !"KeyInputQueue".equals(tag))) {
453 monitorType = (f & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK
454 ? BatteryStats.WAKE_TYPE_PARTIAL
455 : BatteryStats.WAKE_TYPE_FULL;
456 } else {
457 monitorType = -1;
458 }
459 try {
460 b.linkToDeath(this, 0);
461 } catch (RemoteException e) {
462 binderDied();
463 }
464 }
465 public void binderDied() {
466 synchronized (mLocks) {
467 releaseWakeLockLocked(this.binder, true);
468 }
469 }
470 final int flags;
471 final IBinder binder;
472 final String tag;
473 final int uid;
474 final int monitorType;
475 boolean activated = true;
476 int minState;
477 }
478
479 private void updateWakeLockLocked() {
480 if (mStayOnConditions != 0 && mBatteryService.isPowered(mStayOnConditions)) {
481 // keep the device on if we're plugged in and mStayOnWhilePluggedIn is set.
482 mStayOnWhilePluggedInScreenDimLock.acquire();
483 mStayOnWhilePluggedInPartialLock.acquire();
484 } else {
485 mStayOnWhilePluggedInScreenDimLock.release();
486 mStayOnWhilePluggedInPartialLock.release();
487 }
488 }
489
490 private boolean isScreenLock(int flags)
491 {
492 int n = flags & LOCK_MASK;
493 return n == PowerManager.FULL_WAKE_LOCK
494 || n == PowerManager.SCREEN_BRIGHT_WAKE_LOCK
495 || n == PowerManager.SCREEN_DIM_WAKE_LOCK;
496 }
497
498 public void acquireWakeLock(int flags, IBinder lock, String tag) {
499 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
500 int uid = Binder.getCallingUid();
501 long ident = Binder.clearCallingIdentity();
502 try {
503 synchronized (mLocks) {
504 acquireWakeLockLocked(flags, lock, uid, tag);
505 }
506 } finally {
507 Binder.restoreCallingIdentity(ident);
508 }
509 }
510
511 public void acquireWakeLockLocked(int flags, IBinder lock, int uid, String tag) {
512 int acquireUid = -1;
513 String acquireName = null;
514 int acquireType = -1;
515
516 if (mSpew) {
517 Log.d(TAG, "acquireWakeLock flags=0x" + Integer.toHexString(flags) + " tag=" + tag);
518 }
519
520 int index = mLocks.getIndex(lock);
521 WakeLock wl;
522 boolean newlock;
523 if (index < 0) {
524 wl = new WakeLock(flags, lock, tag, uid);
525 switch (wl.flags & LOCK_MASK)
526 {
527 case PowerManager.FULL_WAKE_LOCK:
528 wl.minState = (mKeyboardVisible ? ALL_BRIGHT : SCREEN_BUTTON_BRIGHT);
529 break;
530 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
531 wl.minState = SCREEN_BRIGHT;
532 break;
533 case PowerManager.SCREEN_DIM_WAKE_LOCK:
534 wl.minState = SCREEN_DIM;
535 break;
536 case PowerManager.PARTIAL_WAKE_LOCK:
537 break;
538 default:
539 // just log and bail. we're in the server, so don't
540 // throw an exception.
541 Log.e(TAG, "bad wakelock type for lock '" + tag + "' "
542 + " flags=" + flags);
543 return;
544 }
545 mLocks.addLock(wl);
546 newlock = true;
547 } else {
548 wl = mLocks.get(index);
549 newlock = false;
550 }
551 if (isScreenLock(flags)) {
552 // if this causes a wakeup, we reactivate all of the locks and
553 // set it to whatever they want. otherwise, we modulate that
554 // by the current state so we never turn it more on than
555 // it already is.
556 if ((wl.flags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) {
557 reactivateWakeLocksLocked();
558 if (mSpew) {
559 Log.d(TAG, "wakeup here mUserState=0x" + Integer.toHexString(mUserState)
560 + " mLocks.gatherState()=0x"
561 + Integer.toHexString(mLocks.gatherState())
562 + " mWakeLockState=0x" + Integer.toHexString(mWakeLockState));
563 }
564 mWakeLockState = mLocks.gatherState();
565 } else {
566 if (mSpew) {
567 Log.d(TAG, "here mUserState=0x" + Integer.toHexString(mUserState)
568 + " mLocks.gatherState()=0x"
569 + Integer.toHexString(mLocks.gatherState())
570 + " mWakeLockState=0x" + Integer.toHexString(mWakeLockState));
571 }
572 mWakeLockState = (mUserState | mWakeLockState) & mLocks.gatherState();
573 }
574 setPowerState(mWakeLockState | mUserState);
575 }
576 else if ((flags & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK) {
577 if (newlock) {
578 mPartialCount++;
579 if (mPartialCount == 1) {
580 if (LOG_PARTIAL_WL) EventLog.writeEvent(LOG_POWER_PARTIAL_WAKE_STATE, 1, tag);
581 }
582 }
583 Power.acquireWakeLock(Power.PARTIAL_WAKE_LOCK,PARTIAL_NAME);
584 }
585 if (newlock) {
586 acquireUid = wl.uid;
587 acquireName = wl.tag;
588 acquireType = wl.monitorType;
589 }
590
591 if (acquireType >= 0) {
592 try {
593 mBatteryStats.noteStartWakelock(acquireUid, acquireName, acquireType);
594 } catch (RemoteException e) {
595 // Ignore
596 }
597 }
598 }
599
600 public void releaseWakeLock(IBinder lock) {
601 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
602
603 synchronized (mLocks) {
604 releaseWakeLockLocked(lock, false);
605 }
606 }
607
608 private void releaseWakeLockLocked(IBinder lock, boolean death) {
609 int releaseUid;
610 String releaseName;
611 int releaseType;
612
613 WakeLock wl = mLocks.removeLock(lock);
614 if (wl == null) {
615 return;
616 }
617
618 if (mSpew) {
619 Log.d(TAG, "releaseWakeLock flags=0x"
620 + Integer.toHexString(wl.flags) + " tag=" + wl.tag);
621 }
622
623 if (isScreenLock(wl.flags)) {
624 mWakeLockState = mLocks.gatherState();
625 // goes in the middle to reduce flicker
626 if ((wl.flags & PowerManager.ON_AFTER_RELEASE) != 0) {
627 userActivity(SystemClock.uptimeMillis(), false);
628 }
629 setPowerState(mWakeLockState | mUserState);
630 }
631 else if ((wl.flags & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK) {
632 mPartialCount--;
633 if (mPartialCount == 0) {
634 if (LOG_PARTIAL_WL) EventLog.writeEvent(LOG_POWER_PARTIAL_WAKE_STATE, 0, wl.tag);
635 Power.releaseWakeLock(PARTIAL_NAME);
636 }
637 }
638 // Unlink the lock from the binder.
639 wl.binder.unlinkToDeath(wl, 0);
640 releaseUid = wl.uid;
641 releaseName = wl.tag;
642 releaseType = wl.monitorType;
643
644 if (releaseType >= 0) {
645 long origId = Binder.clearCallingIdentity();
646 try {
647 mBatteryStats.noteStopWakelock(releaseUid, releaseName, releaseType);
648 } catch (RemoteException e) {
649 // Ignore
650 } finally {
651 Binder.restoreCallingIdentity(origId);
652 }
653 }
654 }
655
656 private void reactivateWakeLocksLocked()
657 {
658 int N = mLocks.size();
659 for (int i=0; i<N; i++) {
660 WakeLock wl = mLocks.get(i);
661 if (isScreenLock(wl.flags)) {
662 mLocks.get(i).activated = true;
663 }
664 }
665 }
666
667 private class PokeLock implements IBinder.DeathRecipient
668 {
669 PokeLock(int p, IBinder b, String t) {
670 super();
671 this.pokey = p;
672 this.binder = b;
673 this.tag = t;
674 try {
675 b.linkToDeath(this, 0);
676 } catch (RemoteException e) {
677 binderDied();
678 }
679 }
680 public void binderDied() {
681 setPokeLock(0, this.binder, this.tag);
682 }
683 int pokey;
684 IBinder binder;
685 String tag;
686 boolean awakeOnSet;
687 }
688
689 public void setPokeLock(int pokey, IBinder token, String tag) {
690 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
691 if (token == null) {
692 Log.e(TAG, "setPokeLock got null token for tag='" + tag + "'");
693 return;
694 }
695
696 if ((pokey & POKE_LOCK_TIMEOUT_MASK) == POKE_LOCK_TIMEOUT_MASK) {
697 throw new IllegalArgumentException("setPokeLock can't have both POKE_LOCK_SHORT_TIMEOUT"
698 + " and POKE_LOCK_MEDIUM_TIMEOUT");
699 }
700
701 synchronized (mLocks) {
702 if (pokey != 0) {
703 PokeLock p = mPokeLocks.get(token);
704 int oldPokey = 0;
705 if (p != null) {
706 oldPokey = p.pokey;
707 p.pokey = pokey;
708 } else {
709 p = new PokeLock(pokey, token, tag);
710 mPokeLocks.put(token, p);
711 }
712 int oldTimeout = oldPokey & POKE_LOCK_TIMEOUT_MASK;
713 int newTimeout = pokey & POKE_LOCK_TIMEOUT_MASK;
714 if (((mPowerState & SCREEN_ON_BIT) == 0) && (oldTimeout != newTimeout)) {
715 p.awakeOnSet = true;
716 }
717 } else {
718 mPokeLocks.remove(token);
719 }
720
721 int oldPokey = mPokey;
722 int cumulative = 0;
723 boolean oldAwakeOnSet = mPokeAwakeOnSet;
724 boolean awakeOnSet = false;
725 for (PokeLock p: mPokeLocks.values()) {
726 cumulative |= p.pokey;
727 if (p.awakeOnSet) {
728 awakeOnSet = true;
729 }
730 }
731 mPokey = cumulative;
732 mPokeAwakeOnSet = awakeOnSet;
733
734 int oldCumulativeTimeout = oldPokey & POKE_LOCK_TIMEOUT_MASK;
735 int newCumulativeTimeout = pokey & POKE_LOCK_TIMEOUT_MASK;
736
737 if (oldCumulativeTimeout != newCumulativeTimeout) {
738 setScreenOffTimeoutsLocked();
739 // reset the countdown timer, but use the existing nextState so it doesn't
740 // change anything
741 setTimeoutLocked(SystemClock.uptimeMillis(), mTimeoutTask.nextState);
742 }
743 }
744 }
745
746 private static String lockType(int type)
747 {
748 switch (type)
749 {
750 case PowerManager.FULL_WAKE_LOCK:
751 return "FULL_WAKE_LOCK ";
752 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
753 return "SCREEN_BRIGHT_WAKE_LOCK";
754 case PowerManager.SCREEN_DIM_WAKE_LOCK:
755 return "SCREEN_DIM_WAKE_LOCK ";
756 case PowerManager.PARTIAL_WAKE_LOCK:
757 return "PARTIAL_WAKE_LOCK ";
758 default:
759 return "??? ";
760 }
761 }
762
763 private static String dumpPowerState(int state) {
764 return (((state & KEYBOARD_BRIGHT_BIT) != 0)
765 ? "KEYBOARD_BRIGHT_BIT " : "")
766 + (((state & SCREEN_BRIGHT_BIT) != 0)
767 ? "SCREEN_BRIGHT_BIT " : "")
768 + (((state & SCREEN_ON_BIT) != 0)
769 ? "SCREEN_ON_BIT " : "")
770 + (((state & BATTERY_LOW_BIT) != 0)
771 ? "BATTERY_LOW_BIT " : "");
772 }
773
774 @Override
775 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
776 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
777 != PackageManager.PERMISSION_GRANTED) {
778 pw.println("Permission Denial: can't dump PowerManager from from pid="
779 + Binder.getCallingPid()
780 + ", uid=" + Binder.getCallingUid());
781 return;
782 }
783
784 long now = SystemClock.uptimeMillis();
785
786 pw.println("Power Manager State:");
787 pw.println(" mIsPowered=" + mIsPowered
788 + " mPowerState=" + mPowerState
789 + " mScreenOffTime=" + (SystemClock.elapsedRealtime()-mScreenOffTime)
790 + " ms");
791 pw.println(" mPartialCount=" + mPartialCount);
792 pw.println(" mWakeLockState=" + dumpPowerState(mWakeLockState));
793 pw.println(" mUserState=" + dumpPowerState(mUserState));
794 pw.println(" mPowerState=" + dumpPowerState(mPowerState));
795 pw.println(" mLocks.gather=" + dumpPowerState(mLocks.gatherState()));
796 pw.println(" mNextTimeout=" + mNextTimeout + " now=" + now
797 + " " + ((mNextTimeout-now)/1000) + "s from now");
798 pw.println(" mDimScreen=" + mDimScreen
799 + " mStayOnConditions=" + mStayOnConditions);
800 pw.println(" mOffBecauseOfUser=" + mOffBecauseOfUser
801 + " mUserState=" + mUserState);
Joe Onorato128e7292009-03-24 18:41:31 -0700802 pw.println(" mBroadcastQueue={" + mBroadcastQueue[0] + ',' + mBroadcastQueue[1]
803 + ',' + mBroadcastQueue[2] + "}");
804 pw.println(" mBroadcastWhy={" + mBroadcastWhy[0] + ',' + mBroadcastWhy[1]
805 + ',' + mBroadcastWhy[2] + "}");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800806 pw.println(" mPokey=" + mPokey + " mPokeAwakeonSet=" + mPokeAwakeOnSet);
807 pw.println(" mKeyboardVisible=" + mKeyboardVisible
808 + " mUserActivityAllowed=" + mUserActivityAllowed);
809 pw.println(" mKeylightDelay=" + mKeylightDelay + " mDimDelay=" + mDimDelay
810 + " mScreenOffDelay=" + mScreenOffDelay);
811 pw.println(" mPreventScreenOn=" + mPreventScreenOn
812 + " mScreenBrightnessOverride=" + mScreenBrightnessOverride);
813 pw.println(" mTotalDelaySetting=" + mTotalDelaySetting);
814 pw.println(" mBroadcastWakeLock=" + mBroadcastWakeLock);
815 pw.println(" mStayOnWhilePluggedInScreenDimLock=" + mStayOnWhilePluggedInScreenDimLock);
816 pw.println(" mStayOnWhilePluggedInPartialLock=" + mStayOnWhilePluggedInPartialLock);
817 pw.println(" mPreventScreenOnPartialLock=" + mPreventScreenOnPartialLock);
818 mScreenBrightness.dump(pw, " mScreenBrightness: ");
819 mKeyboardBrightness.dump(pw, " mKeyboardBrightness: ");
820 mButtonBrightness.dump(pw, " mButtonBrightness: ");
821
822 int N = mLocks.size();
823 pw.println();
824 pw.println("mLocks.size=" + N + ":");
825 for (int i=0; i<N; i++) {
826 WakeLock wl = mLocks.get(i);
827 String type = lockType(wl.flags & LOCK_MASK);
828 String acquireCausesWakeup = "";
829 if ((wl.flags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) {
830 acquireCausesWakeup = "ACQUIRE_CAUSES_WAKEUP ";
831 }
832 String activated = "";
833 if (wl.activated) {
834 activated = " activated";
835 }
836 pw.println(" " + type + " '" + wl.tag + "'" + acquireCausesWakeup
837 + activated + " (minState=" + wl.minState + ")");
838 }
839
840 pw.println();
841 pw.println("mPokeLocks.size=" + mPokeLocks.size() + ":");
842 for (PokeLock p: mPokeLocks.values()) {
843 pw.println(" poke lock '" + p.tag + "':"
844 + ((p.pokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0
845 ? " POKE_LOCK_IGNORE_CHEEK_EVENTS" : "")
846 + ((p.pokey & POKE_LOCK_SHORT_TIMEOUT) != 0
847 ? " POKE_LOCK_SHORT_TIMEOUT" : "")
848 + ((p.pokey & POKE_LOCK_MEDIUM_TIMEOUT) != 0
849 ? " POKE_LOCK_MEDIUM_TIMEOUT" : ""));
850 }
851
852 pw.println();
853 }
854
855 private void setTimeoutLocked(long now, int nextState)
856 {
857 if (mDoneBooting) {
858 mHandler.removeCallbacks(mTimeoutTask);
859 mTimeoutTask.nextState = nextState;
860 long when = now;
861 switch (nextState)
862 {
863 case SCREEN_BRIGHT:
864 when += mKeylightDelay;
865 break;
866 case SCREEN_DIM:
867 if (mDimDelay >= 0) {
868 when += mDimDelay;
869 break;
870 } else {
871 Log.w(TAG, "mDimDelay=" + mDimDelay + " while trying to dim");
872 }
873 case SCREEN_OFF:
874 synchronized (mLocks) {
875 when += mScreenOffDelay;
876 }
877 break;
878 }
879 if (mSpew) {
880 Log.d(TAG, "setTimeoutLocked now=" + now + " nextState=" + nextState
881 + " when=" + when);
882 }
883 mHandler.postAtTime(mTimeoutTask, when);
884 mNextTimeout = when; // for debugging
885 }
886 }
887
888 private void cancelTimerLocked()
889 {
890 mHandler.removeCallbacks(mTimeoutTask);
891 mTimeoutTask.nextState = -1;
892 }
893
894 private class TimeoutTask implements Runnable
895 {
896 int nextState; // access should be synchronized on mLocks
897 public void run()
898 {
899 synchronized (mLocks) {
900 if (mSpew) {
901 Log.d(TAG, "user activity timeout timed out nextState=" + this.nextState);
902 }
903
904 if (nextState == -1) {
905 return;
906 }
907
908 mUserState = this.nextState;
909 setPowerState(this.nextState | mWakeLockState);
910
911 long now = SystemClock.uptimeMillis();
912
913 switch (this.nextState)
914 {
915 case SCREEN_BRIGHT:
916 if (mDimDelay >= 0) {
917 setTimeoutLocked(now, SCREEN_DIM);
918 break;
919 }
920 case SCREEN_DIM:
921 setTimeoutLocked(now, SCREEN_OFF);
922 break;
923 }
924 }
925 }
926 }
927
928 private void sendNotificationLocked(boolean on, int why)
929 {
Joe Onorato128e7292009-03-24 18:41:31 -0700930 // Add to the queue.
931 int index = 0;
932 while (mBroadcastQueue[index] != -1) {
933 index++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800934 }
Joe Onorato128e7292009-03-24 18:41:31 -0700935 mBroadcastQueue[index] = on ? 1 : 0;
936 mBroadcastWhy[index] = why;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800937
Joe Onorato128e7292009-03-24 18:41:31 -0700938 // If we added it position 2, then there is a pair that can be stripped.
939 // If we added it position 1 and we're turning the screen off, we can strip
940 // the pair and do nothing, because the screen is already off, and therefore
941 // keyguard has already been enabled.
942 // However, if we added it at position 1 and we're turning it on, then position
943 // 0 was to turn it off, and we can't strip that, because keyguard needs to come
944 // on, so have to run the queue then.
945 if (index == 2) {
946 // Also, while we're collapsing them, if it's going to be an "off," and one
947 // is off because of user, then use that, regardless of whether it's the first
948 // or second one.
949 if (!on && why == WindowManagerPolicy.OFF_BECAUSE_OF_USER) {
950 mBroadcastWhy[0] = WindowManagerPolicy.OFF_BECAUSE_OF_USER;
951 }
952 mBroadcastQueue[0] = on ? 1 : 0;
953 mBroadcastQueue[1] = -1;
954 mBroadcastQueue[2] = -1;
955 index = 0;
956 }
957 if (index == 1 && !on) {
958 mBroadcastQueue[0] = -1;
959 mBroadcastQueue[1] = -1;
960 index = -1;
961 // The wake lock was being held, but we're not actually going to do any
962 // broadcasts, so release the wake lock.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800963 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_STOP, 1, mBroadcastWakeLock.mCount);
964 mBroadcastWakeLock.release();
Joe Onorato128e7292009-03-24 18:41:31 -0700965 }
966
967 // Now send the message.
968 if (index >= 0) {
969 // Acquire the broadcast wake lock before changing the power
970 // state. It will be release after the broadcast is sent.
971 // We always increment the ref count for each notification in the queue
972 // and always decrement when that notification is handled.
973 mBroadcastWakeLock.acquire();
974 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_SEND, mBroadcastWakeLock.mCount);
975 mHandler.post(mNotificationTask);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800976 }
977 }
978
979 private Runnable mNotificationTask = new Runnable()
980 {
981 public void run()
982 {
Joe Onorato128e7292009-03-24 18:41:31 -0700983 while (true) {
984 int value;
985 int why;
986 WindowManagerPolicy policy;
987 synchronized (mLocks) {
988 value = mBroadcastQueue[0];
989 why = mBroadcastWhy[0];
990 for (int i=0; i<2; i++) {
991 mBroadcastQueue[i] = mBroadcastQueue[i+1];
992 mBroadcastWhy[i] = mBroadcastWhy[i+1];
993 }
994 policy = getPolicyLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800995 }
Joe Onorato128e7292009-03-24 18:41:31 -0700996 if (value == 1) {
997 mScreenOnStart = SystemClock.uptimeMillis();
998
999 policy.screenTurnedOn();
1000 try {
1001 ActivityManagerNative.getDefault().wakingUp();
1002 } catch (RemoteException e) {
1003 // ignore it
1004 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001005
Joe Onorato128e7292009-03-24 18:41:31 -07001006 if (mSpew) {
1007 Log.d(TAG, "mBroadcastWakeLock=" + mBroadcastWakeLock);
1008 }
1009 if (mContext != null && ActivityManagerNative.isSystemReady()) {
1010 mContext.sendOrderedBroadcast(mScreenOnIntent, null,
1011 mScreenOnBroadcastDone, mHandler, 0, null, null);
1012 } else {
1013 synchronized (mLocks) {
1014 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_STOP, 2,
1015 mBroadcastWakeLock.mCount);
1016 mBroadcastWakeLock.release();
1017 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001018 }
1019 }
Joe Onorato128e7292009-03-24 18:41:31 -07001020 else if (value == 0) {
1021 mScreenOffStart = SystemClock.uptimeMillis();
1022
1023 policy.screenTurnedOff(why);
1024 try {
1025 ActivityManagerNative.getDefault().goingToSleep();
1026 } catch (RemoteException e) {
1027 // ignore it.
1028 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001029
Joe Onorato128e7292009-03-24 18:41:31 -07001030 if (mContext != null && ActivityManagerNative.isSystemReady()) {
1031 mContext.sendOrderedBroadcast(mScreenOffIntent, null,
1032 mScreenOffBroadcastDone, mHandler, 0, null, null);
1033 } else {
1034 synchronized (mLocks) {
1035 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_STOP, 3,
1036 mBroadcastWakeLock.mCount);
1037 mBroadcastWakeLock.release();
1038 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001039 }
1040 }
Joe Onorato128e7292009-03-24 18:41:31 -07001041 else {
1042 // If we're in this case, then this handler is running for a previous
1043 // paired transaction. mBroadcastWakeLock will already have been released.
1044 break;
1045 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001046 }
1047 }
1048 };
1049
1050 long mScreenOnStart;
1051 private BroadcastReceiver mScreenOnBroadcastDone = new BroadcastReceiver() {
1052 public void onReceive(Context context, Intent intent) {
1053 synchronized (mLocks) {
1054 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_DONE, 1,
1055 SystemClock.uptimeMillis() - mScreenOnStart, mBroadcastWakeLock.mCount);
1056 mBroadcastWakeLock.release();
1057 }
1058 }
1059 };
1060
1061 long mScreenOffStart;
1062 private BroadcastReceiver mScreenOffBroadcastDone = new BroadcastReceiver() {
1063 public void onReceive(Context context, Intent intent) {
1064 synchronized (mLocks) {
1065 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_DONE, 0,
1066 SystemClock.uptimeMillis() - mScreenOffStart, mBroadcastWakeLock.mCount);
1067 mBroadcastWakeLock.release();
1068 }
1069 }
1070 };
1071
1072 void logPointerUpEvent() {
1073 if (LOG_TOUCH_DOWNS) {
1074 mTotalTouchDownTime += SystemClock.elapsedRealtime() - mLastTouchDown;
1075 mLastTouchDown = 0;
1076 }
1077 }
1078
1079 void logPointerDownEvent() {
1080 if (LOG_TOUCH_DOWNS) {
1081 // If we are not already timing a down/up sequence
1082 if (mLastTouchDown == 0) {
1083 mLastTouchDown = SystemClock.elapsedRealtime();
1084 mTouchCycles++;
1085 }
1086 }
1087 }
1088
1089 /**
1090 * Prevents the screen from turning on even if it *should* turn on due
1091 * to a subsequent full wake lock being acquired.
1092 * <p>
1093 * This is a temporary hack that allows an activity to "cover up" any
1094 * display glitches that happen during the activity's startup
1095 * sequence. (Specifically, this API was added to work around a
1096 * cosmetic bug in the "incoming call" sequence, where the lock screen
1097 * would flicker briefly before the incoming call UI became visible.)
1098 * TODO: There ought to be a more elegant way of doing this,
1099 * probably by having the PowerManager and ActivityManager
1100 * work together to let apps specify that the screen on/off
1101 * state should be synchronized with the Activity lifecycle.
1102 * <p>
1103 * Note that calling preventScreenOn(true) will NOT turn the screen
1104 * off if it's currently on. (This API only affects *future*
1105 * acquisitions of full wake locks.)
1106 * But calling preventScreenOn(false) WILL turn the screen on if
1107 * it's currently off because of a prior preventScreenOn(true) call.
1108 * <p>
1109 * Any call to preventScreenOn(true) MUST be followed promptly by a call
1110 * to preventScreenOn(false). In fact, if the preventScreenOn(false)
1111 * call doesn't occur within 5 seconds, we'll turn the screen back on
1112 * ourselves (and log a warning about it); this prevents a buggy app
1113 * from disabling the screen forever.)
1114 * <p>
1115 * TODO: this feature should really be controlled by a new type of poke
1116 * lock (rather than an IPowerManager call).
1117 */
1118 public void preventScreenOn(boolean prevent) {
1119 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1120
1121 synchronized (mLocks) {
1122 if (prevent) {
1123 // First of all, grab a partial wake lock to
1124 // make sure the CPU stays on during the entire
1125 // preventScreenOn(true) -> preventScreenOn(false) sequence.
1126 mPreventScreenOnPartialLock.acquire();
1127
1128 // Post a forceReenableScreen() call (for 5 seconds in the
1129 // future) to make sure the matching preventScreenOn(false) call
1130 // has happened by then.
1131 mHandler.removeCallbacks(mForceReenableScreenTask);
1132 mHandler.postDelayed(mForceReenableScreenTask, 5000);
1133
1134 // Finally, set the flag that prevents the screen from turning on.
1135 // (Below, in setPowerState(), we'll check mPreventScreenOn and
1136 // we *won't* call Power.setScreenState(true) if it's set.)
1137 mPreventScreenOn = true;
1138 } else {
1139 // (Re)enable the screen.
1140 mPreventScreenOn = false;
1141
1142 // We're "undoing" a the prior preventScreenOn(true) call, so we
1143 // no longer need the 5-second safeguard.
1144 mHandler.removeCallbacks(mForceReenableScreenTask);
1145
1146 // Forcibly turn on the screen if it's supposed to be on. (This
1147 // handles the case where the screen is currently off because of
1148 // a prior preventScreenOn(true) call.)
1149 if ((mPowerState & SCREEN_ON_BIT) != 0) {
1150 if (mSpew) {
1151 Log.d(TAG,
1152 "preventScreenOn: turning on after a prior preventScreenOn(true)!");
1153 }
1154 int err = Power.setScreenState(true);
1155 if (err != 0) {
1156 Log.w(TAG, "preventScreenOn: error from Power.setScreenState(): " + err);
1157 }
1158 }
1159
1160 // Release the partial wake lock that we held during the
1161 // preventScreenOn(true) -> preventScreenOn(false) sequence.
1162 mPreventScreenOnPartialLock.release();
1163 }
1164 }
1165 }
1166
1167 public void setScreenBrightnessOverride(int brightness) {
1168 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1169
1170 synchronized (mLocks) {
1171 if (mScreenBrightnessOverride != brightness) {
1172 mScreenBrightnessOverride = brightness;
1173 updateLightsLocked(mPowerState, SCREEN_ON_BIT);
1174 }
1175 }
1176 }
1177
1178 /**
1179 * Sanity-check that gets called 5 seconds after any call to
1180 * preventScreenOn(true). This ensures that the original call
1181 * is followed promptly by a call to preventScreenOn(false).
1182 */
1183 private void forceReenableScreen() {
1184 // We shouldn't get here at all if mPreventScreenOn is false, since
1185 // we should have already removed any existing
1186 // mForceReenableScreenTask messages...
1187 if (!mPreventScreenOn) {
1188 Log.w(TAG, "forceReenableScreen: mPreventScreenOn is false, nothing to do");
1189 return;
1190 }
1191
1192 // Uh oh. It's been 5 seconds since a call to
1193 // preventScreenOn(true) and we haven't re-enabled the screen yet.
1194 // This means the app that called preventScreenOn(true) is either
1195 // slow (i.e. it took more than 5 seconds to call preventScreenOn(false)),
1196 // or buggy (i.e. it forgot to call preventScreenOn(false), or
1197 // crashed before doing so.)
1198
1199 // Log a warning, and forcibly turn the screen back on.
1200 Log.w(TAG, "App called preventScreenOn(true) but didn't promptly reenable the screen! "
1201 + "Forcing the screen back on...");
1202 preventScreenOn(false);
1203 }
1204
1205 private Runnable mForceReenableScreenTask = new Runnable() {
1206 public void run() {
1207 forceReenableScreen();
1208 }
1209 };
1210
1211 private void setPowerState(int state)
1212 {
1213 setPowerState(state, false, false);
1214 }
1215
1216 private void setPowerState(int newState, boolean noChangeLights, boolean becauseOfUser)
1217 {
1218 synchronized (mLocks) {
1219 int err;
1220
1221 if (mSpew) {
1222 Log.d(TAG, "setPowerState: mPowerState=0x" + Integer.toHexString(mPowerState)
1223 + " newState=0x" + Integer.toHexString(newState)
1224 + " noChangeLights=" + noChangeLights);
1225 }
1226
1227 if (noChangeLights) {
1228 newState = (newState & ~LIGHTS_MASK) | (mPowerState & LIGHTS_MASK);
1229 }
1230
1231 if (batteryIsLow()) {
1232 newState |= BATTERY_LOW_BIT;
1233 } else {
1234 newState &= ~BATTERY_LOW_BIT;
1235 }
1236 if (newState == mPowerState) {
1237 return;
1238 }
1239
1240 if (!mDoneBooting) {
1241 newState |= ALL_BRIGHT;
1242 }
1243
1244 boolean oldScreenOn = (mPowerState & SCREEN_ON_BIT) != 0;
1245 boolean newScreenOn = (newState & SCREEN_ON_BIT) != 0;
1246
1247 if (mSpew) {
1248 Log.d(TAG, "setPowerState: mPowerState=" + mPowerState
1249 + " newState=" + newState + " noChangeLights=" + noChangeLights);
1250 Log.d(TAG, " oldKeyboardBright=" + ((mPowerState & KEYBOARD_BRIGHT_BIT) != 0)
1251 + " newKeyboardBright=" + ((newState & KEYBOARD_BRIGHT_BIT) != 0));
1252 Log.d(TAG, " oldScreenBright=" + ((mPowerState & SCREEN_BRIGHT_BIT) != 0)
1253 + " newScreenBright=" + ((newState & SCREEN_BRIGHT_BIT) != 0));
1254 Log.d(TAG, " oldButtonBright=" + ((mPowerState & BUTTON_BRIGHT_BIT) != 0)
1255 + " newButtonBright=" + ((newState & BUTTON_BRIGHT_BIT) != 0));
1256 Log.d(TAG, " oldScreenOn=" + oldScreenOn
1257 + " newScreenOn=" + newScreenOn);
1258 Log.d(TAG, " oldBatteryLow=" + ((mPowerState & BATTERY_LOW_BIT) != 0)
1259 + " newBatteryLow=" + ((newState & BATTERY_LOW_BIT) != 0));
1260 }
1261
1262 if (mPowerState != newState) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001263 updateLightsLocked(newState, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001264 mPowerState = (mPowerState & ~LIGHTS_MASK) | (newState & LIGHTS_MASK);
1265 }
1266
1267 if (oldScreenOn != newScreenOn) {
1268 if (newScreenOn) {
Joe Onorato128e7292009-03-24 18:41:31 -07001269 // When the user presses the power button, we need to always send out the
1270 // notification that it's going to sleep so the keyguard goes on. But
1271 // we can't do that until the screen fades out, so we don't show the keyguard
1272 // too early.
1273 if (mStillNeedSleepNotification) {
1274 sendNotificationLocked(false, WindowManagerPolicy.OFF_BECAUSE_OF_USER);
1275 }
1276
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001277 // Turn on the screen UNLESS there was a prior
1278 // preventScreenOn(true) request. (Note that the lifetime
1279 // of a single preventScreenOn() request is limited to 5
1280 // seconds to prevent a buggy app from disabling the
1281 // screen forever; see forceReenableScreen().)
1282 boolean reallyTurnScreenOn = true;
1283 if (mSpew) {
1284 Log.d(TAG, "- turning screen on... mPreventScreenOn = "
1285 + mPreventScreenOn);
1286 }
1287
1288 if (mPreventScreenOn) {
1289 if (mSpew) {
1290 Log.d(TAG, "- PREVENTING screen from really turning on!");
1291 }
1292 reallyTurnScreenOn = false;
1293 }
1294 if (reallyTurnScreenOn) {
1295 err = Power.setScreenState(true);
1296 long identity = Binder.clearCallingIdentity();
1297 try {
1298 mBatteryStats.noteScreenOn();
1299 } catch (RemoteException e) {
1300 Log.w(TAG, "RemoteException calling noteScreenOn on BatteryStatsService", e);
1301 } finally {
1302 Binder.restoreCallingIdentity(identity);
1303 }
1304 } else {
1305 Power.setScreenState(false);
1306 // But continue as if we really did turn the screen on...
1307 err = 0;
1308 }
1309
1310 mScreenOnStartTime = SystemClock.elapsedRealtime();
1311 mLastTouchDown = 0;
1312 mTotalTouchDownTime = 0;
1313 mTouchCycles = 0;
1314 EventLog.writeEvent(LOG_POWER_SCREEN_STATE, 1, becauseOfUser ? 1 : 0,
1315 mTotalTouchDownTime, mTouchCycles);
1316 if (err == 0) {
1317 mPowerState |= SCREEN_ON_BIT;
1318 sendNotificationLocked(true, -1);
1319 }
1320 } else {
1321 mScreenOffTime = SystemClock.elapsedRealtime();
1322 long identity = Binder.clearCallingIdentity();
1323 try {
1324 mBatteryStats.noteScreenOff();
1325 } catch (RemoteException e) {
1326 Log.w(TAG, "RemoteException calling noteScreenOff on BatteryStatsService", e);
1327 } finally {
1328 Binder.restoreCallingIdentity(identity);
1329 }
1330 mPowerState &= ~SCREEN_ON_BIT;
1331 if (!mScreenBrightness.animating) {
Joe Onorato128e7292009-03-24 18:41:31 -07001332 err = screenOffFinishedAnimatingLocked(becauseOfUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001333 } else {
1334 mOffBecauseOfUser = becauseOfUser;
1335 err = 0;
1336 mLastTouchDown = 0;
1337 }
1338 }
1339 }
1340 }
1341 }
1342
Joe Onorato128e7292009-03-24 18:41:31 -07001343 private int screenOffFinishedAnimatingLocked(boolean becauseOfUser) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001344 // I don't think we need to check the current state here because all of these
1345 // Power.setScreenState and sendNotificationLocked can both handle being
1346 // called multiple times in the same state. -joeo
1347 EventLog.writeEvent(LOG_POWER_SCREEN_STATE, 0, becauseOfUser ? 1 : 0,
1348 mTotalTouchDownTime, mTouchCycles);
1349 mLastTouchDown = 0;
1350 int err = Power.setScreenState(false);
1351 if (mScreenOnStartTime != 0) {
1352 mScreenOnTime += SystemClock.elapsedRealtime() - mScreenOnStartTime;
1353 mScreenOnStartTime = 0;
1354 }
1355 if (err == 0) {
1356 int why = becauseOfUser
1357 ? WindowManagerPolicy.OFF_BECAUSE_OF_USER
1358 : WindowManagerPolicy.OFF_BECAUSE_OF_TIMEOUT;
1359 sendNotificationLocked(false, why);
1360 }
1361 return err;
1362 }
1363
1364 private boolean batteryIsLow() {
1365 return (!mIsPowered &&
1366 mBatteryService.getBatteryLevel() <= Power.LOW_BATTERY_THRESHOLD);
1367 }
1368
The Android Open Source Project10592532009-03-18 17:39:46 -07001369 private void updateLightsLocked(int newState, int forceState) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001370 int oldState = mPowerState;
1371 int difference = (newState ^ oldState) | forceState;
1372 if (difference == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001373 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001374 }
1375
1376 int offMask = 0;
1377 int dimMask = 0;
1378 int onMask = 0;
1379
1380 int preferredBrightness = getPreferredBrightness();
1381 boolean startAnimation = false;
1382
1383 if ((difference & KEYBOARD_BRIGHT_BIT) != 0) {
1384 if (ANIMATE_KEYBOARD_LIGHTS) {
1385 if ((newState & KEYBOARD_BRIGHT_BIT) == 0) {
1386 mKeyboardBrightness.setTargetLocked(Power.BRIGHTNESS_OFF,
Joe Onorato128e7292009-03-24 18:41:31 -07001387 ANIM_STEPS, INITIAL_KEYBOARD_BRIGHTNESS,
1388 preferredBrightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001389 } else {
1390 mKeyboardBrightness.setTargetLocked(preferredBrightness,
Joe Onorato128e7292009-03-24 18:41:31 -07001391 ANIM_STEPS, INITIAL_KEYBOARD_BRIGHTNESS,
1392 Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001393 }
1394 startAnimation = true;
1395 } else {
1396 if ((newState & KEYBOARD_BRIGHT_BIT) == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001397 offMask |= KEYBOARD_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001398 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001399 onMask |= KEYBOARD_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001400 }
1401 }
1402 }
1403
1404 if ((difference & BUTTON_BRIGHT_BIT) != 0) {
1405 if (ANIMATE_BUTTON_LIGHTS) {
1406 if ((newState & BUTTON_BRIGHT_BIT) == 0) {
1407 mButtonBrightness.setTargetLocked(Power.BRIGHTNESS_OFF,
Joe Onorato128e7292009-03-24 18:41:31 -07001408 ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
1409 preferredBrightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001410 } else {
1411 mButtonBrightness.setTargetLocked(preferredBrightness,
Joe Onorato128e7292009-03-24 18:41:31 -07001412 ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
1413 Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001414 }
1415 startAnimation = true;
1416 } else {
1417 if ((newState & BUTTON_BRIGHT_BIT) == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001418 offMask |= BUTTON_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001419 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001420 onMask |= BUTTON_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001421 }
1422 }
1423 }
1424
1425 if ((difference & (SCREEN_ON_BIT | SCREEN_BRIGHT_BIT)) != 0) {
1426 if (ANIMATE_SCREEN_LIGHTS) {
Joe Onorato128e7292009-03-24 18:41:31 -07001427 int nominalCurrentValue;
1428 switch (oldState & (SCREEN_BRIGHT_BIT|SCREEN_ON_BIT)) {
1429 case SCREEN_BRIGHT_BIT | SCREEN_ON_BIT:
1430 nominalCurrentValue = preferredBrightness;
1431 break;
1432 case SCREEN_ON_BIT:
1433 nominalCurrentValue = Power.BRIGHTNESS_DIM;
1434 break;
1435 case 0:
1436 nominalCurrentValue = Power.BRIGHTNESS_OFF;
1437 break;
1438 case SCREEN_BRIGHT_BIT:
1439 default:
1440 // not possible
1441 nominalCurrentValue = (int)mScreenBrightness.curValue;
1442 break;
1443 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001444 if ((newState & SCREEN_BRIGHT_BIT) == 0) {
1445 // dim or turn off backlight, depending on if the screen is on
1446 // the scale is because the brightness ramp isn't linear and this biases
1447 // it so the later parts take longer.
1448 final float scale = 1.5f;
1449 float ratio = (((float)Power.BRIGHTNESS_DIM)/preferredBrightness);
1450 if (ratio > 1.0f) ratio = 1.0f;
1451 if ((newState & SCREEN_ON_BIT) == 0) {
1452 int steps;
1453 if ((oldState & SCREEN_BRIGHT_BIT) != 0) {
1454 // was bright
1455 steps = ANIM_STEPS;
1456 } else {
1457 // was dim
1458 steps = (int)(ANIM_STEPS*ratio*scale);
1459 }
1460 mScreenBrightness.setTargetLocked(Power.BRIGHTNESS_OFF,
Joe Onorato128e7292009-03-24 18:41:31 -07001461 steps, INITIAL_SCREEN_BRIGHTNESS, nominalCurrentValue);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001462 } else {
1463 int steps;
1464 if ((oldState & SCREEN_ON_BIT) != 0) {
1465 // was bright
1466 steps = (int)(ANIM_STEPS*(1.0f-ratio)*scale);
1467 } else {
1468 // was dim
1469 steps = (int)(ANIM_STEPS*ratio);
1470 }
1471 if (mStayOnConditions != 0 && mBatteryService.isPowered(mStayOnConditions)) {
1472 // If the "stay on while plugged in" option is
1473 // turned on, then the screen will often not
1474 // automatically turn off while plugged in. To
1475 // still have a sense of when it is inactive, we
1476 // will then count going dim as turning off.
1477 mScreenOffTime = SystemClock.elapsedRealtime();
1478 }
1479 mScreenBrightness.setTargetLocked(Power.BRIGHTNESS_DIM,
Joe Onorato128e7292009-03-24 18:41:31 -07001480 steps, INITIAL_SCREEN_BRIGHTNESS, nominalCurrentValue);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001481 }
1482 } else {
1483 mScreenBrightness.setTargetLocked(preferredBrightness,
Joe Onorato128e7292009-03-24 18:41:31 -07001484 ANIM_STEPS, INITIAL_SCREEN_BRIGHTNESS, nominalCurrentValue);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001485 }
1486 startAnimation = true;
1487 } else {
1488 if ((newState & SCREEN_BRIGHT_BIT) == 0) {
1489 // dim or turn off backlight, depending on if the screen is on
1490 if ((newState & SCREEN_ON_BIT) == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001491 offMask |= SCREEN_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001492 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001493 dimMask |= SCREEN_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001494 }
1495 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001496 onMask |= SCREEN_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001497 }
1498 }
1499 }
1500
1501 if (startAnimation) {
1502 if (mSpew) {
1503 Log.i(TAG, "Scheduling light animator!");
1504 }
1505 mHandler.removeCallbacks(mLightAnimator);
1506 mHandler.post(mLightAnimator);
1507 }
1508
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001509 if (offMask != 0) {
1510 //Log.i(TAG, "Setting brightess off: " + offMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001511 setLightBrightness(offMask, Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001512 }
1513 if (dimMask != 0) {
1514 int brightness = Power.BRIGHTNESS_DIM;
1515 if ((newState & BATTERY_LOW_BIT) != 0 &&
1516 brightness > Power.BRIGHTNESS_LOW_BATTERY) {
1517 brightness = Power.BRIGHTNESS_LOW_BATTERY;
1518 }
1519 //Log.i(TAG, "Setting brightess dim " + brightness + ": " + offMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001520 setLightBrightness(dimMask, brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001521 }
1522 if (onMask != 0) {
1523 int brightness = getPreferredBrightness();
1524 if ((newState & BATTERY_LOW_BIT) != 0 &&
1525 brightness > Power.BRIGHTNESS_LOW_BATTERY) {
1526 brightness = Power.BRIGHTNESS_LOW_BATTERY;
1527 }
1528 //Log.i(TAG, "Setting brightess on " + brightness + ": " + onMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001529 setLightBrightness(onMask, brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001530 }
The Android Open Source Project10592532009-03-18 17:39:46 -07001531 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001532
The Android Open Source Project10592532009-03-18 17:39:46 -07001533 private void setLightBrightness(int mask, int value) {
1534 if ((mask & SCREEN_BRIGHT_BIT) != 0) {
1535 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_BACKLIGHT, value);
1536 }
1537 if ((mask & BUTTON_BRIGHT_BIT) != 0) {
1538 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_BUTTONS, value);
1539 }
1540 if ((mask & KEYBOARD_BRIGHT_BIT) != 0) {
1541 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_KEYBOARD, value);
1542 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001543 }
1544
1545 class BrightnessState {
1546 final int mask;
1547
1548 boolean initialized;
1549 int targetValue;
1550 float curValue;
1551 float delta;
1552 boolean animating;
1553
1554 BrightnessState(int m) {
1555 mask = m;
1556 }
1557
1558 public void dump(PrintWriter pw, String prefix) {
1559 pw.println(prefix + "animating=" + animating
1560 + " targetValue=" + targetValue
1561 + " curValue=" + curValue
1562 + " delta=" + delta);
1563 }
1564
Joe Onorato128e7292009-03-24 18:41:31 -07001565 void setTargetLocked(int target, int stepsToTarget, int initialValue,
1566 int nominalCurrentValue) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001567 if (!initialized) {
1568 initialized = true;
1569 curValue = (float)initialValue;
1570 }
1571 targetValue = target;
Joe Onorato128e7292009-03-24 18:41:31 -07001572 delta = (targetValue-nominalCurrentValue) / stepsToTarget;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001573 if (mSpew) {
Joe Onorato128e7292009-03-24 18:41:31 -07001574 String noticeMe = nominalCurrentValue == curValue ? "" : " ******************";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001575 Log.i(TAG, "Setting target " + mask + ": cur=" + curValue
Joe Onorato128e7292009-03-24 18:41:31 -07001576 + " target=" + targetValue + " delta=" + delta
1577 + " nominalCurrentValue=" + nominalCurrentValue
1578 + noticeMe);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001579 }
1580 animating = true;
1581 }
1582
1583 boolean stepLocked() {
1584 if (!animating) return false;
1585 if (false && mSpew) {
1586 Log.i(TAG, "Step target " + mask + ": cur=" + curValue
1587 + " target=" + targetValue + " delta=" + delta);
1588 }
1589 curValue += delta;
1590 int curIntValue = (int)curValue;
1591 boolean more = true;
1592 if (delta == 0) {
1593 more = false;
1594 } else if (delta > 0) {
1595 if (curIntValue >= targetValue) {
1596 curValue = curIntValue = targetValue;
1597 more = false;
1598 }
1599 } else {
1600 if (curIntValue <= targetValue) {
1601 curValue = curIntValue = targetValue;
1602 more = false;
1603 }
1604 }
1605 //Log.i(TAG, "Animating brightess " + curIntValue + ": " + mask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001606 setLightBrightness(mask, curIntValue);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001607 animating = more;
1608 if (!more) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001609 if (mask == SCREEN_BRIGHT_BIT && curIntValue == Power.BRIGHTNESS_OFF) {
Joe Onorato128e7292009-03-24 18:41:31 -07001610 screenOffFinishedAnimatingLocked(mOffBecauseOfUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001611 }
1612 }
1613 return more;
1614 }
1615 }
1616
1617 private class LightAnimator implements Runnable {
1618 public void run() {
1619 synchronized (mLocks) {
1620 long now = SystemClock.uptimeMillis();
1621 boolean more = mScreenBrightness.stepLocked();
1622 if (mKeyboardBrightness.stepLocked()) {
1623 more = true;
1624 }
1625 if (mButtonBrightness.stepLocked()) {
1626 more = true;
1627 }
1628 if (more) {
1629 mHandler.postAtTime(mLightAnimator, now+(1000/60));
1630 }
1631 }
1632 }
1633 }
1634
1635 private int getPreferredBrightness() {
1636 try {
1637 if (mScreenBrightnessOverride >= 0) {
1638 return mScreenBrightnessOverride;
1639 }
1640 final int brightness = Settings.System.getInt(mContext.getContentResolver(),
1641 SCREEN_BRIGHTNESS);
1642 // Don't let applications turn the screen all the way off
1643 return Math.max(brightness, Power.BRIGHTNESS_DIM);
1644 } catch (SettingNotFoundException snfe) {
1645 return Power.BRIGHTNESS_ON;
1646 }
1647 }
1648
1649 boolean screenIsOn() {
1650 synchronized (mLocks) {
1651 return (mPowerState & SCREEN_ON_BIT) != 0;
1652 }
1653 }
1654
1655 boolean screenIsBright() {
1656 synchronized (mLocks) {
1657 return (mPowerState & SCREEN_BRIGHT) == SCREEN_BRIGHT;
1658 }
1659 }
1660
1661 public void userActivityWithForce(long time, boolean noChangeLights, boolean force) {
1662 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1663 userActivity(time, noChangeLights, OTHER_EVENT, force);
1664 }
1665
1666 public void userActivity(long time, boolean noChangeLights) {
1667 userActivity(time, noChangeLights, OTHER_EVENT, false);
1668 }
1669
1670 public void userActivity(long time, boolean noChangeLights, int eventType) {
1671 userActivity(time, noChangeLights, eventType, false);
1672 }
1673
1674 public void userActivity(long time, boolean noChangeLights, int eventType, boolean force) {
1675 //mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1676
1677 if (((mPokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0)
1678 && !((eventType == OTHER_EVENT) || (eventType == BUTTON_EVENT))) {
1679 if (false) {
1680 Log.d(TAG, "dropping mPokey=0x" + Integer.toHexString(mPokey));
1681 }
1682 return;
1683 }
1684
1685 if (false) {
1686 if (((mPokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0)) {
1687 Log.d(TAG, "userActivity !!!");//, new RuntimeException());
1688 } else {
1689 Log.d(TAG, "mPokey=0x" + Integer.toHexString(mPokey));
1690 }
1691 }
1692
1693 synchronized (mLocks) {
1694 if (mSpew) {
1695 Log.d(TAG, "userActivity mLastEventTime=" + mLastEventTime + " time=" + time
1696 + " mUserActivityAllowed=" + mUserActivityAllowed
1697 + " mUserState=0x" + Integer.toHexString(mUserState)
1698 + " mWakeLockState=0x" + Integer.toHexString(mWakeLockState));
1699 }
1700 if (mLastEventTime <= time || force) {
1701 mLastEventTime = time;
1702 if (mUserActivityAllowed || force) {
1703 // Only turn on button backlights if a button was pressed.
1704 if (eventType == BUTTON_EVENT) {
1705 mUserState = (mKeyboardVisible ? ALL_BRIGHT : SCREEN_BUTTON_BRIGHT);
1706 } else {
1707 // don't clear button/keyboard backlights when the screen is touched.
1708 mUserState |= SCREEN_BRIGHT;
1709 }
1710
1711 reactivateWakeLocksLocked();
1712 mWakeLockState = mLocks.gatherState();
1713 setPowerState(mUserState | mWakeLockState, noChangeLights, true);
1714 setTimeoutLocked(time, SCREEN_BRIGHT);
1715 }
1716 }
1717 }
1718 }
1719
1720 /**
1721 * The user requested that we go to sleep (probably with the power button).
1722 * This overrides all wake locks that are held.
1723 */
1724 public void goToSleep(long time)
1725 {
1726 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1727 synchronized (mLocks) {
1728 goToSleepLocked(time);
1729 }
1730 }
1731
1732 /**
1733 * Returns the time the screen has been on since boot, in millis.
1734 * @return screen on time
1735 */
1736 public long getScreenOnTime() {
1737 synchronized (mLocks) {
1738 if (mScreenOnStartTime == 0) {
1739 return mScreenOnTime;
1740 } else {
1741 return SystemClock.elapsedRealtime() - mScreenOnStartTime + mScreenOnTime;
1742 }
1743 }
1744 }
1745
1746 private void goToSleepLocked(long time) {
1747
1748 if (mLastEventTime <= time) {
1749 mLastEventTime = time;
1750 // cancel all of the wake locks
1751 mWakeLockState = SCREEN_OFF;
1752 int N = mLocks.size();
1753 int numCleared = 0;
1754 for (int i=0; i<N; i++) {
1755 WakeLock wl = mLocks.get(i);
1756 if (isScreenLock(wl.flags)) {
1757 mLocks.get(i).activated = false;
1758 numCleared++;
1759 }
1760 }
1761 EventLog.writeEvent(LOG_POWER_SLEEP_REQUESTED, numCleared);
Joe Onorato128e7292009-03-24 18:41:31 -07001762 mStillNeedSleepNotification = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001763 mUserState = SCREEN_OFF;
1764 setPowerState(SCREEN_OFF, false, true);
1765 cancelTimerLocked();
1766 }
1767 }
1768
1769 public long timeSinceScreenOn() {
1770 synchronized (mLocks) {
1771 if ((mPowerState & SCREEN_ON_BIT) != 0) {
1772 return 0;
1773 }
1774 return SystemClock.elapsedRealtime() - mScreenOffTime;
1775 }
1776 }
1777
1778 public void setKeyboardVisibility(boolean visible) {
1779 mKeyboardVisible = visible;
1780 }
1781
1782 /**
1783 * When the keyguard is up, it manages the power state, and userActivity doesn't do anything.
1784 */
1785 public void enableUserActivity(boolean enabled) {
1786 synchronized (mLocks) {
1787 mUserActivityAllowed = enabled;
1788 mLastEventTime = SystemClock.uptimeMillis(); // we might need to pass this in
1789 }
1790 }
1791
1792 /** Sets the screen off timeouts:
1793 * mKeylightDelay
1794 * mDimDelay
1795 * mScreenOffDelay
1796 * */
1797 private void setScreenOffTimeoutsLocked() {
1798 if ((mPokey & POKE_LOCK_SHORT_TIMEOUT) != 0) {
1799 mKeylightDelay = mShortKeylightDelay; // Configurable via Gservices
1800 mDimDelay = -1;
1801 mScreenOffDelay = 0;
1802 } else if ((mPokey & POKE_LOCK_MEDIUM_TIMEOUT) != 0) {
1803 mKeylightDelay = MEDIUM_KEYLIGHT_DELAY;
1804 mDimDelay = -1;
1805 mScreenOffDelay = 0;
1806 } else {
1807 int totalDelay = mTotalDelaySetting;
1808 mKeylightDelay = LONG_KEYLIGHT_DELAY;
1809 if (totalDelay < 0) {
1810 mScreenOffDelay = Integer.MAX_VALUE;
1811 } else if (mKeylightDelay < totalDelay) {
1812 // subtract the time that the keylight delay. This will give us the
1813 // remainder of the time that we need to sleep to get the accurate
1814 // screen off timeout.
1815 mScreenOffDelay = totalDelay - mKeylightDelay;
1816 } else {
1817 mScreenOffDelay = 0;
1818 }
1819 if (mDimScreen && totalDelay >= (LONG_KEYLIGHT_DELAY + LONG_DIM_TIME)) {
1820 mDimDelay = mScreenOffDelay - LONG_DIM_TIME;
1821 mScreenOffDelay = LONG_DIM_TIME;
1822 } else {
1823 mDimDelay = -1;
1824 }
1825 }
1826 if (mSpew) {
1827 Log.d(TAG, "setScreenOffTimeouts mKeylightDelay=" + mKeylightDelay
1828 + " mDimDelay=" + mDimDelay + " mScreenOffDelay=" + mScreenOffDelay
1829 + " mDimScreen=" + mDimScreen);
1830 }
1831 }
1832
1833 /**
1834 * Refreshes cached Gservices settings. Called once on startup, and
1835 * on subsequent Settings.Gservices.CHANGED_ACTION broadcasts (see
1836 * GservicesChangedReceiver).
1837 */
1838 private void updateGservicesValues() {
1839 mShortKeylightDelay = Settings.Gservices.getInt(
1840 mContext.getContentResolver(),
1841 Settings.Gservices.SHORT_KEYLIGHT_DELAY_MS,
1842 SHORT_KEYLIGHT_DELAY_DEFAULT);
1843 // Log.i(TAG, "updateGservicesValues(): mShortKeylightDelay now " + mShortKeylightDelay);
1844 }
1845
1846 /**
1847 * Receiver for the Gservices.CHANGED_ACTION broadcast intent,
1848 * which tells us we need to refresh our cached Gservices settings.
1849 */
1850 private class GservicesChangedReceiver extends BroadcastReceiver {
1851 @Override
1852 public void onReceive(Context context, Intent intent) {
1853 // Log.i(TAG, "GservicesChangedReceiver.onReceive(): " + intent);
1854 updateGservicesValues();
1855 }
1856 }
1857
1858 private class LockList extends ArrayList<WakeLock>
1859 {
1860 void addLock(WakeLock wl)
1861 {
1862 int index = getIndex(wl.binder);
1863 if (index < 0) {
1864 this.add(wl);
1865 }
1866 }
1867
1868 WakeLock removeLock(IBinder binder)
1869 {
1870 int index = getIndex(binder);
1871 if (index >= 0) {
1872 return this.remove(index);
1873 } else {
1874 return null;
1875 }
1876 }
1877
1878 int getIndex(IBinder binder)
1879 {
1880 int N = this.size();
1881 for (int i=0; i<N; i++) {
1882 if (this.get(i).binder == binder) {
1883 return i;
1884 }
1885 }
1886 return -1;
1887 }
1888
1889 int gatherState()
1890 {
1891 int result = 0;
1892 int N = this.size();
1893 for (int i=0; i<N; i++) {
1894 WakeLock wl = this.get(i);
1895 if (wl.activated) {
1896 if (isScreenLock(wl.flags)) {
1897 result |= wl.minState;
1898 }
1899 }
1900 }
1901 return result;
1902 }
1903 }
1904
1905 void setPolicy(WindowManagerPolicy p) {
1906 synchronized (mLocks) {
1907 mPolicy = p;
1908 mLocks.notifyAll();
1909 }
1910 }
1911
1912 WindowManagerPolicy getPolicyLocked() {
1913 while (mPolicy == null || !mDoneBooting) {
1914 try {
1915 mLocks.wait();
1916 } catch (InterruptedException e) {
1917 // Ignore
1918 }
1919 }
1920 return mPolicy;
1921 }
1922
1923 void systemReady() {
1924 synchronized (mLocks) {
1925 Log.d(TAG, "system ready!");
1926 mDoneBooting = true;
1927 userActivity(SystemClock.uptimeMillis(), false, BUTTON_EVENT, true);
1928 updateWakeLockLocked();
1929 mLocks.notifyAll();
1930 }
1931 }
1932
1933 public void monitor() {
1934 synchronized (mLocks) { }
1935 }
1936}