blob: 9c6e9dcd68970c1763306f7f068536dc9339a81f [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 {
Dianne Hackborn617f8772009-03-31 15:04:46 -07001304 mBatteryStats.noteScreenBrightness(
1305 getPreferredBrightness());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001306 mBatteryStats.noteScreenOn();
1307 } catch (RemoteException e) {
1308 Log.w(TAG, "RemoteException calling noteScreenOn on BatteryStatsService", e);
1309 } finally {
1310 Binder.restoreCallingIdentity(identity);
1311 }
1312 } else {
1313 Power.setScreenState(false);
1314 // But continue as if we really did turn the screen on...
1315 err = 0;
1316 }
1317
1318 mScreenOnStartTime = SystemClock.elapsedRealtime();
1319 mLastTouchDown = 0;
1320 mTotalTouchDownTime = 0;
1321 mTouchCycles = 0;
1322 EventLog.writeEvent(LOG_POWER_SCREEN_STATE, 1, becauseOfUser ? 1 : 0,
1323 mTotalTouchDownTime, mTouchCycles);
1324 if (err == 0) {
1325 mPowerState |= SCREEN_ON_BIT;
1326 sendNotificationLocked(true, -1);
1327 }
1328 } else {
1329 mScreenOffTime = SystemClock.elapsedRealtime();
1330 long identity = Binder.clearCallingIdentity();
1331 try {
1332 mBatteryStats.noteScreenOff();
1333 } catch (RemoteException e) {
1334 Log.w(TAG, "RemoteException calling noteScreenOff on BatteryStatsService", e);
1335 } finally {
1336 Binder.restoreCallingIdentity(identity);
1337 }
1338 mPowerState &= ~SCREEN_ON_BIT;
1339 if (!mScreenBrightness.animating) {
Joe Onorato128e7292009-03-24 18:41:31 -07001340 err = screenOffFinishedAnimatingLocked(becauseOfUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001341 } else {
1342 mOffBecauseOfUser = becauseOfUser;
1343 err = 0;
1344 mLastTouchDown = 0;
1345 }
1346 }
1347 }
1348 }
1349 }
1350
Joe Onorato128e7292009-03-24 18:41:31 -07001351 private int screenOffFinishedAnimatingLocked(boolean becauseOfUser) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001352 // I don't think we need to check the current state here because all of these
1353 // Power.setScreenState and sendNotificationLocked can both handle being
1354 // called multiple times in the same state. -joeo
1355 EventLog.writeEvent(LOG_POWER_SCREEN_STATE, 0, becauseOfUser ? 1 : 0,
1356 mTotalTouchDownTime, mTouchCycles);
1357 mLastTouchDown = 0;
1358 int err = Power.setScreenState(false);
1359 if (mScreenOnStartTime != 0) {
1360 mScreenOnTime += SystemClock.elapsedRealtime() - mScreenOnStartTime;
1361 mScreenOnStartTime = 0;
1362 }
1363 if (err == 0) {
1364 int why = becauseOfUser
1365 ? WindowManagerPolicy.OFF_BECAUSE_OF_USER
1366 : WindowManagerPolicy.OFF_BECAUSE_OF_TIMEOUT;
1367 sendNotificationLocked(false, why);
1368 }
1369 return err;
1370 }
1371
1372 private boolean batteryIsLow() {
1373 return (!mIsPowered &&
1374 mBatteryService.getBatteryLevel() <= Power.LOW_BATTERY_THRESHOLD);
1375 }
1376
The Android Open Source Project10592532009-03-18 17:39:46 -07001377 private void updateLightsLocked(int newState, int forceState) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001378 final int oldState = mPowerState;
1379 final int realDifference = (newState ^ oldState);
1380 final int difference = realDifference | forceState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001381 if (difference == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001382 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001383 }
1384
1385 int offMask = 0;
1386 int dimMask = 0;
1387 int onMask = 0;
1388
1389 int preferredBrightness = getPreferredBrightness();
1390 boolean startAnimation = false;
1391
1392 if ((difference & KEYBOARD_BRIGHT_BIT) != 0) {
1393 if (ANIMATE_KEYBOARD_LIGHTS) {
1394 if ((newState & KEYBOARD_BRIGHT_BIT) == 0) {
1395 mKeyboardBrightness.setTargetLocked(Power.BRIGHTNESS_OFF,
Joe Onorato128e7292009-03-24 18:41:31 -07001396 ANIM_STEPS, INITIAL_KEYBOARD_BRIGHTNESS,
1397 preferredBrightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001398 } else {
1399 mKeyboardBrightness.setTargetLocked(preferredBrightness,
Joe Onorato128e7292009-03-24 18:41:31 -07001400 ANIM_STEPS, INITIAL_KEYBOARD_BRIGHTNESS,
1401 Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001402 }
1403 startAnimation = true;
1404 } else {
1405 if ((newState & KEYBOARD_BRIGHT_BIT) == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001406 offMask |= KEYBOARD_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001407 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001408 onMask |= KEYBOARD_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001409 }
1410 }
1411 }
1412
1413 if ((difference & BUTTON_BRIGHT_BIT) != 0) {
1414 if (ANIMATE_BUTTON_LIGHTS) {
1415 if ((newState & BUTTON_BRIGHT_BIT) == 0) {
1416 mButtonBrightness.setTargetLocked(Power.BRIGHTNESS_OFF,
Joe Onorato128e7292009-03-24 18:41:31 -07001417 ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
1418 preferredBrightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001419 } else {
1420 mButtonBrightness.setTargetLocked(preferredBrightness,
Joe Onorato128e7292009-03-24 18:41:31 -07001421 ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
1422 Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001423 }
1424 startAnimation = true;
1425 } else {
1426 if ((newState & BUTTON_BRIGHT_BIT) == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001427 offMask |= BUTTON_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001428 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001429 onMask |= BUTTON_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001430 }
1431 }
1432 }
1433
1434 if ((difference & (SCREEN_ON_BIT | SCREEN_BRIGHT_BIT)) != 0) {
1435 if (ANIMATE_SCREEN_LIGHTS) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001436 int nominalCurrentValue = -1;
1437 // If there was an actual difference in the light state, then
1438 // figure out the "ideal" current value based on the previous
1439 // state. Otherwise, this is a change due to the brightness
1440 // override, so we want to animate from whatever the current
1441 // value is.
1442 if ((realDifference & (SCREEN_ON_BIT | SCREEN_BRIGHT_BIT)) != 0) {
1443 switch (oldState & (SCREEN_BRIGHT_BIT|SCREEN_ON_BIT)) {
1444 case SCREEN_BRIGHT_BIT | SCREEN_ON_BIT:
1445 nominalCurrentValue = preferredBrightness;
1446 break;
1447 case SCREEN_ON_BIT:
1448 nominalCurrentValue = Power.BRIGHTNESS_DIM;
1449 break;
1450 case 0:
1451 nominalCurrentValue = Power.BRIGHTNESS_OFF;
1452 break;
1453 case SCREEN_BRIGHT_BIT:
1454 default:
1455 // not possible
1456 nominalCurrentValue = (int)mScreenBrightness.curValue;
1457 break;
1458 }
Joe Onorato128e7292009-03-24 18:41:31 -07001459 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001460 int brightness = preferredBrightness;
1461 int steps = ANIM_STEPS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001462 if ((newState & SCREEN_BRIGHT_BIT) == 0) {
1463 // dim or turn off backlight, depending on if the screen is on
1464 // the scale is because the brightness ramp isn't linear and this biases
1465 // it so the later parts take longer.
1466 final float scale = 1.5f;
1467 float ratio = (((float)Power.BRIGHTNESS_DIM)/preferredBrightness);
1468 if (ratio > 1.0f) ratio = 1.0f;
1469 if ((newState & SCREEN_ON_BIT) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001470 if ((oldState & SCREEN_BRIGHT_BIT) != 0) {
1471 // was bright
1472 steps = ANIM_STEPS;
1473 } else {
1474 // was dim
1475 steps = (int)(ANIM_STEPS*ratio*scale);
1476 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001477 brightness = Power.BRIGHTNESS_OFF;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001478 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001479 if ((oldState & SCREEN_ON_BIT) != 0) {
1480 // was bright
1481 steps = (int)(ANIM_STEPS*(1.0f-ratio)*scale);
1482 } else {
1483 // was dim
1484 steps = (int)(ANIM_STEPS*ratio);
1485 }
1486 if (mStayOnConditions != 0 && mBatteryService.isPowered(mStayOnConditions)) {
1487 // If the "stay on while plugged in" option is
1488 // turned on, then the screen will often not
1489 // automatically turn off while plugged in. To
1490 // still have a sense of when it is inactive, we
1491 // will then count going dim as turning off.
1492 mScreenOffTime = SystemClock.elapsedRealtime();
1493 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001494 brightness = Power.BRIGHTNESS_DIM;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001495 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001496 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001497 long identity = Binder.clearCallingIdentity();
1498 try {
1499 mBatteryStats.noteScreenBrightness(brightness);
1500 } catch (RemoteException e) {
1501 // Nothing interesting to do.
1502 } finally {
1503 Binder.restoreCallingIdentity(identity);
1504 }
1505 mScreenBrightness.setTargetLocked(brightness,
1506 steps, INITIAL_SCREEN_BRIGHTNESS, nominalCurrentValue);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001507 startAnimation = true;
1508 } else {
1509 if ((newState & SCREEN_BRIGHT_BIT) == 0) {
1510 // dim or turn off backlight, depending on if the screen is on
1511 if ((newState & SCREEN_ON_BIT) == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001512 offMask |= SCREEN_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001513 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001514 dimMask |= SCREEN_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001515 }
1516 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001517 onMask |= SCREEN_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001518 }
1519 }
1520 }
1521
1522 if (startAnimation) {
1523 if (mSpew) {
1524 Log.i(TAG, "Scheduling light animator!");
1525 }
1526 mHandler.removeCallbacks(mLightAnimator);
1527 mHandler.post(mLightAnimator);
1528 }
1529
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001530 if (offMask != 0) {
1531 //Log.i(TAG, "Setting brightess off: " + offMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001532 setLightBrightness(offMask, Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001533 }
1534 if (dimMask != 0) {
1535 int brightness = Power.BRIGHTNESS_DIM;
1536 if ((newState & BATTERY_LOW_BIT) != 0 &&
1537 brightness > Power.BRIGHTNESS_LOW_BATTERY) {
1538 brightness = Power.BRIGHTNESS_LOW_BATTERY;
1539 }
1540 //Log.i(TAG, "Setting brightess dim " + brightness + ": " + offMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001541 setLightBrightness(dimMask, brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001542 }
1543 if (onMask != 0) {
1544 int brightness = getPreferredBrightness();
1545 if ((newState & BATTERY_LOW_BIT) != 0 &&
1546 brightness > Power.BRIGHTNESS_LOW_BATTERY) {
1547 brightness = Power.BRIGHTNESS_LOW_BATTERY;
1548 }
1549 //Log.i(TAG, "Setting brightess on " + brightness + ": " + onMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001550 setLightBrightness(onMask, brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001551 }
The Android Open Source Project10592532009-03-18 17:39:46 -07001552 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001553
The Android Open Source Project10592532009-03-18 17:39:46 -07001554 private void setLightBrightness(int mask, int value) {
1555 if ((mask & SCREEN_BRIGHT_BIT) != 0) {
1556 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_BACKLIGHT, value);
1557 }
1558 if ((mask & BUTTON_BRIGHT_BIT) != 0) {
1559 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_BUTTONS, value);
1560 }
1561 if ((mask & KEYBOARD_BRIGHT_BIT) != 0) {
1562 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_KEYBOARD, value);
1563 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001564 }
1565
1566 class BrightnessState {
1567 final int mask;
1568
1569 boolean initialized;
1570 int targetValue;
1571 float curValue;
1572 float delta;
1573 boolean animating;
1574
1575 BrightnessState(int m) {
1576 mask = m;
1577 }
1578
1579 public void dump(PrintWriter pw, String prefix) {
1580 pw.println(prefix + "animating=" + animating
1581 + " targetValue=" + targetValue
1582 + " curValue=" + curValue
1583 + " delta=" + delta);
1584 }
1585
Joe Onorato128e7292009-03-24 18:41:31 -07001586 void setTargetLocked(int target, int stepsToTarget, int initialValue,
1587 int nominalCurrentValue) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001588 if (!initialized) {
1589 initialized = true;
1590 curValue = (float)initialValue;
1591 }
1592 targetValue = target;
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001593 delta = (targetValue -
1594 (nominalCurrentValue >= 0 ? nominalCurrentValue : curValue))
1595 / stepsToTarget;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001596 if (mSpew) {
Joe Onorato128e7292009-03-24 18:41:31 -07001597 String noticeMe = nominalCurrentValue == curValue ? "" : " ******************";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001598 Log.i(TAG, "Setting target " + mask + ": cur=" + curValue
Joe Onorato128e7292009-03-24 18:41:31 -07001599 + " target=" + targetValue + " delta=" + delta
1600 + " nominalCurrentValue=" + nominalCurrentValue
1601 + noticeMe);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001602 }
1603 animating = true;
1604 }
1605
1606 boolean stepLocked() {
1607 if (!animating) return false;
1608 if (false && mSpew) {
1609 Log.i(TAG, "Step target " + mask + ": cur=" + curValue
1610 + " target=" + targetValue + " delta=" + delta);
1611 }
1612 curValue += delta;
1613 int curIntValue = (int)curValue;
1614 boolean more = true;
1615 if (delta == 0) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001616 curValue = curIntValue = targetValue;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001617 more = false;
1618 } else if (delta > 0) {
1619 if (curIntValue >= targetValue) {
1620 curValue = curIntValue = targetValue;
1621 more = false;
1622 }
1623 } else {
1624 if (curIntValue <= targetValue) {
1625 curValue = curIntValue = targetValue;
1626 more = false;
1627 }
1628 }
1629 //Log.i(TAG, "Animating brightess " + curIntValue + ": " + mask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001630 setLightBrightness(mask, curIntValue);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001631 animating = more;
1632 if (!more) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001633 if (mask == SCREEN_BRIGHT_BIT && curIntValue == Power.BRIGHTNESS_OFF) {
Joe Onorato128e7292009-03-24 18:41:31 -07001634 screenOffFinishedAnimatingLocked(mOffBecauseOfUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001635 }
1636 }
1637 return more;
1638 }
1639 }
1640
1641 private class LightAnimator implements Runnable {
1642 public void run() {
1643 synchronized (mLocks) {
1644 long now = SystemClock.uptimeMillis();
1645 boolean more = mScreenBrightness.stepLocked();
1646 if (mKeyboardBrightness.stepLocked()) {
1647 more = true;
1648 }
1649 if (mButtonBrightness.stepLocked()) {
1650 more = true;
1651 }
1652 if (more) {
1653 mHandler.postAtTime(mLightAnimator, now+(1000/60));
1654 }
1655 }
1656 }
1657 }
1658
1659 private int getPreferredBrightness() {
1660 try {
1661 if (mScreenBrightnessOverride >= 0) {
1662 return mScreenBrightnessOverride;
1663 }
1664 final int brightness = Settings.System.getInt(mContext.getContentResolver(),
1665 SCREEN_BRIGHTNESS);
1666 // Don't let applications turn the screen all the way off
1667 return Math.max(brightness, Power.BRIGHTNESS_DIM);
1668 } catch (SettingNotFoundException snfe) {
1669 return Power.BRIGHTNESS_ON;
1670 }
1671 }
1672
1673 boolean screenIsOn() {
1674 synchronized (mLocks) {
1675 return (mPowerState & SCREEN_ON_BIT) != 0;
1676 }
1677 }
1678
1679 boolean screenIsBright() {
1680 synchronized (mLocks) {
1681 return (mPowerState & SCREEN_BRIGHT) == SCREEN_BRIGHT;
1682 }
1683 }
1684
1685 public void userActivityWithForce(long time, boolean noChangeLights, boolean force) {
1686 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1687 userActivity(time, noChangeLights, OTHER_EVENT, force);
1688 }
1689
1690 public void userActivity(long time, boolean noChangeLights) {
1691 userActivity(time, noChangeLights, OTHER_EVENT, false);
1692 }
1693
1694 public void userActivity(long time, boolean noChangeLights, int eventType) {
1695 userActivity(time, noChangeLights, eventType, false);
1696 }
1697
1698 public void userActivity(long time, boolean noChangeLights, int eventType, boolean force) {
1699 //mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1700
1701 if (((mPokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0)
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07001702 && (eventType == CHEEK_EVENT || eventType == TOUCH_EVENT)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001703 if (false) {
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07001704 Log.d(TAG, "dropping cheek or short event mPokey=0x" + Integer.toHexString(mPokey));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001705 }
1706 return;
1707 }
1708
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07001709 if (((mPokey & POKE_LOCK_IGNORE_TOUCH_AND_CHEEK_EVENTS) != 0)
1710 && (eventType == TOUCH_EVENT || eventType == TOUCH_UP_EVENT
1711 || eventType == LONG_TOUCH_EVENT || eventType == CHEEK_EVENT)) {
1712 if (false) {
1713 Log.d(TAG, "dropping touch mPokey=0x" + Integer.toHexString(mPokey));
1714 }
1715 return;
1716 }
1717
1718
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001719 if (false) {
1720 if (((mPokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0)) {
1721 Log.d(TAG, "userActivity !!!");//, new RuntimeException());
1722 } else {
1723 Log.d(TAG, "mPokey=0x" + Integer.toHexString(mPokey));
1724 }
1725 }
1726
1727 synchronized (mLocks) {
1728 if (mSpew) {
1729 Log.d(TAG, "userActivity mLastEventTime=" + mLastEventTime + " time=" + time
1730 + " mUserActivityAllowed=" + mUserActivityAllowed
1731 + " mUserState=0x" + Integer.toHexString(mUserState)
1732 + " mWakeLockState=0x" + Integer.toHexString(mWakeLockState));
1733 }
1734 if (mLastEventTime <= time || force) {
1735 mLastEventTime = time;
1736 if (mUserActivityAllowed || force) {
1737 // Only turn on button backlights if a button was pressed.
1738 if (eventType == BUTTON_EVENT) {
1739 mUserState = (mKeyboardVisible ? ALL_BRIGHT : SCREEN_BUTTON_BRIGHT);
1740 } else {
1741 // don't clear button/keyboard backlights when the screen is touched.
1742 mUserState |= SCREEN_BRIGHT;
1743 }
1744
Dianne Hackborn617f8772009-03-31 15:04:46 -07001745 int uid = Binder.getCallingUid();
1746 long ident = Binder.clearCallingIdentity();
1747 try {
1748 mBatteryStats.noteUserActivity(uid, eventType);
1749 } catch (RemoteException e) {
1750 // Ignore
1751 } finally {
1752 Binder.restoreCallingIdentity(ident);
1753 }
1754
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001755 reactivateWakeLocksLocked();
1756 mWakeLockState = mLocks.gatherState();
1757 setPowerState(mUserState | mWakeLockState, noChangeLights, true);
1758 setTimeoutLocked(time, SCREEN_BRIGHT);
1759 }
1760 }
1761 }
1762 }
1763
1764 /**
1765 * The user requested that we go to sleep (probably with the power button).
1766 * This overrides all wake locks that are held.
1767 */
1768 public void goToSleep(long time)
1769 {
1770 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1771 synchronized (mLocks) {
1772 goToSleepLocked(time);
1773 }
1774 }
1775
1776 /**
1777 * Returns the time the screen has been on since boot, in millis.
1778 * @return screen on time
1779 */
1780 public long getScreenOnTime() {
1781 synchronized (mLocks) {
1782 if (mScreenOnStartTime == 0) {
1783 return mScreenOnTime;
1784 } else {
1785 return SystemClock.elapsedRealtime() - mScreenOnStartTime + mScreenOnTime;
1786 }
1787 }
1788 }
1789
1790 private void goToSleepLocked(long time) {
1791
1792 if (mLastEventTime <= time) {
1793 mLastEventTime = time;
1794 // cancel all of the wake locks
1795 mWakeLockState = SCREEN_OFF;
1796 int N = mLocks.size();
1797 int numCleared = 0;
1798 for (int i=0; i<N; i++) {
1799 WakeLock wl = mLocks.get(i);
1800 if (isScreenLock(wl.flags)) {
1801 mLocks.get(i).activated = false;
1802 numCleared++;
1803 }
1804 }
1805 EventLog.writeEvent(LOG_POWER_SLEEP_REQUESTED, numCleared);
Joe Onorato128e7292009-03-24 18:41:31 -07001806 mStillNeedSleepNotification = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001807 mUserState = SCREEN_OFF;
1808 setPowerState(SCREEN_OFF, false, true);
1809 cancelTimerLocked();
1810 }
1811 }
1812
1813 public long timeSinceScreenOn() {
1814 synchronized (mLocks) {
1815 if ((mPowerState & SCREEN_ON_BIT) != 0) {
1816 return 0;
1817 }
1818 return SystemClock.elapsedRealtime() - mScreenOffTime;
1819 }
1820 }
1821
1822 public void setKeyboardVisibility(boolean visible) {
1823 mKeyboardVisible = visible;
1824 }
1825
1826 /**
1827 * When the keyguard is up, it manages the power state, and userActivity doesn't do anything.
1828 */
1829 public void enableUserActivity(boolean enabled) {
1830 synchronized (mLocks) {
1831 mUserActivityAllowed = enabled;
1832 mLastEventTime = SystemClock.uptimeMillis(); // we might need to pass this in
1833 }
1834 }
1835
1836 /** Sets the screen off timeouts:
1837 * mKeylightDelay
1838 * mDimDelay
1839 * mScreenOffDelay
1840 * */
1841 private void setScreenOffTimeoutsLocked() {
1842 if ((mPokey & POKE_LOCK_SHORT_TIMEOUT) != 0) {
1843 mKeylightDelay = mShortKeylightDelay; // Configurable via Gservices
1844 mDimDelay = -1;
1845 mScreenOffDelay = 0;
1846 } else if ((mPokey & POKE_LOCK_MEDIUM_TIMEOUT) != 0) {
1847 mKeylightDelay = MEDIUM_KEYLIGHT_DELAY;
1848 mDimDelay = -1;
1849 mScreenOffDelay = 0;
1850 } else {
1851 int totalDelay = mTotalDelaySetting;
1852 mKeylightDelay = LONG_KEYLIGHT_DELAY;
1853 if (totalDelay < 0) {
1854 mScreenOffDelay = Integer.MAX_VALUE;
1855 } else if (mKeylightDelay < totalDelay) {
1856 // subtract the time that the keylight delay. This will give us the
1857 // remainder of the time that we need to sleep to get the accurate
1858 // screen off timeout.
1859 mScreenOffDelay = totalDelay - mKeylightDelay;
1860 } else {
1861 mScreenOffDelay = 0;
1862 }
1863 if (mDimScreen && totalDelay >= (LONG_KEYLIGHT_DELAY + LONG_DIM_TIME)) {
1864 mDimDelay = mScreenOffDelay - LONG_DIM_TIME;
1865 mScreenOffDelay = LONG_DIM_TIME;
1866 } else {
1867 mDimDelay = -1;
1868 }
1869 }
1870 if (mSpew) {
1871 Log.d(TAG, "setScreenOffTimeouts mKeylightDelay=" + mKeylightDelay
1872 + " mDimDelay=" + mDimDelay + " mScreenOffDelay=" + mScreenOffDelay
1873 + " mDimScreen=" + mDimScreen);
1874 }
1875 }
1876
1877 /**
1878 * Refreshes cached Gservices settings. Called once on startup, and
1879 * on subsequent Settings.Gservices.CHANGED_ACTION broadcasts (see
1880 * GservicesChangedReceiver).
1881 */
1882 private void updateGservicesValues() {
1883 mShortKeylightDelay = Settings.Gservices.getInt(
1884 mContext.getContentResolver(),
1885 Settings.Gservices.SHORT_KEYLIGHT_DELAY_MS,
1886 SHORT_KEYLIGHT_DELAY_DEFAULT);
1887 // Log.i(TAG, "updateGservicesValues(): mShortKeylightDelay now " + mShortKeylightDelay);
1888 }
1889
1890 /**
1891 * Receiver for the Gservices.CHANGED_ACTION broadcast intent,
1892 * which tells us we need to refresh our cached Gservices settings.
1893 */
1894 private class GservicesChangedReceiver extends BroadcastReceiver {
1895 @Override
1896 public void onReceive(Context context, Intent intent) {
1897 // Log.i(TAG, "GservicesChangedReceiver.onReceive(): " + intent);
1898 updateGservicesValues();
1899 }
1900 }
1901
1902 private class LockList extends ArrayList<WakeLock>
1903 {
1904 void addLock(WakeLock wl)
1905 {
1906 int index = getIndex(wl.binder);
1907 if (index < 0) {
1908 this.add(wl);
1909 }
1910 }
1911
1912 WakeLock removeLock(IBinder binder)
1913 {
1914 int index = getIndex(binder);
1915 if (index >= 0) {
1916 return this.remove(index);
1917 } else {
1918 return null;
1919 }
1920 }
1921
1922 int getIndex(IBinder binder)
1923 {
1924 int N = this.size();
1925 for (int i=0; i<N; i++) {
1926 if (this.get(i).binder == binder) {
1927 return i;
1928 }
1929 }
1930 return -1;
1931 }
1932
1933 int gatherState()
1934 {
1935 int result = 0;
1936 int N = this.size();
1937 for (int i=0; i<N; i++) {
1938 WakeLock wl = this.get(i);
1939 if (wl.activated) {
1940 if (isScreenLock(wl.flags)) {
1941 result |= wl.minState;
1942 }
1943 }
1944 }
1945 return result;
1946 }
1947 }
1948
1949 void setPolicy(WindowManagerPolicy p) {
1950 synchronized (mLocks) {
1951 mPolicy = p;
1952 mLocks.notifyAll();
1953 }
1954 }
1955
1956 WindowManagerPolicy getPolicyLocked() {
1957 while (mPolicy == null || !mDoneBooting) {
1958 try {
1959 mLocks.wait();
1960 } catch (InterruptedException e) {
1961 // Ignore
1962 }
1963 }
1964 return mPolicy;
1965 }
1966
1967 void systemReady() {
1968 synchronized (mLocks) {
1969 Log.d(TAG, "system ready!");
1970 mDoneBooting = true;
Dianne Hackborn617f8772009-03-31 15:04:46 -07001971 long identity = Binder.clearCallingIdentity();
1972 try {
1973 mBatteryStats.noteScreenBrightness(getPreferredBrightness());
1974 mBatteryStats.noteScreenOn();
1975 } catch (RemoteException e) {
1976 // Nothing interesting to do.
1977 } finally {
1978 Binder.restoreCallingIdentity(identity);
1979 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001980 userActivity(SystemClock.uptimeMillis(), false, BUTTON_EVENT, true);
1981 updateWakeLockLocked();
1982 mLocks.notifyAll();
1983 }
1984 }
1985
1986 public void monitor() {
1987 synchronized (mLocks) { }
1988 }
1989}