blob: a900b3e5a3071bcab00cf39a9db9d9b41ecf2a68 [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" : "")
Joe Onoratoe68ffcb2009-03-24 19:11:13 -0700846 + ((p.pokey & POKE_LOCK_IGNORE_TOUCH_AND_CHEEK_EVENTS) != 0
847 ? " POKE_LOCK_IGNORE_TOUCH_AND_CHEEK_EVENTS" : "")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800848 + ((p.pokey & POKE_LOCK_SHORT_TIMEOUT) != 0
849 ? " POKE_LOCK_SHORT_TIMEOUT" : "")
850 + ((p.pokey & POKE_LOCK_MEDIUM_TIMEOUT) != 0
851 ? " POKE_LOCK_MEDIUM_TIMEOUT" : ""));
852 }
853
854 pw.println();
855 }
856
857 private void setTimeoutLocked(long now, int nextState)
858 {
859 if (mDoneBooting) {
860 mHandler.removeCallbacks(mTimeoutTask);
861 mTimeoutTask.nextState = nextState;
862 long when = now;
863 switch (nextState)
864 {
865 case SCREEN_BRIGHT:
866 when += mKeylightDelay;
867 break;
868 case SCREEN_DIM:
869 if (mDimDelay >= 0) {
870 when += mDimDelay;
871 break;
872 } else {
873 Log.w(TAG, "mDimDelay=" + mDimDelay + " while trying to dim");
874 }
875 case SCREEN_OFF:
876 synchronized (mLocks) {
877 when += mScreenOffDelay;
878 }
879 break;
880 }
881 if (mSpew) {
882 Log.d(TAG, "setTimeoutLocked now=" + now + " nextState=" + nextState
883 + " when=" + when);
884 }
885 mHandler.postAtTime(mTimeoutTask, when);
886 mNextTimeout = when; // for debugging
887 }
888 }
889
890 private void cancelTimerLocked()
891 {
892 mHandler.removeCallbacks(mTimeoutTask);
893 mTimeoutTask.nextState = -1;
894 }
895
896 private class TimeoutTask implements Runnable
897 {
898 int nextState; // access should be synchronized on mLocks
899 public void run()
900 {
901 synchronized (mLocks) {
902 if (mSpew) {
903 Log.d(TAG, "user activity timeout timed out nextState=" + this.nextState);
904 }
905
906 if (nextState == -1) {
907 return;
908 }
909
910 mUserState = this.nextState;
911 setPowerState(this.nextState | mWakeLockState);
912
913 long now = SystemClock.uptimeMillis();
914
915 switch (this.nextState)
916 {
917 case SCREEN_BRIGHT:
918 if (mDimDelay >= 0) {
919 setTimeoutLocked(now, SCREEN_DIM);
920 break;
921 }
922 case SCREEN_DIM:
923 setTimeoutLocked(now, SCREEN_OFF);
924 break;
925 }
926 }
927 }
928 }
929
930 private void sendNotificationLocked(boolean on, int why)
931 {
Joe Onorato64c62ba2009-03-24 20:13:57 -0700932 if (!on) {
933 mStillNeedSleepNotification = false;
934 }
935
Joe Onorato128e7292009-03-24 18:41:31 -0700936 // Add to the queue.
937 int index = 0;
938 while (mBroadcastQueue[index] != -1) {
939 index++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800940 }
Joe Onorato128e7292009-03-24 18:41:31 -0700941 mBroadcastQueue[index] = on ? 1 : 0;
942 mBroadcastWhy[index] = why;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800943
Joe Onorato128e7292009-03-24 18:41:31 -0700944 // If we added it position 2, then there is a pair that can be stripped.
945 // If we added it position 1 and we're turning the screen off, we can strip
946 // the pair and do nothing, because the screen is already off, and therefore
947 // keyguard has already been enabled.
948 // However, if we added it at position 1 and we're turning it on, then position
949 // 0 was to turn it off, and we can't strip that, because keyguard needs to come
950 // on, so have to run the queue then.
951 if (index == 2) {
952 // Also, while we're collapsing them, if it's going to be an "off," and one
953 // is off because of user, then use that, regardless of whether it's the first
954 // or second one.
955 if (!on && why == WindowManagerPolicy.OFF_BECAUSE_OF_USER) {
956 mBroadcastWhy[0] = WindowManagerPolicy.OFF_BECAUSE_OF_USER;
957 }
958 mBroadcastQueue[0] = on ? 1 : 0;
959 mBroadcastQueue[1] = -1;
960 mBroadcastQueue[2] = -1;
961 index = 0;
962 }
963 if (index == 1 && !on) {
964 mBroadcastQueue[0] = -1;
965 mBroadcastQueue[1] = -1;
966 index = -1;
967 // The wake lock was being held, but we're not actually going to do any
968 // broadcasts, so release the wake lock.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800969 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_STOP, 1, mBroadcastWakeLock.mCount);
970 mBroadcastWakeLock.release();
Joe Onorato128e7292009-03-24 18:41:31 -0700971 }
972
973 // Now send the message.
974 if (index >= 0) {
975 // Acquire the broadcast wake lock before changing the power
976 // state. It will be release after the broadcast is sent.
977 // We always increment the ref count for each notification in the queue
978 // and always decrement when that notification is handled.
979 mBroadcastWakeLock.acquire();
980 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_SEND, mBroadcastWakeLock.mCount);
981 mHandler.post(mNotificationTask);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800982 }
983 }
984
985 private Runnable mNotificationTask = new Runnable()
986 {
987 public void run()
988 {
Joe Onorato128e7292009-03-24 18:41:31 -0700989 while (true) {
990 int value;
991 int why;
992 WindowManagerPolicy policy;
993 synchronized (mLocks) {
994 value = mBroadcastQueue[0];
995 why = mBroadcastWhy[0];
996 for (int i=0; i<2; i++) {
997 mBroadcastQueue[i] = mBroadcastQueue[i+1];
998 mBroadcastWhy[i] = mBroadcastWhy[i+1];
999 }
1000 policy = getPolicyLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001001 }
Joe Onorato128e7292009-03-24 18:41:31 -07001002 if (value == 1) {
1003 mScreenOnStart = SystemClock.uptimeMillis();
1004
1005 policy.screenTurnedOn();
1006 try {
1007 ActivityManagerNative.getDefault().wakingUp();
1008 } catch (RemoteException e) {
1009 // ignore it
1010 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001011
Joe Onorato128e7292009-03-24 18:41:31 -07001012 if (mSpew) {
1013 Log.d(TAG, "mBroadcastWakeLock=" + mBroadcastWakeLock);
1014 }
1015 if (mContext != null && ActivityManagerNative.isSystemReady()) {
1016 mContext.sendOrderedBroadcast(mScreenOnIntent, null,
1017 mScreenOnBroadcastDone, mHandler, 0, null, null);
1018 } else {
1019 synchronized (mLocks) {
1020 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_STOP, 2,
1021 mBroadcastWakeLock.mCount);
1022 mBroadcastWakeLock.release();
1023 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001024 }
1025 }
Joe Onorato128e7292009-03-24 18:41:31 -07001026 else if (value == 0) {
1027 mScreenOffStart = SystemClock.uptimeMillis();
1028
1029 policy.screenTurnedOff(why);
1030 try {
1031 ActivityManagerNative.getDefault().goingToSleep();
1032 } catch (RemoteException e) {
1033 // ignore it.
1034 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001035
Joe Onorato128e7292009-03-24 18:41:31 -07001036 if (mContext != null && ActivityManagerNative.isSystemReady()) {
1037 mContext.sendOrderedBroadcast(mScreenOffIntent, null,
1038 mScreenOffBroadcastDone, mHandler, 0, null, null);
1039 } else {
1040 synchronized (mLocks) {
1041 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_STOP, 3,
1042 mBroadcastWakeLock.mCount);
1043 mBroadcastWakeLock.release();
1044 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001045 }
1046 }
Joe Onorato128e7292009-03-24 18:41:31 -07001047 else {
1048 // If we're in this case, then this handler is running for a previous
1049 // paired transaction. mBroadcastWakeLock will already have been released.
1050 break;
1051 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001052 }
1053 }
1054 };
1055
1056 long mScreenOnStart;
1057 private BroadcastReceiver mScreenOnBroadcastDone = new BroadcastReceiver() {
1058 public void onReceive(Context context, Intent intent) {
1059 synchronized (mLocks) {
1060 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_DONE, 1,
1061 SystemClock.uptimeMillis() - mScreenOnStart, mBroadcastWakeLock.mCount);
1062 mBroadcastWakeLock.release();
1063 }
1064 }
1065 };
1066
1067 long mScreenOffStart;
1068 private BroadcastReceiver mScreenOffBroadcastDone = new BroadcastReceiver() {
1069 public void onReceive(Context context, Intent intent) {
1070 synchronized (mLocks) {
1071 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_DONE, 0,
1072 SystemClock.uptimeMillis() - mScreenOffStart, mBroadcastWakeLock.mCount);
1073 mBroadcastWakeLock.release();
1074 }
1075 }
1076 };
1077
1078 void logPointerUpEvent() {
1079 if (LOG_TOUCH_DOWNS) {
1080 mTotalTouchDownTime += SystemClock.elapsedRealtime() - mLastTouchDown;
1081 mLastTouchDown = 0;
1082 }
1083 }
1084
1085 void logPointerDownEvent() {
1086 if (LOG_TOUCH_DOWNS) {
1087 // If we are not already timing a down/up sequence
1088 if (mLastTouchDown == 0) {
1089 mLastTouchDown = SystemClock.elapsedRealtime();
1090 mTouchCycles++;
1091 }
1092 }
1093 }
1094
1095 /**
1096 * Prevents the screen from turning on even if it *should* turn on due
1097 * to a subsequent full wake lock being acquired.
1098 * <p>
1099 * This is a temporary hack that allows an activity to "cover up" any
1100 * display glitches that happen during the activity's startup
1101 * sequence. (Specifically, this API was added to work around a
1102 * cosmetic bug in the "incoming call" sequence, where the lock screen
1103 * would flicker briefly before the incoming call UI became visible.)
1104 * TODO: There ought to be a more elegant way of doing this,
1105 * probably by having the PowerManager and ActivityManager
1106 * work together to let apps specify that the screen on/off
1107 * state should be synchronized with the Activity lifecycle.
1108 * <p>
1109 * Note that calling preventScreenOn(true) will NOT turn the screen
1110 * off if it's currently on. (This API only affects *future*
1111 * acquisitions of full wake locks.)
1112 * But calling preventScreenOn(false) WILL turn the screen on if
1113 * it's currently off because of a prior preventScreenOn(true) call.
1114 * <p>
1115 * Any call to preventScreenOn(true) MUST be followed promptly by a call
1116 * to preventScreenOn(false). In fact, if the preventScreenOn(false)
1117 * call doesn't occur within 5 seconds, we'll turn the screen back on
1118 * ourselves (and log a warning about it); this prevents a buggy app
1119 * from disabling the screen forever.)
1120 * <p>
1121 * TODO: this feature should really be controlled by a new type of poke
1122 * lock (rather than an IPowerManager call).
1123 */
1124 public void preventScreenOn(boolean prevent) {
1125 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1126
1127 synchronized (mLocks) {
1128 if (prevent) {
1129 // First of all, grab a partial wake lock to
1130 // make sure the CPU stays on during the entire
1131 // preventScreenOn(true) -> preventScreenOn(false) sequence.
1132 mPreventScreenOnPartialLock.acquire();
1133
1134 // Post a forceReenableScreen() call (for 5 seconds in the
1135 // future) to make sure the matching preventScreenOn(false) call
1136 // has happened by then.
1137 mHandler.removeCallbacks(mForceReenableScreenTask);
1138 mHandler.postDelayed(mForceReenableScreenTask, 5000);
1139
1140 // Finally, set the flag that prevents the screen from turning on.
1141 // (Below, in setPowerState(), we'll check mPreventScreenOn and
1142 // we *won't* call Power.setScreenState(true) if it's set.)
1143 mPreventScreenOn = true;
1144 } else {
1145 // (Re)enable the screen.
1146 mPreventScreenOn = false;
1147
1148 // We're "undoing" a the prior preventScreenOn(true) call, so we
1149 // no longer need the 5-second safeguard.
1150 mHandler.removeCallbacks(mForceReenableScreenTask);
1151
1152 // Forcibly turn on the screen if it's supposed to be on. (This
1153 // handles the case where the screen is currently off because of
1154 // a prior preventScreenOn(true) call.)
1155 if ((mPowerState & SCREEN_ON_BIT) != 0) {
1156 if (mSpew) {
1157 Log.d(TAG,
1158 "preventScreenOn: turning on after a prior preventScreenOn(true)!");
1159 }
1160 int err = Power.setScreenState(true);
1161 if (err != 0) {
1162 Log.w(TAG, "preventScreenOn: error from Power.setScreenState(): " + err);
1163 }
1164 }
1165
1166 // Release the partial wake lock that we held during the
1167 // preventScreenOn(true) -> preventScreenOn(false) sequence.
1168 mPreventScreenOnPartialLock.release();
1169 }
1170 }
1171 }
1172
1173 public void setScreenBrightnessOverride(int brightness) {
1174 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1175
1176 synchronized (mLocks) {
1177 if (mScreenBrightnessOverride != brightness) {
1178 mScreenBrightnessOverride = brightness;
1179 updateLightsLocked(mPowerState, SCREEN_ON_BIT);
1180 }
1181 }
1182 }
1183
1184 /**
1185 * Sanity-check that gets called 5 seconds after any call to
1186 * preventScreenOn(true). This ensures that the original call
1187 * is followed promptly by a call to preventScreenOn(false).
1188 */
1189 private void forceReenableScreen() {
1190 // We shouldn't get here at all if mPreventScreenOn is false, since
1191 // we should have already removed any existing
1192 // mForceReenableScreenTask messages...
1193 if (!mPreventScreenOn) {
1194 Log.w(TAG, "forceReenableScreen: mPreventScreenOn is false, nothing to do");
1195 return;
1196 }
1197
1198 // Uh oh. It's been 5 seconds since a call to
1199 // preventScreenOn(true) and we haven't re-enabled the screen yet.
1200 // This means the app that called preventScreenOn(true) is either
1201 // slow (i.e. it took more than 5 seconds to call preventScreenOn(false)),
1202 // or buggy (i.e. it forgot to call preventScreenOn(false), or
1203 // crashed before doing so.)
1204
1205 // Log a warning, and forcibly turn the screen back on.
1206 Log.w(TAG, "App called preventScreenOn(true) but didn't promptly reenable the screen! "
1207 + "Forcing the screen back on...");
1208 preventScreenOn(false);
1209 }
1210
1211 private Runnable mForceReenableScreenTask = new Runnable() {
1212 public void run() {
1213 forceReenableScreen();
1214 }
1215 };
1216
1217 private void setPowerState(int state)
1218 {
1219 setPowerState(state, false, false);
1220 }
1221
1222 private void setPowerState(int newState, boolean noChangeLights, boolean becauseOfUser)
1223 {
1224 synchronized (mLocks) {
1225 int err;
1226
1227 if (mSpew) {
1228 Log.d(TAG, "setPowerState: mPowerState=0x" + Integer.toHexString(mPowerState)
1229 + " newState=0x" + Integer.toHexString(newState)
1230 + " noChangeLights=" + noChangeLights);
1231 }
1232
1233 if (noChangeLights) {
1234 newState = (newState & ~LIGHTS_MASK) | (mPowerState & LIGHTS_MASK);
1235 }
1236
1237 if (batteryIsLow()) {
1238 newState |= BATTERY_LOW_BIT;
1239 } else {
1240 newState &= ~BATTERY_LOW_BIT;
1241 }
1242 if (newState == mPowerState) {
1243 return;
1244 }
1245
1246 if (!mDoneBooting) {
1247 newState |= ALL_BRIGHT;
1248 }
1249
1250 boolean oldScreenOn = (mPowerState & SCREEN_ON_BIT) != 0;
1251 boolean newScreenOn = (newState & SCREEN_ON_BIT) != 0;
1252
1253 if (mSpew) {
1254 Log.d(TAG, "setPowerState: mPowerState=" + mPowerState
1255 + " newState=" + newState + " noChangeLights=" + noChangeLights);
1256 Log.d(TAG, " oldKeyboardBright=" + ((mPowerState & KEYBOARD_BRIGHT_BIT) != 0)
1257 + " newKeyboardBright=" + ((newState & KEYBOARD_BRIGHT_BIT) != 0));
1258 Log.d(TAG, " oldScreenBright=" + ((mPowerState & SCREEN_BRIGHT_BIT) != 0)
1259 + " newScreenBright=" + ((newState & SCREEN_BRIGHT_BIT) != 0));
1260 Log.d(TAG, " oldButtonBright=" + ((mPowerState & BUTTON_BRIGHT_BIT) != 0)
1261 + " newButtonBright=" + ((newState & BUTTON_BRIGHT_BIT) != 0));
1262 Log.d(TAG, " oldScreenOn=" + oldScreenOn
1263 + " newScreenOn=" + newScreenOn);
1264 Log.d(TAG, " oldBatteryLow=" + ((mPowerState & BATTERY_LOW_BIT) != 0)
1265 + " newBatteryLow=" + ((newState & BATTERY_LOW_BIT) != 0));
1266 }
1267
1268 if (mPowerState != newState) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001269 updateLightsLocked(newState, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001270 mPowerState = (mPowerState & ~LIGHTS_MASK) | (newState & LIGHTS_MASK);
1271 }
1272
1273 if (oldScreenOn != newScreenOn) {
1274 if (newScreenOn) {
Joe Onorato128e7292009-03-24 18:41:31 -07001275 // When the user presses the power button, we need to always send out the
1276 // notification that it's going to sleep so the keyguard goes on. But
1277 // we can't do that until the screen fades out, so we don't show the keyguard
1278 // too early.
1279 if (mStillNeedSleepNotification) {
1280 sendNotificationLocked(false, WindowManagerPolicy.OFF_BECAUSE_OF_USER);
1281 }
1282
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001283 // Turn on the screen UNLESS there was a prior
1284 // preventScreenOn(true) request. (Note that the lifetime
1285 // of a single preventScreenOn() request is limited to 5
1286 // seconds to prevent a buggy app from disabling the
1287 // screen forever; see forceReenableScreen().)
1288 boolean reallyTurnScreenOn = true;
1289 if (mSpew) {
1290 Log.d(TAG, "- turning screen on... mPreventScreenOn = "
1291 + mPreventScreenOn);
1292 }
1293
1294 if (mPreventScreenOn) {
1295 if (mSpew) {
1296 Log.d(TAG, "- PREVENTING screen from really turning on!");
1297 }
1298 reallyTurnScreenOn = false;
1299 }
1300 if (reallyTurnScreenOn) {
1301 err = Power.setScreenState(true);
1302 long identity = Binder.clearCallingIdentity();
1303 try {
1304 mBatteryStats.noteScreenOn();
1305 } catch (RemoteException e) {
1306 Log.w(TAG, "RemoteException calling noteScreenOn on BatteryStatsService", e);
1307 } finally {
1308 Binder.restoreCallingIdentity(identity);
1309 }
1310 } else {
1311 Power.setScreenState(false);
1312 // But continue as if we really did turn the screen on...
1313 err = 0;
1314 }
1315
1316 mScreenOnStartTime = SystemClock.elapsedRealtime();
1317 mLastTouchDown = 0;
1318 mTotalTouchDownTime = 0;
1319 mTouchCycles = 0;
1320 EventLog.writeEvent(LOG_POWER_SCREEN_STATE, 1, becauseOfUser ? 1 : 0,
1321 mTotalTouchDownTime, mTouchCycles);
1322 if (err == 0) {
1323 mPowerState |= SCREEN_ON_BIT;
1324 sendNotificationLocked(true, -1);
1325 }
1326 } else {
1327 mScreenOffTime = SystemClock.elapsedRealtime();
1328 long identity = Binder.clearCallingIdentity();
1329 try {
1330 mBatteryStats.noteScreenOff();
1331 } catch (RemoteException e) {
1332 Log.w(TAG, "RemoteException calling noteScreenOff on BatteryStatsService", e);
1333 } finally {
1334 Binder.restoreCallingIdentity(identity);
1335 }
1336 mPowerState &= ~SCREEN_ON_BIT;
1337 if (!mScreenBrightness.animating) {
Joe Onorato128e7292009-03-24 18:41:31 -07001338 err = screenOffFinishedAnimatingLocked(becauseOfUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001339 } else {
1340 mOffBecauseOfUser = becauseOfUser;
1341 err = 0;
1342 mLastTouchDown = 0;
1343 }
1344 }
1345 }
1346 }
1347 }
1348
Joe Onorato128e7292009-03-24 18:41:31 -07001349 private int screenOffFinishedAnimatingLocked(boolean becauseOfUser) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001350 // I don't think we need to check the current state here because all of these
1351 // Power.setScreenState and sendNotificationLocked can both handle being
1352 // called multiple times in the same state. -joeo
1353 EventLog.writeEvent(LOG_POWER_SCREEN_STATE, 0, becauseOfUser ? 1 : 0,
1354 mTotalTouchDownTime, mTouchCycles);
1355 mLastTouchDown = 0;
1356 int err = Power.setScreenState(false);
1357 if (mScreenOnStartTime != 0) {
1358 mScreenOnTime += SystemClock.elapsedRealtime() - mScreenOnStartTime;
1359 mScreenOnStartTime = 0;
1360 }
1361 if (err == 0) {
1362 int why = becauseOfUser
1363 ? WindowManagerPolicy.OFF_BECAUSE_OF_USER
1364 : WindowManagerPolicy.OFF_BECAUSE_OF_TIMEOUT;
1365 sendNotificationLocked(false, why);
1366 }
1367 return err;
1368 }
1369
1370 private boolean batteryIsLow() {
1371 return (!mIsPowered &&
1372 mBatteryService.getBatteryLevel() <= Power.LOW_BATTERY_THRESHOLD);
1373 }
1374
The Android Open Source Project10592532009-03-18 17:39:46 -07001375 private void updateLightsLocked(int newState, int forceState) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001376 int oldState = mPowerState;
1377 int difference = (newState ^ oldState) | forceState;
1378 if (difference == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001379 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001380 }
1381
1382 int offMask = 0;
1383 int dimMask = 0;
1384 int onMask = 0;
1385
1386 int preferredBrightness = getPreferredBrightness();
1387 boolean startAnimation = false;
1388
1389 if ((difference & KEYBOARD_BRIGHT_BIT) != 0) {
1390 if (ANIMATE_KEYBOARD_LIGHTS) {
1391 if ((newState & KEYBOARD_BRIGHT_BIT) == 0) {
1392 mKeyboardBrightness.setTargetLocked(Power.BRIGHTNESS_OFF,
Joe Onorato128e7292009-03-24 18:41:31 -07001393 ANIM_STEPS, INITIAL_KEYBOARD_BRIGHTNESS,
1394 preferredBrightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001395 } else {
1396 mKeyboardBrightness.setTargetLocked(preferredBrightness,
Joe Onorato128e7292009-03-24 18:41:31 -07001397 ANIM_STEPS, INITIAL_KEYBOARD_BRIGHTNESS,
1398 Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001399 }
1400 startAnimation = true;
1401 } else {
1402 if ((newState & KEYBOARD_BRIGHT_BIT) == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001403 offMask |= KEYBOARD_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001404 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001405 onMask |= KEYBOARD_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001406 }
1407 }
1408 }
1409
1410 if ((difference & BUTTON_BRIGHT_BIT) != 0) {
1411 if (ANIMATE_BUTTON_LIGHTS) {
1412 if ((newState & BUTTON_BRIGHT_BIT) == 0) {
1413 mButtonBrightness.setTargetLocked(Power.BRIGHTNESS_OFF,
Joe Onorato128e7292009-03-24 18:41:31 -07001414 ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
1415 preferredBrightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001416 } else {
1417 mButtonBrightness.setTargetLocked(preferredBrightness,
Joe Onorato128e7292009-03-24 18:41:31 -07001418 ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
1419 Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001420 }
1421 startAnimation = true;
1422 } else {
1423 if ((newState & BUTTON_BRIGHT_BIT) == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001424 offMask |= BUTTON_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001425 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001426 onMask |= BUTTON_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001427 }
1428 }
1429 }
1430
1431 if ((difference & (SCREEN_ON_BIT | SCREEN_BRIGHT_BIT)) != 0) {
1432 if (ANIMATE_SCREEN_LIGHTS) {
Joe Onorato128e7292009-03-24 18:41:31 -07001433 int nominalCurrentValue;
1434 switch (oldState & (SCREEN_BRIGHT_BIT|SCREEN_ON_BIT)) {
1435 case SCREEN_BRIGHT_BIT | SCREEN_ON_BIT:
1436 nominalCurrentValue = preferredBrightness;
1437 break;
1438 case SCREEN_ON_BIT:
1439 nominalCurrentValue = Power.BRIGHTNESS_DIM;
1440 break;
1441 case 0:
1442 nominalCurrentValue = Power.BRIGHTNESS_OFF;
1443 break;
1444 case SCREEN_BRIGHT_BIT:
1445 default:
1446 // not possible
1447 nominalCurrentValue = (int)mScreenBrightness.curValue;
1448 break;
1449 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001450 if ((newState & SCREEN_BRIGHT_BIT) == 0) {
1451 // dim or turn off backlight, depending on if the screen is on
1452 // the scale is because the brightness ramp isn't linear and this biases
1453 // it so the later parts take longer.
1454 final float scale = 1.5f;
1455 float ratio = (((float)Power.BRIGHTNESS_DIM)/preferredBrightness);
1456 if (ratio > 1.0f) ratio = 1.0f;
1457 if ((newState & SCREEN_ON_BIT) == 0) {
1458 int steps;
1459 if ((oldState & SCREEN_BRIGHT_BIT) != 0) {
1460 // was bright
1461 steps = ANIM_STEPS;
1462 } else {
1463 // was dim
1464 steps = (int)(ANIM_STEPS*ratio*scale);
1465 }
1466 mScreenBrightness.setTargetLocked(Power.BRIGHTNESS_OFF,
Joe Onorato128e7292009-03-24 18:41:31 -07001467 steps, INITIAL_SCREEN_BRIGHTNESS, nominalCurrentValue);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001468 } else {
1469 int steps;
1470 if ((oldState & SCREEN_ON_BIT) != 0) {
1471 // was bright
1472 steps = (int)(ANIM_STEPS*(1.0f-ratio)*scale);
1473 } else {
1474 // was dim
1475 steps = (int)(ANIM_STEPS*ratio);
1476 }
1477 if (mStayOnConditions != 0 && mBatteryService.isPowered(mStayOnConditions)) {
1478 // If the "stay on while plugged in" option is
1479 // turned on, then the screen will often not
1480 // automatically turn off while plugged in. To
1481 // still have a sense of when it is inactive, we
1482 // will then count going dim as turning off.
1483 mScreenOffTime = SystemClock.elapsedRealtime();
1484 }
1485 mScreenBrightness.setTargetLocked(Power.BRIGHTNESS_DIM,
Joe Onorato128e7292009-03-24 18:41:31 -07001486 steps, INITIAL_SCREEN_BRIGHTNESS, nominalCurrentValue);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001487 }
1488 } else {
1489 mScreenBrightness.setTargetLocked(preferredBrightness,
Joe Onorato128e7292009-03-24 18:41:31 -07001490 ANIM_STEPS, INITIAL_SCREEN_BRIGHTNESS, nominalCurrentValue);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001491 }
1492 startAnimation = true;
1493 } else {
1494 if ((newState & SCREEN_BRIGHT_BIT) == 0) {
1495 // dim or turn off backlight, depending on if the screen is on
1496 if ((newState & SCREEN_ON_BIT) == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001497 offMask |= SCREEN_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001498 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001499 dimMask |= SCREEN_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001500 }
1501 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001502 onMask |= SCREEN_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001503 }
1504 }
1505 }
1506
1507 if (startAnimation) {
1508 if (mSpew) {
1509 Log.i(TAG, "Scheduling light animator!");
1510 }
1511 mHandler.removeCallbacks(mLightAnimator);
1512 mHandler.post(mLightAnimator);
1513 }
1514
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001515 if (offMask != 0) {
1516 //Log.i(TAG, "Setting brightess off: " + offMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001517 setLightBrightness(offMask, Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001518 }
1519 if (dimMask != 0) {
1520 int brightness = Power.BRIGHTNESS_DIM;
1521 if ((newState & BATTERY_LOW_BIT) != 0 &&
1522 brightness > Power.BRIGHTNESS_LOW_BATTERY) {
1523 brightness = Power.BRIGHTNESS_LOW_BATTERY;
1524 }
1525 //Log.i(TAG, "Setting brightess dim " + brightness + ": " + offMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001526 setLightBrightness(dimMask, brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001527 }
1528 if (onMask != 0) {
1529 int brightness = getPreferredBrightness();
1530 if ((newState & BATTERY_LOW_BIT) != 0 &&
1531 brightness > Power.BRIGHTNESS_LOW_BATTERY) {
1532 brightness = Power.BRIGHTNESS_LOW_BATTERY;
1533 }
1534 //Log.i(TAG, "Setting brightess on " + brightness + ": " + onMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001535 setLightBrightness(onMask, brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001536 }
The Android Open Source Project10592532009-03-18 17:39:46 -07001537 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001538
The Android Open Source Project10592532009-03-18 17:39:46 -07001539 private void setLightBrightness(int mask, int value) {
1540 if ((mask & SCREEN_BRIGHT_BIT) != 0) {
1541 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_BACKLIGHT, value);
1542 }
1543 if ((mask & BUTTON_BRIGHT_BIT) != 0) {
1544 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_BUTTONS, value);
1545 }
1546 if ((mask & KEYBOARD_BRIGHT_BIT) != 0) {
1547 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_KEYBOARD, value);
1548 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001549 }
1550
1551 class BrightnessState {
1552 final int mask;
1553
1554 boolean initialized;
1555 int targetValue;
1556 float curValue;
1557 float delta;
1558 boolean animating;
1559
1560 BrightnessState(int m) {
1561 mask = m;
1562 }
1563
1564 public void dump(PrintWriter pw, String prefix) {
1565 pw.println(prefix + "animating=" + animating
1566 + " targetValue=" + targetValue
1567 + " curValue=" + curValue
1568 + " delta=" + delta);
1569 }
1570
Joe Onorato128e7292009-03-24 18:41:31 -07001571 void setTargetLocked(int target, int stepsToTarget, int initialValue,
1572 int nominalCurrentValue) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001573 if (!initialized) {
1574 initialized = true;
1575 curValue = (float)initialValue;
1576 }
1577 targetValue = target;
Joe Onorato128e7292009-03-24 18:41:31 -07001578 delta = (targetValue-nominalCurrentValue) / stepsToTarget;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001579 if (mSpew) {
Joe Onorato128e7292009-03-24 18:41:31 -07001580 String noticeMe = nominalCurrentValue == curValue ? "" : " ******************";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001581 Log.i(TAG, "Setting target " + mask + ": cur=" + curValue
Joe Onorato128e7292009-03-24 18:41:31 -07001582 + " target=" + targetValue + " delta=" + delta
1583 + " nominalCurrentValue=" + nominalCurrentValue
1584 + noticeMe);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001585 }
1586 animating = true;
1587 }
1588
1589 boolean stepLocked() {
1590 if (!animating) return false;
1591 if (false && mSpew) {
1592 Log.i(TAG, "Step target " + mask + ": cur=" + curValue
1593 + " target=" + targetValue + " delta=" + delta);
1594 }
1595 curValue += delta;
1596 int curIntValue = (int)curValue;
1597 boolean more = true;
1598 if (delta == 0) {
1599 more = false;
1600 } else if (delta > 0) {
1601 if (curIntValue >= targetValue) {
1602 curValue = curIntValue = targetValue;
1603 more = false;
1604 }
1605 } else {
1606 if (curIntValue <= targetValue) {
1607 curValue = curIntValue = targetValue;
1608 more = false;
1609 }
1610 }
1611 //Log.i(TAG, "Animating brightess " + curIntValue + ": " + mask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001612 setLightBrightness(mask, curIntValue);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001613 animating = more;
1614 if (!more) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001615 if (mask == SCREEN_BRIGHT_BIT && curIntValue == Power.BRIGHTNESS_OFF) {
Joe Onorato128e7292009-03-24 18:41:31 -07001616 screenOffFinishedAnimatingLocked(mOffBecauseOfUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001617 }
1618 }
1619 return more;
1620 }
1621 }
1622
1623 private class LightAnimator implements Runnable {
1624 public void run() {
1625 synchronized (mLocks) {
1626 long now = SystemClock.uptimeMillis();
1627 boolean more = mScreenBrightness.stepLocked();
1628 if (mKeyboardBrightness.stepLocked()) {
1629 more = true;
1630 }
1631 if (mButtonBrightness.stepLocked()) {
1632 more = true;
1633 }
1634 if (more) {
1635 mHandler.postAtTime(mLightAnimator, now+(1000/60));
1636 }
1637 }
1638 }
1639 }
1640
1641 private int getPreferredBrightness() {
1642 try {
1643 if (mScreenBrightnessOverride >= 0) {
1644 return mScreenBrightnessOverride;
1645 }
1646 final int brightness = Settings.System.getInt(mContext.getContentResolver(),
1647 SCREEN_BRIGHTNESS);
1648 // Don't let applications turn the screen all the way off
1649 return Math.max(brightness, Power.BRIGHTNESS_DIM);
1650 } catch (SettingNotFoundException snfe) {
1651 return Power.BRIGHTNESS_ON;
1652 }
1653 }
1654
1655 boolean screenIsOn() {
1656 synchronized (mLocks) {
1657 return (mPowerState & SCREEN_ON_BIT) != 0;
1658 }
1659 }
1660
1661 boolean screenIsBright() {
1662 synchronized (mLocks) {
1663 return (mPowerState & SCREEN_BRIGHT) == SCREEN_BRIGHT;
1664 }
1665 }
1666
1667 public void userActivityWithForce(long time, boolean noChangeLights, boolean force) {
1668 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1669 userActivity(time, noChangeLights, OTHER_EVENT, force);
1670 }
1671
1672 public void userActivity(long time, boolean noChangeLights) {
1673 userActivity(time, noChangeLights, OTHER_EVENT, false);
1674 }
1675
1676 public void userActivity(long time, boolean noChangeLights, int eventType) {
1677 userActivity(time, noChangeLights, eventType, false);
1678 }
1679
1680 public void userActivity(long time, boolean noChangeLights, int eventType, boolean force) {
1681 //mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1682
1683 if (((mPokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0)
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07001684 && (eventType == CHEEK_EVENT || eventType == TOUCH_EVENT)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001685 if (false) {
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07001686 Log.d(TAG, "dropping cheek or short event mPokey=0x" + Integer.toHexString(mPokey));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001687 }
1688 return;
1689 }
1690
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07001691 if (((mPokey & POKE_LOCK_IGNORE_TOUCH_AND_CHEEK_EVENTS) != 0)
1692 && (eventType == TOUCH_EVENT || eventType == TOUCH_UP_EVENT
1693 || eventType == LONG_TOUCH_EVENT || eventType == CHEEK_EVENT)) {
1694 if (false) {
1695 Log.d(TAG, "dropping touch mPokey=0x" + Integer.toHexString(mPokey));
1696 }
1697 return;
1698 }
1699
1700
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001701 if (false) {
1702 if (((mPokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0)) {
1703 Log.d(TAG, "userActivity !!!");//, new RuntimeException());
1704 } else {
1705 Log.d(TAG, "mPokey=0x" + Integer.toHexString(mPokey));
1706 }
1707 }
1708
1709 synchronized (mLocks) {
1710 if (mSpew) {
1711 Log.d(TAG, "userActivity mLastEventTime=" + mLastEventTime + " time=" + time
1712 + " mUserActivityAllowed=" + mUserActivityAllowed
1713 + " mUserState=0x" + Integer.toHexString(mUserState)
1714 + " mWakeLockState=0x" + Integer.toHexString(mWakeLockState));
1715 }
1716 if (mLastEventTime <= time || force) {
1717 mLastEventTime = time;
1718 if (mUserActivityAllowed || force) {
1719 // Only turn on button backlights if a button was pressed.
1720 if (eventType == BUTTON_EVENT) {
1721 mUserState = (mKeyboardVisible ? ALL_BRIGHT : SCREEN_BUTTON_BRIGHT);
1722 } else {
1723 // don't clear button/keyboard backlights when the screen is touched.
1724 mUserState |= SCREEN_BRIGHT;
1725 }
1726
1727 reactivateWakeLocksLocked();
1728 mWakeLockState = mLocks.gatherState();
1729 setPowerState(mUserState | mWakeLockState, noChangeLights, true);
1730 setTimeoutLocked(time, SCREEN_BRIGHT);
1731 }
1732 }
1733 }
1734 }
1735
1736 /**
1737 * The user requested that we go to sleep (probably with the power button).
1738 * This overrides all wake locks that are held.
1739 */
1740 public void goToSleep(long time)
1741 {
1742 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1743 synchronized (mLocks) {
1744 goToSleepLocked(time);
1745 }
1746 }
1747
1748 /**
1749 * Returns the time the screen has been on since boot, in millis.
1750 * @return screen on time
1751 */
1752 public long getScreenOnTime() {
1753 synchronized (mLocks) {
1754 if (mScreenOnStartTime == 0) {
1755 return mScreenOnTime;
1756 } else {
1757 return SystemClock.elapsedRealtime() - mScreenOnStartTime + mScreenOnTime;
1758 }
1759 }
1760 }
1761
1762 private void goToSleepLocked(long time) {
1763
1764 if (mLastEventTime <= time) {
1765 mLastEventTime = time;
1766 // cancel all of the wake locks
1767 mWakeLockState = SCREEN_OFF;
1768 int N = mLocks.size();
1769 int numCleared = 0;
1770 for (int i=0; i<N; i++) {
1771 WakeLock wl = mLocks.get(i);
1772 if (isScreenLock(wl.flags)) {
1773 mLocks.get(i).activated = false;
1774 numCleared++;
1775 }
1776 }
1777 EventLog.writeEvent(LOG_POWER_SLEEP_REQUESTED, numCleared);
Joe Onorato128e7292009-03-24 18:41:31 -07001778 mStillNeedSleepNotification = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001779 mUserState = SCREEN_OFF;
1780 setPowerState(SCREEN_OFF, false, true);
1781 cancelTimerLocked();
1782 }
1783 }
1784
1785 public long timeSinceScreenOn() {
1786 synchronized (mLocks) {
1787 if ((mPowerState & SCREEN_ON_BIT) != 0) {
1788 return 0;
1789 }
1790 return SystemClock.elapsedRealtime() - mScreenOffTime;
1791 }
1792 }
1793
1794 public void setKeyboardVisibility(boolean visible) {
1795 mKeyboardVisible = visible;
1796 }
1797
1798 /**
1799 * When the keyguard is up, it manages the power state, and userActivity doesn't do anything.
1800 */
1801 public void enableUserActivity(boolean enabled) {
1802 synchronized (mLocks) {
1803 mUserActivityAllowed = enabled;
1804 mLastEventTime = SystemClock.uptimeMillis(); // we might need to pass this in
1805 }
1806 }
1807
1808 /** Sets the screen off timeouts:
1809 * mKeylightDelay
1810 * mDimDelay
1811 * mScreenOffDelay
1812 * */
1813 private void setScreenOffTimeoutsLocked() {
1814 if ((mPokey & POKE_LOCK_SHORT_TIMEOUT) != 0) {
1815 mKeylightDelay = mShortKeylightDelay; // Configurable via Gservices
1816 mDimDelay = -1;
1817 mScreenOffDelay = 0;
1818 } else if ((mPokey & POKE_LOCK_MEDIUM_TIMEOUT) != 0) {
1819 mKeylightDelay = MEDIUM_KEYLIGHT_DELAY;
1820 mDimDelay = -1;
1821 mScreenOffDelay = 0;
1822 } else {
1823 int totalDelay = mTotalDelaySetting;
1824 mKeylightDelay = LONG_KEYLIGHT_DELAY;
1825 if (totalDelay < 0) {
1826 mScreenOffDelay = Integer.MAX_VALUE;
1827 } else if (mKeylightDelay < totalDelay) {
1828 // subtract the time that the keylight delay. This will give us the
1829 // remainder of the time that we need to sleep to get the accurate
1830 // screen off timeout.
1831 mScreenOffDelay = totalDelay - mKeylightDelay;
1832 } else {
1833 mScreenOffDelay = 0;
1834 }
1835 if (mDimScreen && totalDelay >= (LONG_KEYLIGHT_DELAY + LONG_DIM_TIME)) {
1836 mDimDelay = mScreenOffDelay - LONG_DIM_TIME;
1837 mScreenOffDelay = LONG_DIM_TIME;
1838 } else {
1839 mDimDelay = -1;
1840 }
1841 }
1842 if (mSpew) {
1843 Log.d(TAG, "setScreenOffTimeouts mKeylightDelay=" + mKeylightDelay
1844 + " mDimDelay=" + mDimDelay + " mScreenOffDelay=" + mScreenOffDelay
1845 + " mDimScreen=" + mDimScreen);
1846 }
1847 }
1848
1849 /**
1850 * Refreshes cached Gservices settings. Called once on startup, and
1851 * on subsequent Settings.Gservices.CHANGED_ACTION broadcasts (see
1852 * GservicesChangedReceiver).
1853 */
1854 private void updateGservicesValues() {
1855 mShortKeylightDelay = Settings.Gservices.getInt(
1856 mContext.getContentResolver(),
1857 Settings.Gservices.SHORT_KEYLIGHT_DELAY_MS,
1858 SHORT_KEYLIGHT_DELAY_DEFAULT);
1859 // Log.i(TAG, "updateGservicesValues(): mShortKeylightDelay now " + mShortKeylightDelay);
1860 }
1861
1862 /**
1863 * Receiver for the Gservices.CHANGED_ACTION broadcast intent,
1864 * which tells us we need to refresh our cached Gservices settings.
1865 */
1866 private class GservicesChangedReceiver extends BroadcastReceiver {
1867 @Override
1868 public void onReceive(Context context, Intent intent) {
1869 // Log.i(TAG, "GservicesChangedReceiver.onReceive(): " + intent);
1870 updateGservicesValues();
1871 }
1872 }
1873
1874 private class LockList extends ArrayList<WakeLock>
1875 {
1876 void addLock(WakeLock wl)
1877 {
1878 int index = getIndex(wl.binder);
1879 if (index < 0) {
1880 this.add(wl);
1881 }
1882 }
1883
1884 WakeLock removeLock(IBinder binder)
1885 {
1886 int index = getIndex(binder);
1887 if (index >= 0) {
1888 return this.remove(index);
1889 } else {
1890 return null;
1891 }
1892 }
1893
1894 int getIndex(IBinder binder)
1895 {
1896 int N = this.size();
1897 for (int i=0; i<N; i++) {
1898 if (this.get(i).binder == binder) {
1899 return i;
1900 }
1901 }
1902 return -1;
1903 }
1904
1905 int gatherState()
1906 {
1907 int result = 0;
1908 int N = this.size();
1909 for (int i=0; i<N; i++) {
1910 WakeLock wl = this.get(i);
1911 if (wl.activated) {
1912 if (isScreenLock(wl.flags)) {
1913 result |= wl.minState;
1914 }
1915 }
1916 }
1917 return result;
1918 }
1919 }
1920
1921 void setPolicy(WindowManagerPolicy p) {
1922 synchronized (mLocks) {
1923 mPolicy = p;
1924 mLocks.notifyAll();
1925 }
1926 }
1927
1928 WindowManagerPolicy getPolicyLocked() {
1929 while (mPolicy == null || !mDoneBooting) {
1930 try {
1931 mLocks.wait();
1932 } catch (InterruptedException e) {
1933 // Ignore
1934 }
1935 }
1936 return mPolicy;
1937 }
1938
1939 void systemReady() {
1940 synchronized (mLocks) {
1941 Log.d(TAG, "system ready!");
1942 mDoneBooting = true;
1943 userActivity(SystemClock.uptimeMillis(), false, BUTTON_EVENT, true);
1944 updateWakeLockLocked();
1945 mLocks.notifyAll();
1946 }
1947 }
1948
1949 public void monitor() {
1950 synchronized (mLocks) { }
1951 }
1952}