blob: bbca40148ee0a2d0c6a5569120e2251b66584344 [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) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001376 final int oldState = mPowerState;
1377 final int realDifference = (newState ^ oldState);
1378 final int difference = realDifference | forceState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001379 if (difference == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001380 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001381 }
1382
1383 int offMask = 0;
1384 int dimMask = 0;
1385 int onMask = 0;
1386
1387 int preferredBrightness = getPreferredBrightness();
1388 boolean startAnimation = false;
1389
1390 if ((difference & KEYBOARD_BRIGHT_BIT) != 0) {
1391 if (ANIMATE_KEYBOARD_LIGHTS) {
1392 if ((newState & KEYBOARD_BRIGHT_BIT) == 0) {
1393 mKeyboardBrightness.setTargetLocked(Power.BRIGHTNESS_OFF,
Joe Onorato128e7292009-03-24 18:41:31 -07001394 ANIM_STEPS, INITIAL_KEYBOARD_BRIGHTNESS,
1395 preferredBrightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001396 } else {
1397 mKeyboardBrightness.setTargetLocked(preferredBrightness,
Joe Onorato128e7292009-03-24 18:41:31 -07001398 ANIM_STEPS, INITIAL_KEYBOARD_BRIGHTNESS,
1399 Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001400 }
1401 startAnimation = true;
1402 } else {
1403 if ((newState & KEYBOARD_BRIGHT_BIT) == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001404 offMask |= KEYBOARD_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001405 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001406 onMask |= KEYBOARD_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001407 }
1408 }
1409 }
1410
1411 if ((difference & BUTTON_BRIGHT_BIT) != 0) {
1412 if (ANIMATE_BUTTON_LIGHTS) {
1413 if ((newState & BUTTON_BRIGHT_BIT) == 0) {
1414 mButtonBrightness.setTargetLocked(Power.BRIGHTNESS_OFF,
Joe Onorato128e7292009-03-24 18:41:31 -07001415 ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
1416 preferredBrightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001417 } else {
1418 mButtonBrightness.setTargetLocked(preferredBrightness,
Joe Onorato128e7292009-03-24 18:41:31 -07001419 ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
1420 Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001421 }
1422 startAnimation = true;
1423 } else {
1424 if ((newState & BUTTON_BRIGHT_BIT) == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001425 offMask |= BUTTON_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001426 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001427 onMask |= BUTTON_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001428 }
1429 }
1430 }
1431
1432 if ((difference & (SCREEN_ON_BIT | SCREEN_BRIGHT_BIT)) != 0) {
1433 if (ANIMATE_SCREEN_LIGHTS) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001434 int nominalCurrentValue = -1;
1435 // If there was an actual difference in the light state, then
1436 // figure out the "ideal" current value based on the previous
1437 // state. Otherwise, this is a change due to the brightness
1438 // override, so we want to animate from whatever the current
1439 // value is.
1440 if ((realDifference & (SCREEN_ON_BIT | SCREEN_BRIGHT_BIT)) != 0) {
1441 switch (oldState & (SCREEN_BRIGHT_BIT|SCREEN_ON_BIT)) {
1442 case SCREEN_BRIGHT_BIT | SCREEN_ON_BIT:
1443 nominalCurrentValue = preferredBrightness;
1444 break;
1445 case SCREEN_ON_BIT:
1446 nominalCurrentValue = Power.BRIGHTNESS_DIM;
1447 break;
1448 case 0:
1449 nominalCurrentValue = Power.BRIGHTNESS_OFF;
1450 break;
1451 case SCREEN_BRIGHT_BIT:
1452 default:
1453 // not possible
1454 nominalCurrentValue = (int)mScreenBrightness.curValue;
1455 break;
1456 }
Joe Onorato128e7292009-03-24 18:41:31 -07001457 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001458 if ((newState & SCREEN_BRIGHT_BIT) == 0) {
1459 // dim or turn off backlight, depending on if the screen is on
1460 // the scale is because the brightness ramp isn't linear and this biases
1461 // it so the later parts take longer.
1462 final float scale = 1.5f;
1463 float ratio = (((float)Power.BRIGHTNESS_DIM)/preferredBrightness);
1464 if (ratio > 1.0f) ratio = 1.0f;
1465 if ((newState & SCREEN_ON_BIT) == 0) {
1466 int steps;
1467 if ((oldState & SCREEN_BRIGHT_BIT) != 0) {
1468 // was bright
1469 steps = ANIM_STEPS;
1470 } else {
1471 // was dim
1472 steps = (int)(ANIM_STEPS*ratio*scale);
1473 }
1474 mScreenBrightness.setTargetLocked(Power.BRIGHTNESS_OFF,
Joe Onorato128e7292009-03-24 18:41:31 -07001475 steps, INITIAL_SCREEN_BRIGHTNESS, nominalCurrentValue);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001476 } else {
1477 int steps;
1478 if ((oldState & SCREEN_ON_BIT) != 0) {
1479 // was bright
1480 steps = (int)(ANIM_STEPS*(1.0f-ratio)*scale);
1481 } else {
1482 // was dim
1483 steps = (int)(ANIM_STEPS*ratio);
1484 }
1485 if (mStayOnConditions != 0 && mBatteryService.isPowered(mStayOnConditions)) {
1486 // If the "stay on while plugged in" option is
1487 // turned on, then the screen will often not
1488 // automatically turn off while plugged in. To
1489 // still have a sense of when it is inactive, we
1490 // will then count going dim as turning off.
1491 mScreenOffTime = SystemClock.elapsedRealtime();
1492 }
1493 mScreenBrightness.setTargetLocked(Power.BRIGHTNESS_DIM,
Joe Onorato128e7292009-03-24 18:41:31 -07001494 steps, INITIAL_SCREEN_BRIGHTNESS, nominalCurrentValue);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001495 }
1496 } else {
1497 mScreenBrightness.setTargetLocked(preferredBrightness,
Joe Onorato128e7292009-03-24 18:41:31 -07001498 ANIM_STEPS, INITIAL_SCREEN_BRIGHTNESS, nominalCurrentValue);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001499 }
1500 startAnimation = true;
1501 } else {
1502 if ((newState & SCREEN_BRIGHT_BIT) == 0) {
1503 // dim or turn off backlight, depending on if the screen is on
1504 if ((newState & SCREEN_ON_BIT) == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001505 offMask |= SCREEN_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001506 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001507 dimMask |= SCREEN_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001508 }
1509 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001510 onMask |= SCREEN_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001511 }
1512 }
1513 }
1514
1515 if (startAnimation) {
1516 if (mSpew) {
1517 Log.i(TAG, "Scheduling light animator!");
1518 }
1519 mHandler.removeCallbacks(mLightAnimator);
1520 mHandler.post(mLightAnimator);
1521 }
1522
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001523 if (offMask != 0) {
1524 //Log.i(TAG, "Setting brightess off: " + offMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001525 setLightBrightness(offMask, Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001526 }
1527 if (dimMask != 0) {
1528 int brightness = Power.BRIGHTNESS_DIM;
1529 if ((newState & BATTERY_LOW_BIT) != 0 &&
1530 brightness > Power.BRIGHTNESS_LOW_BATTERY) {
1531 brightness = Power.BRIGHTNESS_LOW_BATTERY;
1532 }
1533 //Log.i(TAG, "Setting brightess dim " + brightness + ": " + offMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001534 setLightBrightness(dimMask, brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001535 }
1536 if (onMask != 0) {
1537 int brightness = getPreferredBrightness();
1538 if ((newState & BATTERY_LOW_BIT) != 0 &&
1539 brightness > Power.BRIGHTNESS_LOW_BATTERY) {
1540 brightness = Power.BRIGHTNESS_LOW_BATTERY;
1541 }
1542 //Log.i(TAG, "Setting brightess on " + brightness + ": " + onMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001543 setLightBrightness(onMask, brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001544 }
The Android Open Source Project10592532009-03-18 17:39:46 -07001545 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001546
The Android Open Source Project10592532009-03-18 17:39:46 -07001547 private void setLightBrightness(int mask, int value) {
1548 if ((mask & SCREEN_BRIGHT_BIT) != 0) {
1549 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_BACKLIGHT, value);
1550 }
1551 if ((mask & BUTTON_BRIGHT_BIT) != 0) {
1552 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_BUTTONS, value);
1553 }
1554 if ((mask & KEYBOARD_BRIGHT_BIT) != 0) {
1555 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_KEYBOARD, value);
1556 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001557 }
1558
1559 class BrightnessState {
1560 final int mask;
1561
1562 boolean initialized;
1563 int targetValue;
1564 float curValue;
1565 float delta;
1566 boolean animating;
1567
1568 BrightnessState(int m) {
1569 mask = m;
1570 }
1571
1572 public void dump(PrintWriter pw, String prefix) {
1573 pw.println(prefix + "animating=" + animating
1574 + " targetValue=" + targetValue
1575 + " curValue=" + curValue
1576 + " delta=" + delta);
1577 }
1578
Joe Onorato128e7292009-03-24 18:41:31 -07001579 void setTargetLocked(int target, int stepsToTarget, int initialValue,
1580 int nominalCurrentValue) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001581 if (!initialized) {
1582 initialized = true;
1583 curValue = (float)initialValue;
1584 }
1585 targetValue = target;
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001586 delta = (targetValue -
1587 (nominalCurrentValue >= 0 ? nominalCurrentValue : curValue))
1588 / stepsToTarget;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001589 if (mSpew) {
Joe Onorato128e7292009-03-24 18:41:31 -07001590 String noticeMe = nominalCurrentValue == curValue ? "" : " ******************";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001591 Log.i(TAG, "Setting target " + mask + ": cur=" + curValue
Joe Onorato128e7292009-03-24 18:41:31 -07001592 + " target=" + targetValue + " delta=" + delta
1593 + " nominalCurrentValue=" + nominalCurrentValue
1594 + noticeMe);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001595 }
1596 animating = true;
1597 }
1598
1599 boolean stepLocked() {
1600 if (!animating) return false;
1601 if (false && mSpew) {
1602 Log.i(TAG, "Step target " + mask + ": cur=" + curValue
1603 + " target=" + targetValue + " delta=" + delta);
1604 }
1605 curValue += delta;
1606 int curIntValue = (int)curValue;
1607 boolean more = true;
1608 if (delta == 0) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001609 curValue = curIntValue = targetValue;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001610 more = false;
1611 } else if (delta > 0) {
1612 if (curIntValue >= targetValue) {
1613 curValue = curIntValue = targetValue;
1614 more = false;
1615 }
1616 } else {
1617 if (curIntValue <= targetValue) {
1618 curValue = curIntValue = targetValue;
1619 more = false;
1620 }
1621 }
1622 //Log.i(TAG, "Animating brightess " + curIntValue + ": " + mask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001623 setLightBrightness(mask, curIntValue);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001624 animating = more;
1625 if (!more) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001626 if (mask == SCREEN_BRIGHT_BIT && curIntValue == Power.BRIGHTNESS_OFF) {
Joe Onorato128e7292009-03-24 18:41:31 -07001627 screenOffFinishedAnimatingLocked(mOffBecauseOfUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001628 }
1629 }
1630 return more;
1631 }
1632 }
1633
1634 private class LightAnimator implements Runnable {
1635 public void run() {
1636 synchronized (mLocks) {
1637 long now = SystemClock.uptimeMillis();
1638 boolean more = mScreenBrightness.stepLocked();
1639 if (mKeyboardBrightness.stepLocked()) {
1640 more = true;
1641 }
1642 if (mButtonBrightness.stepLocked()) {
1643 more = true;
1644 }
1645 if (more) {
1646 mHandler.postAtTime(mLightAnimator, now+(1000/60));
1647 }
1648 }
1649 }
1650 }
1651
1652 private int getPreferredBrightness() {
1653 try {
1654 if (mScreenBrightnessOverride >= 0) {
1655 return mScreenBrightnessOverride;
1656 }
1657 final int brightness = Settings.System.getInt(mContext.getContentResolver(),
1658 SCREEN_BRIGHTNESS);
1659 // Don't let applications turn the screen all the way off
1660 return Math.max(brightness, Power.BRIGHTNESS_DIM);
1661 } catch (SettingNotFoundException snfe) {
1662 return Power.BRIGHTNESS_ON;
1663 }
1664 }
1665
1666 boolean screenIsOn() {
1667 synchronized (mLocks) {
1668 return (mPowerState & SCREEN_ON_BIT) != 0;
1669 }
1670 }
1671
1672 boolean screenIsBright() {
1673 synchronized (mLocks) {
1674 return (mPowerState & SCREEN_BRIGHT) == SCREEN_BRIGHT;
1675 }
1676 }
1677
1678 public void userActivityWithForce(long time, boolean noChangeLights, boolean force) {
1679 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1680 userActivity(time, noChangeLights, OTHER_EVENT, force);
1681 }
1682
1683 public void userActivity(long time, boolean noChangeLights) {
1684 userActivity(time, noChangeLights, OTHER_EVENT, false);
1685 }
1686
1687 public void userActivity(long time, boolean noChangeLights, int eventType) {
1688 userActivity(time, noChangeLights, eventType, false);
1689 }
1690
1691 public void userActivity(long time, boolean noChangeLights, int eventType, boolean force) {
1692 //mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1693
1694 if (((mPokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0)
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07001695 && (eventType == CHEEK_EVENT || eventType == TOUCH_EVENT)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001696 if (false) {
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07001697 Log.d(TAG, "dropping cheek or short event mPokey=0x" + Integer.toHexString(mPokey));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001698 }
1699 return;
1700 }
1701
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07001702 if (((mPokey & POKE_LOCK_IGNORE_TOUCH_AND_CHEEK_EVENTS) != 0)
1703 && (eventType == TOUCH_EVENT || eventType == TOUCH_UP_EVENT
1704 || eventType == LONG_TOUCH_EVENT || eventType == CHEEK_EVENT)) {
1705 if (false) {
1706 Log.d(TAG, "dropping touch mPokey=0x" + Integer.toHexString(mPokey));
1707 }
1708 return;
1709 }
1710
1711
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001712 if (false) {
1713 if (((mPokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0)) {
1714 Log.d(TAG, "userActivity !!!");//, new RuntimeException());
1715 } else {
1716 Log.d(TAG, "mPokey=0x" + Integer.toHexString(mPokey));
1717 }
1718 }
1719
1720 synchronized (mLocks) {
1721 if (mSpew) {
1722 Log.d(TAG, "userActivity mLastEventTime=" + mLastEventTime + " time=" + time
1723 + " mUserActivityAllowed=" + mUserActivityAllowed
1724 + " mUserState=0x" + Integer.toHexString(mUserState)
1725 + " mWakeLockState=0x" + Integer.toHexString(mWakeLockState));
1726 }
1727 if (mLastEventTime <= time || force) {
1728 mLastEventTime = time;
1729 if (mUserActivityAllowed || force) {
1730 // Only turn on button backlights if a button was pressed.
1731 if (eventType == BUTTON_EVENT) {
1732 mUserState = (mKeyboardVisible ? ALL_BRIGHT : SCREEN_BUTTON_BRIGHT);
1733 } else {
1734 // don't clear button/keyboard backlights when the screen is touched.
1735 mUserState |= SCREEN_BRIGHT;
1736 }
1737
1738 reactivateWakeLocksLocked();
1739 mWakeLockState = mLocks.gatherState();
1740 setPowerState(mUserState | mWakeLockState, noChangeLights, true);
1741 setTimeoutLocked(time, SCREEN_BRIGHT);
1742 }
1743 }
1744 }
1745 }
1746
1747 /**
1748 * The user requested that we go to sleep (probably with the power button).
1749 * This overrides all wake locks that are held.
1750 */
1751 public void goToSleep(long time)
1752 {
1753 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1754 synchronized (mLocks) {
1755 goToSleepLocked(time);
1756 }
1757 }
1758
1759 /**
1760 * Returns the time the screen has been on since boot, in millis.
1761 * @return screen on time
1762 */
1763 public long getScreenOnTime() {
1764 synchronized (mLocks) {
1765 if (mScreenOnStartTime == 0) {
1766 return mScreenOnTime;
1767 } else {
1768 return SystemClock.elapsedRealtime() - mScreenOnStartTime + mScreenOnTime;
1769 }
1770 }
1771 }
1772
1773 private void goToSleepLocked(long time) {
1774
1775 if (mLastEventTime <= time) {
1776 mLastEventTime = time;
1777 // cancel all of the wake locks
1778 mWakeLockState = SCREEN_OFF;
1779 int N = mLocks.size();
1780 int numCleared = 0;
1781 for (int i=0; i<N; i++) {
1782 WakeLock wl = mLocks.get(i);
1783 if (isScreenLock(wl.flags)) {
1784 mLocks.get(i).activated = false;
1785 numCleared++;
1786 }
1787 }
1788 EventLog.writeEvent(LOG_POWER_SLEEP_REQUESTED, numCleared);
Joe Onorato128e7292009-03-24 18:41:31 -07001789 mStillNeedSleepNotification = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001790 mUserState = SCREEN_OFF;
1791 setPowerState(SCREEN_OFF, false, true);
1792 cancelTimerLocked();
1793 }
1794 }
1795
1796 public long timeSinceScreenOn() {
1797 synchronized (mLocks) {
1798 if ((mPowerState & SCREEN_ON_BIT) != 0) {
1799 return 0;
1800 }
1801 return SystemClock.elapsedRealtime() - mScreenOffTime;
1802 }
1803 }
1804
1805 public void setKeyboardVisibility(boolean visible) {
1806 mKeyboardVisible = visible;
1807 }
1808
1809 /**
1810 * When the keyguard is up, it manages the power state, and userActivity doesn't do anything.
1811 */
1812 public void enableUserActivity(boolean enabled) {
1813 synchronized (mLocks) {
1814 mUserActivityAllowed = enabled;
1815 mLastEventTime = SystemClock.uptimeMillis(); // we might need to pass this in
1816 }
1817 }
1818
1819 /** Sets the screen off timeouts:
1820 * mKeylightDelay
1821 * mDimDelay
1822 * mScreenOffDelay
1823 * */
1824 private void setScreenOffTimeoutsLocked() {
1825 if ((mPokey & POKE_LOCK_SHORT_TIMEOUT) != 0) {
1826 mKeylightDelay = mShortKeylightDelay; // Configurable via Gservices
1827 mDimDelay = -1;
1828 mScreenOffDelay = 0;
1829 } else if ((mPokey & POKE_LOCK_MEDIUM_TIMEOUT) != 0) {
1830 mKeylightDelay = MEDIUM_KEYLIGHT_DELAY;
1831 mDimDelay = -1;
1832 mScreenOffDelay = 0;
1833 } else {
1834 int totalDelay = mTotalDelaySetting;
1835 mKeylightDelay = LONG_KEYLIGHT_DELAY;
1836 if (totalDelay < 0) {
1837 mScreenOffDelay = Integer.MAX_VALUE;
1838 } else if (mKeylightDelay < totalDelay) {
1839 // subtract the time that the keylight delay. This will give us the
1840 // remainder of the time that we need to sleep to get the accurate
1841 // screen off timeout.
1842 mScreenOffDelay = totalDelay - mKeylightDelay;
1843 } else {
1844 mScreenOffDelay = 0;
1845 }
1846 if (mDimScreen && totalDelay >= (LONG_KEYLIGHT_DELAY + LONG_DIM_TIME)) {
1847 mDimDelay = mScreenOffDelay - LONG_DIM_TIME;
1848 mScreenOffDelay = LONG_DIM_TIME;
1849 } else {
1850 mDimDelay = -1;
1851 }
1852 }
1853 if (mSpew) {
1854 Log.d(TAG, "setScreenOffTimeouts mKeylightDelay=" + mKeylightDelay
1855 + " mDimDelay=" + mDimDelay + " mScreenOffDelay=" + mScreenOffDelay
1856 + " mDimScreen=" + mDimScreen);
1857 }
1858 }
1859
1860 /**
1861 * Refreshes cached Gservices settings. Called once on startup, and
1862 * on subsequent Settings.Gservices.CHANGED_ACTION broadcasts (see
1863 * GservicesChangedReceiver).
1864 */
1865 private void updateGservicesValues() {
1866 mShortKeylightDelay = Settings.Gservices.getInt(
1867 mContext.getContentResolver(),
1868 Settings.Gservices.SHORT_KEYLIGHT_DELAY_MS,
1869 SHORT_KEYLIGHT_DELAY_DEFAULT);
1870 // Log.i(TAG, "updateGservicesValues(): mShortKeylightDelay now " + mShortKeylightDelay);
1871 }
1872
1873 /**
1874 * Receiver for the Gservices.CHANGED_ACTION broadcast intent,
1875 * which tells us we need to refresh our cached Gservices settings.
1876 */
1877 private class GservicesChangedReceiver extends BroadcastReceiver {
1878 @Override
1879 public void onReceive(Context context, Intent intent) {
1880 // Log.i(TAG, "GservicesChangedReceiver.onReceive(): " + intent);
1881 updateGservicesValues();
1882 }
1883 }
1884
1885 private class LockList extends ArrayList<WakeLock>
1886 {
1887 void addLock(WakeLock wl)
1888 {
1889 int index = getIndex(wl.binder);
1890 if (index < 0) {
1891 this.add(wl);
1892 }
1893 }
1894
1895 WakeLock removeLock(IBinder binder)
1896 {
1897 int index = getIndex(binder);
1898 if (index >= 0) {
1899 return this.remove(index);
1900 } else {
1901 return null;
1902 }
1903 }
1904
1905 int getIndex(IBinder binder)
1906 {
1907 int N = this.size();
1908 for (int i=0; i<N; i++) {
1909 if (this.get(i).binder == binder) {
1910 return i;
1911 }
1912 }
1913 return -1;
1914 }
1915
1916 int gatherState()
1917 {
1918 int result = 0;
1919 int N = this.size();
1920 for (int i=0; i<N; i++) {
1921 WakeLock wl = this.get(i);
1922 if (wl.activated) {
1923 if (isScreenLock(wl.flags)) {
1924 result |= wl.minState;
1925 }
1926 }
1927 }
1928 return result;
1929 }
1930 }
1931
1932 void setPolicy(WindowManagerPolicy p) {
1933 synchronized (mLocks) {
1934 mPolicy = p;
1935 mLocks.notifyAll();
1936 }
1937 }
1938
1939 WindowManagerPolicy getPolicyLocked() {
1940 while (mPolicy == null || !mDoneBooting) {
1941 try {
1942 mLocks.wait();
1943 } catch (InterruptedException e) {
1944 // Ignore
1945 }
1946 }
1947 return mPolicy;
1948 }
1949
1950 void systemReady() {
1951 synchronized (mLocks) {
1952 Log.d(TAG, "system ready!");
1953 mDoneBooting = true;
1954 userActivity(SystemClock.uptimeMillis(), false, BUTTON_EVENT, true);
1955 updateWakeLockLocked();
1956 mLocks.notifyAll();
1957 }
1958 }
1959
1960 public void monitor() {
1961 synchronized (mLocks) { }
1962 }
1963}