blob: 79d78ad13a946eaad25af02b2f03f0a7df1d9129 [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) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800499 int uid = Binder.getCallingUid();
Michael Chane96440f2009-05-06 10:27:36 -0700500 if (uid != Process.myUid()) {
501 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
502 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800503 long ident = Binder.clearCallingIdentity();
504 try {
505 synchronized (mLocks) {
506 acquireWakeLockLocked(flags, lock, uid, tag);
507 }
508 } finally {
509 Binder.restoreCallingIdentity(ident);
510 }
511 }
512
513 public void acquireWakeLockLocked(int flags, IBinder lock, int uid, String tag) {
514 int acquireUid = -1;
515 String acquireName = null;
516 int acquireType = -1;
517
518 if (mSpew) {
519 Log.d(TAG, "acquireWakeLock flags=0x" + Integer.toHexString(flags) + " tag=" + tag);
520 }
521
522 int index = mLocks.getIndex(lock);
523 WakeLock wl;
524 boolean newlock;
525 if (index < 0) {
526 wl = new WakeLock(flags, lock, tag, uid);
527 switch (wl.flags & LOCK_MASK)
528 {
529 case PowerManager.FULL_WAKE_LOCK:
530 wl.minState = (mKeyboardVisible ? ALL_BRIGHT : SCREEN_BUTTON_BRIGHT);
531 break;
532 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
533 wl.minState = SCREEN_BRIGHT;
534 break;
535 case PowerManager.SCREEN_DIM_WAKE_LOCK:
536 wl.minState = SCREEN_DIM;
537 break;
538 case PowerManager.PARTIAL_WAKE_LOCK:
539 break;
540 default:
541 // just log and bail. we're in the server, so don't
542 // throw an exception.
543 Log.e(TAG, "bad wakelock type for lock '" + tag + "' "
544 + " flags=" + flags);
545 return;
546 }
547 mLocks.addLock(wl);
548 newlock = true;
549 } else {
550 wl = mLocks.get(index);
551 newlock = false;
552 }
553 if (isScreenLock(flags)) {
554 // if this causes a wakeup, we reactivate all of the locks and
555 // set it to whatever they want. otherwise, we modulate that
556 // by the current state so we never turn it more on than
557 // it already is.
558 if ((wl.flags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) {
Michael Chane96440f2009-05-06 10:27:36 -0700559 int oldWakeLockState = mWakeLockState;
560 mWakeLockState = mLocks.reactivateScreenLocksLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800561 if (mSpew) {
562 Log.d(TAG, "wakeup here mUserState=0x" + Integer.toHexString(mUserState)
Michael Chane96440f2009-05-06 10:27:36 -0700563 + " mWakeLockState=0x"
564 + Integer.toHexString(mWakeLockState)
565 + " previous wakeLockState=0x" + Integer.toHexString(oldWakeLockState));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800566 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800567 } else {
568 if (mSpew) {
569 Log.d(TAG, "here mUserState=0x" + Integer.toHexString(mUserState)
570 + " mLocks.gatherState()=0x"
571 + Integer.toHexString(mLocks.gatherState())
572 + " mWakeLockState=0x" + Integer.toHexString(mWakeLockState));
573 }
574 mWakeLockState = (mUserState | mWakeLockState) & mLocks.gatherState();
575 }
576 setPowerState(mWakeLockState | mUserState);
577 }
578 else if ((flags & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK) {
579 if (newlock) {
580 mPartialCount++;
581 if (mPartialCount == 1) {
582 if (LOG_PARTIAL_WL) EventLog.writeEvent(LOG_POWER_PARTIAL_WAKE_STATE, 1, tag);
583 }
584 }
585 Power.acquireWakeLock(Power.PARTIAL_WAKE_LOCK,PARTIAL_NAME);
586 }
587 if (newlock) {
588 acquireUid = wl.uid;
589 acquireName = wl.tag;
590 acquireType = wl.monitorType;
591 }
592
593 if (acquireType >= 0) {
594 try {
595 mBatteryStats.noteStartWakelock(acquireUid, acquireName, acquireType);
596 } catch (RemoteException e) {
597 // Ignore
598 }
599 }
600 }
601
602 public void releaseWakeLock(IBinder lock) {
Michael Chane96440f2009-05-06 10:27:36 -0700603 int uid = Binder.getCallingUid();
604 if (uid != Process.myUid()) {
605 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
606 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800607
608 synchronized (mLocks) {
609 releaseWakeLockLocked(lock, false);
610 }
611 }
612
613 private void releaseWakeLockLocked(IBinder lock, boolean death) {
614 int releaseUid;
615 String releaseName;
616 int releaseType;
617
618 WakeLock wl = mLocks.removeLock(lock);
619 if (wl == null) {
620 return;
621 }
622
623 if (mSpew) {
624 Log.d(TAG, "releaseWakeLock flags=0x"
625 + Integer.toHexString(wl.flags) + " tag=" + wl.tag);
626 }
627
628 if (isScreenLock(wl.flags)) {
629 mWakeLockState = mLocks.gatherState();
630 // goes in the middle to reduce flicker
631 if ((wl.flags & PowerManager.ON_AFTER_RELEASE) != 0) {
632 userActivity(SystemClock.uptimeMillis(), false);
633 }
634 setPowerState(mWakeLockState | mUserState);
635 }
636 else if ((wl.flags & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK) {
637 mPartialCount--;
638 if (mPartialCount == 0) {
639 if (LOG_PARTIAL_WL) EventLog.writeEvent(LOG_POWER_PARTIAL_WAKE_STATE, 0, wl.tag);
640 Power.releaseWakeLock(PARTIAL_NAME);
641 }
642 }
643 // Unlink the lock from the binder.
644 wl.binder.unlinkToDeath(wl, 0);
645 releaseUid = wl.uid;
646 releaseName = wl.tag;
647 releaseType = wl.monitorType;
648
649 if (releaseType >= 0) {
650 long origId = Binder.clearCallingIdentity();
651 try {
652 mBatteryStats.noteStopWakelock(releaseUid, releaseName, releaseType);
653 } catch (RemoteException e) {
654 // Ignore
655 } finally {
656 Binder.restoreCallingIdentity(origId);
657 }
658 }
659 }
660
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800661 private class PokeLock implements IBinder.DeathRecipient
662 {
663 PokeLock(int p, IBinder b, String t) {
664 super();
665 this.pokey = p;
666 this.binder = b;
667 this.tag = t;
668 try {
669 b.linkToDeath(this, 0);
670 } catch (RemoteException e) {
671 binderDied();
672 }
673 }
674 public void binderDied() {
675 setPokeLock(0, this.binder, this.tag);
676 }
677 int pokey;
678 IBinder binder;
679 String tag;
680 boolean awakeOnSet;
681 }
682
683 public void setPokeLock(int pokey, IBinder token, String tag) {
684 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
685 if (token == null) {
686 Log.e(TAG, "setPokeLock got null token for tag='" + tag + "'");
687 return;
688 }
689
690 if ((pokey & POKE_LOCK_TIMEOUT_MASK) == POKE_LOCK_TIMEOUT_MASK) {
691 throw new IllegalArgumentException("setPokeLock can't have both POKE_LOCK_SHORT_TIMEOUT"
692 + " and POKE_LOCK_MEDIUM_TIMEOUT");
693 }
694
695 synchronized (mLocks) {
696 if (pokey != 0) {
697 PokeLock p = mPokeLocks.get(token);
698 int oldPokey = 0;
699 if (p != null) {
700 oldPokey = p.pokey;
701 p.pokey = pokey;
702 } else {
703 p = new PokeLock(pokey, token, tag);
704 mPokeLocks.put(token, p);
705 }
706 int oldTimeout = oldPokey & POKE_LOCK_TIMEOUT_MASK;
707 int newTimeout = pokey & POKE_LOCK_TIMEOUT_MASK;
708 if (((mPowerState & SCREEN_ON_BIT) == 0) && (oldTimeout != newTimeout)) {
709 p.awakeOnSet = true;
710 }
711 } else {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -0700712 PokeLock rLock = mPokeLocks.remove(token);
713 if (rLock != null) {
714 token.unlinkToDeath(rLock, 0);
715 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800716 }
717
718 int oldPokey = mPokey;
719 int cumulative = 0;
720 boolean oldAwakeOnSet = mPokeAwakeOnSet;
721 boolean awakeOnSet = false;
722 for (PokeLock p: mPokeLocks.values()) {
723 cumulative |= p.pokey;
724 if (p.awakeOnSet) {
725 awakeOnSet = true;
726 }
727 }
728 mPokey = cumulative;
729 mPokeAwakeOnSet = awakeOnSet;
730
731 int oldCumulativeTimeout = oldPokey & POKE_LOCK_TIMEOUT_MASK;
732 int newCumulativeTimeout = pokey & POKE_LOCK_TIMEOUT_MASK;
733
734 if (oldCumulativeTimeout != newCumulativeTimeout) {
735 setScreenOffTimeoutsLocked();
736 // reset the countdown timer, but use the existing nextState so it doesn't
737 // change anything
738 setTimeoutLocked(SystemClock.uptimeMillis(), mTimeoutTask.nextState);
739 }
740 }
741 }
742
743 private static String lockType(int type)
744 {
745 switch (type)
746 {
747 case PowerManager.FULL_WAKE_LOCK:
748 return "FULL_WAKE_LOCK ";
749 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
750 return "SCREEN_BRIGHT_WAKE_LOCK";
751 case PowerManager.SCREEN_DIM_WAKE_LOCK:
752 return "SCREEN_DIM_WAKE_LOCK ";
753 case PowerManager.PARTIAL_WAKE_LOCK:
754 return "PARTIAL_WAKE_LOCK ";
755 default:
756 return "??? ";
757 }
758 }
759
760 private static String dumpPowerState(int state) {
761 return (((state & KEYBOARD_BRIGHT_BIT) != 0)
762 ? "KEYBOARD_BRIGHT_BIT " : "")
763 + (((state & SCREEN_BRIGHT_BIT) != 0)
764 ? "SCREEN_BRIGHT_BIT " : "")
765 + (((state & SCREEN_ON_BIT) != 0)
766 ? "SCREEN_ON_BIT " : "")
767 + (((state & BATTERY_LOW_BIT) != 0)
768 ? "BATTERY_LOW_BIT " : "");
769 }
770
771 @Override
772 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
773 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
774 != PackageManager.PERMISSION_GRANTED) {
775 pw.println("Permission Denial: can't dump PowerManager from from pid="
776 + Binder.getCallingPid()
777 + ", uid=" + Binder.getCallingUid());
778 return;
779 }
780
781 long now = SystemClock.uptimeMillis();
782
783 pw.println("Power Manager State:");
784 pw.println(" mIsPowered=" + mIsPowered
785 + " mPowerState=" + mPowerState
786 + " mScreenOffTime=" + (SystemClock.elapsedRealtime()-mScreenOffTime)
787 + " ms");
788 pw.println(" mPartialCount=" + mPartialCount);
789 pw.println(" mWakeLockState=" + dumpPowerState(mWakeLockState));
790 pw.println(" mUserState=" + dumpPowerState(mUserState));
791 pw.println(" mPowerState=" + dumpPowerState(mPowerState));
792 pw.println(" mLocks.gather=" + dumpPowerState(mLocks.gatherState()));
793 pw.println(" mNextTimeout=" + mNextTimeout + " now=" + now
794 + " " + ((mNextTimeout-now)/1000) + "s from now");
795 pw.println(" mDimScreen=" + mDimScreen
796 + " mStayOnConditions=" + mStayOnConditions);
797 pw.println(" mOffBecauseOfUser=" + mOffBecauseOfUser
798 + " mUserState=" + mUserState);
Joe Onorato128e7292009-03-24 18:41:31 -0700799 pw.println(" mBroadcastQueue={" + mBroadcastQueue[0] + ',' + mBroadcastQueue[1]
800 + ',' + mBroadcastQueue[2] + "}");
801 pw.println(" mBroadcastWhy={" + mBroadcastWhy[0] + ',' + mBroadcastWhy[1]
802 + ',' + mBroadcastWhy[2] + "}");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800803 pw.println(" mPokey=" + mPokey + " mPokeAwakeonSet=" + mPokeAwakeOnSet);
804 pw.println(" mKeyboardVisible=" + mKeyboardVisible
805 + " mUserActivityAllowed=" + mUserActivityAllowed);
806 pw.println(" mKeylightDelay=" + mKeylightDelay + " mDimDelay=" + mDimDelay
807 + " mScreenOffDelay=" + mScreenOffDelay);
808 pw.println(" mPreventScreenOn=" + mPreventScreenOn
809 + " mScreenBrightnessOverride=" + mScreenBrightnessOverride);
810 pw.println(" mTotalDelaySetting=" + mTotalDelaySetting);
811 pw.println(" mBroadcastWakeLock=" + mBroadcastWakeLock);
812 pw.println(" mStayOnWhilePluggedInScreenDimLock=" + mStayOnWhilePluggedInScreenDimLock);
813 pw.println(" mStayOnWhilePluggedInPartialLock=" + mStayOnWhilePluggedInPartialLock);
814 pw.println(" mPreventScreenOnPartialLock=" + mPreventScreenOnPartialLock);
815 mScreenBrightness.dump(pw, " mScreenBrightness: ");
816 mKeyboardBrightness.dump(pw, " mKeyboardBrightness: ");
817 mButtonBrightness.dump(pw, " mButtonBrightness: ");
818
819 int N = mLocks.size();
820 pw.println();
821 pw.println("mLocks.size=" + N + ":");
822 for (int i=0; i<N; i++) {
823 WakeLock wl = mLocks.get(i);
824 String type = lockType(wl.flags & LOCK_MASK);
825 String acquireCausesWakeup = "";
826 if ((wl.flags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) {
827 acquireCausesWakeup = "ACQUIRE_CAUSES_WAKEUP ";
828 }
829 String activated = "";
830 if (wl.activated) {
831 activated = " activated";
832 }
833 pw.println(" " + type + " '" + wl.tag + "'" + acquireCausesWakeup
834 + activated + " (minState=" + wl.minState + ")");
835 }
836
837 pw.println();
838 pw.println("mPokeLocks.size=" + mPokeLocks.size() + ":");
839 for (PokeLock p: mPokeLocks.values()) {
840 pw.println(" poke lock '" + p.tag + "':"
841 + ((p.pokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0
842 ? " POKE_LOCK_IGNORE_CHEEK_EVENTS" : "")
Joe Onoratoe68ffcb2009-03-24 19:11:13 -0700843 + ((p.pokey & POKE_LOCK_IGNORE_TOUCH_AND_CHEEK_EVENTS) != 0
844 ? " POKE_LOCK_IGNORE_TOUCH_AND_CHEEK_EVENTS" : "")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800845 + ((p.pokey & POKE_LOCK_SHORT_TIMEOUT) != 0
846 ? " POKE_LOCK_SHORT_TIMEOUT" : "")
847 + ((p.pokey & POKE_LOCK_MEDIUM_TIMEOUT) != 0
848 ? " POKE_LOCK_MEDIUM_TIMEOUT" : ""));
849 }
850
851 pw.println();
852 }
853
854 private void setTimeoutLocked(long now, int nextState)
855 {
856 if (mDoneBooting) {
857 mHandler.removeCallbacks(mTimeoutTask);
858 mTimeoutTask.nextState = nextState;
859 long when = now;
860 switch (nextState)
861 {
862 case SCREEN_BRIGHT:
863 when += mKeylightDelay;
864 break;
865 case SCREEN_DIM:
866 if (mDimDelay >= 0) {
867 when += mDimDelay;
868 break;
869 } else {
870 Log.w(TAG, "mDimDelay=" + mDimDelay + " while trying to dim");
871 }
872 case SCREEN_OFF:
873 synchronized (mLocks) {
874 when += mScreenOffDelay;
875 }
876 break;
877 }
878 if (mSpew) {
879 Log.d(TAG, "setTimeoutLocked now=" + now + " nextState=" + nextState
880 + " when=" + when);
881 }
882 mHandler.postAtTime(mTimeoutTask, when);
883 mNextTimeout = when; // for debugging
884 }
885 }
886
887 private void cancelTimerLocked()
888 {
889 mHandler.removeCallbacks(mTimeoutTask);
890 mTimeoutTask.nextState = -1;
891 }
892
893 private class TimeoutTask implements Runnable
894 {
895 int nextState; // access should be synchronized on mLocks
896 public void run()
897 {
898 synchronized (mLocks) {
899 if (mSpew) {
900 Log.d(TAG, "user activity timeout timed out nextState=" + this.nextState);
901 }
902
903 if (nextState == -1) {
904 return;
905 }
906
907 mUserState = this.nextState;
908 setPowerState(this.nextState | mWakeLockState);
909
910 long now = SystemClock.uptimeMillis();
911
912 switch (this.nextState)
913 {
914 case SCREEN_BRIGHT:
915 if (mDimDelay >= 0) {
916 setTimeoutLocked(now, SCREEN_DIM);
917 break;
918 }
919 case SCREEN_DIM:
920 setTimeoutLocked(now, SCREEN_OFF);
921 break;
922 }
923 }
924 }
925 }
926
927 private void sendNotificationLocked(boolean on, int why)
928 {
Joe Onorato64c62ba2009-03-24 20:13:57 -0700929 if (!on) {
930 mStillNeedSleepNotification = false;
931 }
932
Joe Onorato128e7292009-03-24 18:41:31 -0700933 // Add to the queue.
934 int index = 0;
935 while (mBroadcastQueue[index] != -1) {
936 index++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800937 }
Joe Onorato128e7292009-03-24 18:41:31 -0700938 mBroadcastQueue[index] = on ? 1 : 0;
939 mBroadcastWhy[index] = why;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800940
Joe Onorato128e7292009-03-24 18:41:31 -0700941 // If we added it position 2, then there is a pair that can be stripped.
942 // If we added it position 1 and we're turning the screen off, we can strip
943 // the pair and do nothing, because the screen is already off, and therefore
944 // keyguard has already been enabled.
945 // However, if we added it at position 1 and we're turning it on, then position
946 // 0 was to turn it off, and we can't strip that, because keyguard needs to come
947 // on, so have to run the queue then.
948 if (index == 2) {
949 // Also, while we're collapsing them, if it's going to be an "off," and one
950 // is off because of user, then use that, regardless of whether it's the first
951 // or second one.
952 if (!on && why == WindowManagerPolicy.OFF_BECAUSE_OF_USER) {
953 mBroadcastWhy[0] = WindowManagerPolicy.OFF_BECAUSE_OF_USER;
954 }
955 mBroadcastQueue[0] = on ? 1 : 0;
956 mBroadcastQueue[1] = -1;
957 mBroadcastQueue[2] = -1;
958 index = 0;
959 }
960 if (index == 1 && !on) {
961 mBroadcastQueue[0] = -1;
962 mBroadcastQueue[1] = -1;
963 index = -1;
964 // The wake lock was being held, but we're not actually going to do any
965 // broadcasts, so release the wake lock.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800966 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_STOP, 1, mBroadcastWakeLock.mCount);
967 mBroadcastWakeLock.release();
Joe Onorato128e7292009-03-24 18:41:31 -0700968 }
969
970 // Now send the message.
971 if (index >= 0) {
972 // Acquire the broadcast wake lock before changing the power
973 // state. It will be release after the broadcast is sent.
974 // We always increment the ref count for each notification in the queue
975 // and always decrement when that notification is handled.
976 mBroadcastWakeLock.acquire();
977 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_SEND, mBroadcastWakeLock.mCount);
978 mHandler.post(mNotificationTask);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800979 }
980 }
981
982 private Runnable mNotificationTask = new Runnable()
983 {
984 public void run()
985 {
Joe Onorato128e7292009-03-24 18:41:31 -0700986 while (true) {
987 int value;
988 int why;
989 WindowManagerPolicy policy;
990 synchronized (mLocks) {
991 value = mBroadcastQueue[0];
992 why = mBroadcastWhy[0];
993 for (int i=0; i<2; i++) {
994 mBroadcastQueue[i] = mBroadcastQueue[i+1];
995 mBroadcastWhy[i] = mBroadcastWhy[i+1];
996 }
997 policy = getPolicyLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800998 }
Joe Onorato128e7292009-03-24 18:41:31 -0700999 if (value == 1) {
1000 mScreenOnStart = SystemClock.uptimeMillis();
1001
1002 policy.screenTurnedOn();
1003 try {
1004 ActivityManagerNative.getDefault().wakingUp();
1005 } catch (RemoteException e) {
1006 // ignore it
1007 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001008
Joe Onorato128e7292009-03-24 18:41:31 -07001009 if (mSpew) {
1010 Log.d(TAG, "mBroadcastWakeLock=" + mBroadcastWakeLock);
1011 }
1012 if (mContext != null && ActivityManagerNative.isSystemReady()) {
1013 mContext.sendOrderedBroadcast(mScreenOnIntent, null,
1014 mScreenOnBroadcastDone, mHandler, 0, null, null);
1015 } else {
1016 synchronized (mLocks) {
1017 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_STOP, 2,
1018 mBroadcastWakeLock.mCount);
1019 mBroadcastWakeLock.release();
1020 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001021 }
1022 }
Joe Onorato128e7292009-03-24 18:41:31 -07001023 else if (value == 0) {
1024 mScreenOffStart = SystemClock.uptimeMillis();
1025
1026 policy.screenTurnedOff(why);
1027 try {
1028 ActivityManagerNative.getDefault().goingToSleep();
1029 } catch (RemoteException e) {
1030 // ignore it.
1031 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001032
Joe Onorato128e7292009-03-24 18:41:31 -07001033 if (mContext != null && ActivityManagerNative.isSystemReady()) {
1034 mContext.sendOrderedBroadcast(mScreenOffIntent, null,
1035 mScreenOffBroadcastDone, mHandler, 0, null, null);
1036 } else {
1037 synchronized (mLocks) {
1038 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_STOP, 3,
1039 mBroadcastWakeLock.mCount);
1040 mBroadcastWakeLock.release();
1041 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001042 }
1043 }
Joe Onorato128e7292009-03-24 18:41:31 -07001044 else {
1045 // If we're in this case, then this handler is running for a previous
1046 // paired transaction. mBroadcastWakeLock will already have been released.
1047 break;
1048 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001049 }
1050 }
1051 };
1052
1053 long mScreenOnStart;
1054 private BroadcastReceiver mScreenOnBroadcastDone = new BroadcastReceiver() {
1055 public void onReceive(Context context, Intent intent) {
1056 synchronized (mLocks) {
1057 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_DONE, 1,
1058 SystemClock.uptimeMillis() - mScreenOnStart, mBroadcastWakeLock.mCount);
1059 mBroadcastWakeLock.release();
1060 }
1061 }
1062 };
1063
1064 long mScreenOffStart;
1065 private BroadcastReceiver mScreenOffBroadcastDone = new BroadcastReceiver() {
1066 public void onReceive(Context context, Intent intent) {
1067 synchronized (mLocks) {
1068 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_DONE, 0,
1069 SystemClock.uptimeMillis() - mScreenOffStart, mBroadcastWakeLock.mCount);
1070 mBroadcastWakeLock.release();
1071 }
1072 }
1073 };
1074
1075 void logPointerUpEvent() {
1076 if (LOG_TOUCH_DOWNS) {
1077 mTotalTouchDownTime += SystemClock.elapsedRealtime() - mLastTouchDown;
1078 mLastTouchDown = 0;
1079 }
1080 }
1081
1082 void logPointerDownEvent() {
1083 if (LOG_TOUCH_DOWNS) {
1084 // If we are not already timing a down/up sequence
1085 if (mLastTouchDown == 0) {
1086 mLastTouchDown = SystemClock.elapsedRealtime();
1087 mTouchCycles++;
1088 }
1089 }
1090 }
1091
1092 /**
1093 * Prevents the screen from turning on even if it *should* turn on due
1094 * to a subsequent full wake lock being acquired.
1095 * <p>
1096 * This is a temporary hack that allows an activity to "cover up" any
1097 * display glitches that happen during the activity's startup
1098 * sequence. (Specifically, this API was added to work around a
1099 * cosmetic bug in the "incoming call" sequence, where the lock screen
1100 * would flicker briefly before the incoming call UI became visible.)
1101 * TODO: There ought to be a more elegant way of doing this,
1102 * probably by having the PowerManager and ActivityManager
1103 * work together to let apps specify that the screen on/off
1104 * state should be synchronized with the Activity lifecycle.
1105 * <p>
1106 * Note that calling preventScreenOn(true) will NOT turn the screen
1107 * off if it's currently on. (This API only affects *future*
1108 * acquisitions of full wake locks.)
1109 * But calling preventScreenOn(false) WILL turn the screen on if
1110 * it's currently off because of a prior preventScreenOn(true) call.
1111 * <p>
1112 * Any call to preventScreenOn(true) MUST be followed promptly by a call
1113 * to preventScreenOn(false). In fact, if the preventScreenOn(false)
1114 * call doesn't occur within 5 seconds, we'll turn the screen back on
1115 * ourselves (and log a warning about it); this prevents a buggy app
1116 * from disabling the screen forever.)
1117 * <p>
1118 * TODO: this feature should really be controlled by a new type of poke
1119 * lock (rather than an IPowerManager call).
1120 */
1121 public void preventScreenOn(boolean prevent) {
1122 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1123
1124 synchronized (mLocks) {
1125 if (prevent) {
1126 // First of all, grab a partial wake lock to
1127 // make sure the CPU stays on during the entire
1128 // preventScreenOn(true) -> preventScreenOn(false) sequence.
1129 mPreventScreenOnPartialLock.acquire();
1130
1131 // Post a forceReenableScreen() call (for 5 seconds in the
1132 // future) to make sure the matching preventScreenOn(false) call
1133 // has happened by then.
1134 mHandler.removeCallbacks(mForceReenableScreenTask);
1135 mHandler.postDelayed(mForceReenableScreenTask, 5000);
1136
1137 // Finally, set the flag that prevents the screen from turning on.
1138 // (Below, in setPowerState(), we'll check mPreventScreenOn and
1139 // we *won't* call Power.setScreenState(true) if it's set.)
1140 mPreventScreenOn = true;
1141 } else {
1142 // (Re)enable the screen.
1143 mPreventScreenOn = false;
1144
1145 // We're "undoing" a the prior preventScreenOn(true) call, so we
1146 // no longer need the 5-second safeguard.
1147 mHandler.removeCallbacks(mForceReenableScreenTask);
1148
1149 // Forcibly turn on the screen if it's supposed to be on. (This
1150 // handles the case where the screen is currently off because of
1151 // a prior preventScreenOn(true) call.)
1152 if ((mPowerState & SCREEN_ON_BIT) != 0) {
1153 if (mSpew) {
1154 Log.d(TAG,
1155 "preventScreenOn: turning on after a prior preventScreenOn(true)!");
1156 }
1157 int err = Power.setScreenState(true);
1158 if (err != 0) {
1159 Log.w(TAG, "preventScreenOn: error from Power.setScreenState(): " + err);
1160 }
1161 }
1162
1163 // Release the partial wake lock that we held during the
1164 // preventScreenOn(true) -> preventScreenOn(false) sequence.
1165 mPreventScreenOnPartialLock.release();
1166 }
1167 }
1168 }
1169
1170 public void setScreenBrightnessOverride(int brightness) {
1171 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1172
1173 synchronized (mLocks) {
1174 if (mScreenBrightnessOverride != brightness) {
1175 mScreenBrightnessOverride = brightness;
1176 updateLightsLocked(mPowerState, SCREEN_ON_BIT);
1177 }
1178 }
1179 }
1180
1181 /**
1182 * Sanity-check that gets called 5 seconds after any call to
1183 * preventScreenOn(true). This ensures that the original call
1184 * is followed promptly by a call to preventScreenOn(false).
1185 */
1186 private void forceReenableScreen() {
1187 // We shouldn't get here at all if mPreventScreenOn is false, since
1188 // we should have already removed any existing
1189 // mForceReenableScreenTask messages...
1190 if (!mPreventScreenOn) {
1191 Log.w(TAG, "forceReenableScreen: mPreventScreenOn is false, nothing to do");
1192 return;
1193 }
1194
1195 // Uh oh. It's been 5 seconds since a call to
1196 // preventScreenOn(true) and we haven't re-enabled the screen yet.
1197 // This means the app that called preventScreenOn(true) is either
1198 // slow (i.e. it took more than 5 seconds to call preventScreenOn(false)),
1199 // or buggy (i.e. it forgot to call preventScreenOn(false), or
1200 // crashed before doing so.)
1201
1202 // Log a warning, and forcibly turn the screen back on.
1203 Log.w(TAG, "App called preventScreenOn(true) but didn't promptly reenable the screen! "
1204 + "Forcing the screen back on...");
1205 preventScreenOn(false);
1206 }
1207
1208 private Runnable mForceReenableScreenTask = new Runnable() {
1209 public void run() {
1210 forceReenableScreen();
1211 }
1212 };
1213
1214 private void setPowerState(int state)
1215 {
1216 setPowerState(state, false, false);
1217 }
1218
1219 private void setPowerState(int newState, boolean noChangeLights, boolean becauseOfUser)
1220 {
1221 synchronized (mLocks) {
1222 int err;
1223
1224 if (mSpew) {
1225 Log.d(TAG, "setPowerState: mPowerState=0x" + Integer.toHexString(mPowerState)
1226 + " newState=0x" + Integer.toHexString(newState)
1227 + " noChangeLights=" + noChangeLights);
1228 }
1229
1230 if (noChangeLights) {
1231 newState = (newState & ~LIGHTS_MASK) | (mPowerState & LIGHTS_MASK);
1232 }
1233
1234 if (batteryIsLow()) {
1235 newState |= BATTERY_LOW_BIT;
1236 } else {
1237 newState &= ~BATTERY_LOW_BIT;
1238 }
1239 if (newState == mPowerState) {
1240 return;
1241 }
1242
1243 if (!mDoneBooting) {
1244 newState |= ALL_BRIGHT;
1245 }
1246
1247 boolean oldScreenOn = (mPowerState & SCREEN_ON_BIT) != 0;
1248 boolean newScreenOn = (newState & SCREEN_ON_BIT) != 0;
1249
1250 if (mSpew) {
1251 Log.d(TAG, "setPowerState: mPowerState=" + mPowerState
1252 + " newState=" + newState + " noChangeLights=" + noChangeLights);
1253 Log.d(TAG, " oldKeyboardBright=" + ((mPowerState & KEYBOARD_BRIGHT_BIT) != 0)
1254 + " newKeyboardBright=" + ((newState & KEYBOARD_BRIGHT_BIT) != 0));
1255 Log.d(TAG, " oldScreenBright=" + ((mPowerState & SCREEN_BRIGHT_BIT) != 0)
1256 + " newScreenBright=" + ((newState & SCREEN_BRIGHT_BIT) != 0));
1257 Log.d(TAG, " oldButtonBright=" + ((mPowerState & BUTTON_BRIGHT_BIT) != 0)
1258 + " newButtonBright=" + ((newState & BUTTON_BRIGHT_BIT) != 0));
1259 Log.d(TAG, " oldScreenOn=" + oldScreenOn
1260 + " newScreenOn=" + newScreenOn);
1261 Log.d(TAG, " oldBatteryLow=" + ((mPowerState & BATTERY_LOW_BIT) != 0)
1262 + " newBatteryLow=" + ((newState & BATTERY_LOW_BIT) != 0));
1263 }
1264
1265 if (mPowerState != newState) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001266 updateLightsLocked(newState, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001267 mPowerState = (mPowerState & ~LIGHTS_MASK) | (newState & LIGHTS_MASK);
1268 }
1269
1270 if (oldScreenOn != newScreenOn) {
1271 if (newScreenOn) {
Joe Onorato128e7292009-03-24 18:41:31 -07001272 // When the user presses the power button, we need to always send out the
1273 // notification that it's going to sleep so the keyguard goes on. But
1274 // we can't do that until the screen fades out, so we don't show the keyguard
1275 // too early.
1276 if (mStillNeedSleepNotification) {
1277 sendNotificationLocked(false, WindowManagerPolicy.OFF_BECAUSE_OF_USER);
1278 }
1279
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001280 // Turn on the screen UNLESS there was a prior
1281 // preventScreenOn(true) request. (Note that the lifetime
1282 // of a single preventScreenOn() request is limited to 5
1283 // seconds to prevent a buggy app from disabling the
1284 // screen forever; see forceReenableScreen().)
1285 boolean reallyTurnScreenOn = true;
1286 if (mSpew) {
1287 Log.d(TAG, "- turning screen on... mPreventScreenOn = "
1288 + mPreventScreenOn);
1289 }
1290
1291 if (mPreventScreenOn) {
1292 if (mSpew) {
1293 Log.d(TAG, "- PREVENTING screen from really turning on!");
1294 }
1295 reallyTurnScreenOn = false;
1296 }
1297 if (reallyTurnScreenOn) {
1298 err = Power.setScreenState(true);
1299 long identity = Binder.clearCallingIdentity();
1300 try {
Dianne Hackborn617f8772009-03-31 15:04:46 -07001301 mBatteryStats.noteScreenBrightness(
1302 getPreferredBrightness());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001303 mBatteryStats.noteScreenOn();
1304 } catch (RemoteException e) {
1305 Log.w(TAG, "RemoteException calling noteScreenOn on BatteryStatsService", e);
1306 } finally {
1307 Binder.restoreCallingIdentity(identity);
1308 }
1309 } else {
1310 Power.setScreenState(false);
1311 // But continue as if we really did turn the screen on...
1312 err = 0;
1313 }
1314
1315 mScreenOnStartTime = SystemClock.elapsedRealtime();
1316 mLastTouchDown = 0;
1317 mTotalTouchDownTime = 0;
1318 mTouchCycles = 0;
1319 EventLog.writeEvent(LOG_POWER_SCREEN_STATE, 1, becauseOfUser ? 1 : 0,
1320 mTotalTouchDownTime, mTouchCycles);
1321 if (err == 0) {
1322 mPowerState |= SCREEN_ON_BIT;
1323 sendNotificationLocked(true, -1);
1324 }
1325 } else {
1326 mScreenOffTime = SystemClock.elapsedRealtime();
1327 long identity = Binder.clearCallingIdentity();
1328 try {
1329 mBatteryStats.noteScreenOff();
1330 } catch (RemoteException e) {
1331 Log.w(TAG, "RemoteException calling noteScreenOff on BatteryStatsService", e);
1332 } finally {
1333 Binder.restoreCallingIdentity(identity);
1334 }
1335 mPowerState &= ~SCREEN_ON_BIT;
1336 if (!mScreenBrightness.animating) {
Joe Onorato128e7292009-03-24 18:41:31 -07001337 err = screenOffFinishedAnimatingLocked(becauseOfUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001338 } else {
1339 mOffBecauseOfUser = becauseOfUser;
1340 err = 0;
1341 mLastTouchDown = 0;
1342 }
1343 }
1344 }
1345 }
1346 }
1347
Joe Onorato128e7292009-03-24 18:41:31 -07001348 private int screenOffFinishedAnimatingLocked(boolean becauseOfUser) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001349 // I don't think we need to check the current state here because all of these
1350 // Power.setScreenState and sendNotificationLocked can both handle being
1351 // called multiple times in the same state. -joeo
1352 EventLog.writeEvent(LOG_POWER_SCREEN_STATE, 0, becauseOfUser ? 1 : 0,
1353 mTotalTouchDownTime, mTouchCycles);
1354 mLastTouchDown = 0;
1355 int err = Power.setScreenState(false);
1356 if (mScreenOnStartTime != 0) {
1357 mScreenOnTime += SystemClock.elapsedRealtime() - mScreenOnStartTime;
1358 mScreenOnStartTime = 0;
1359 }
1360 if (err == 0) {
1361 int why = becauseOfUser
1362 ? WindowManagerPolicy.OFF_BECAUSE_OF_USER
1363 : WindowManagerPolicy.OFF_BECAUSE_OF_TIMEOUT;
1364 sendNotificationLocked(false, why);
1365 }
1366 return err;
1367 }
1368
1369 private boolean batteryIsLow() {
1370 return (!mIsPowered &&
1371 mBatteryService.getBatteryLevel() <= Power.LOW_BATTERY_THRESHOLD);
1372 }
1373
The Android Open Source Project10592532009-03-18 17:39:46 -07001374 private void updateLightsLocked(int newState, int forceState) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001375 final int oldState = mPowerState;
1376 final int realDifference = (newState ^ oldState);
1377 final int difference = realDifference | forceState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001378 if (difference == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001379 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001380 }
1381
1382 int offMask = 0;
1383 int dimMask = 0;
1384 int onMask = 0;
1385
1386 int preferredBrightness = getPreferredBrightness();
1387 boolean startAnimation = false;
1388
1389 if ((difference & KEYBOARD_BRIGHT_BIT) != 0) {
1390 if (ANIMATE_KEYBOARD_LIGHTS) {
1391 if ((newState & KEYBOARD_BRIGHT_BIT) == 0) {
1392 mKeyboardBrightness.setTargetLocked(Power.BRIGHTNESS_OFF,
Joe Onorato128e7292009-03-24 18:41:31 -07001393 ANIM_STEPS, INITIAL_KEYBOARD_BRIGHTNESS,
1394 preferredBrightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001395 } else {
1396 mKeyboardBrightness.setTargetLocked(preferredBrightness,
Joe Onorato128e7292009-03-24 18:41:31 -07001397 ANIM_STEPS, INITIAL_KEYBOARD_BRIGHTNESS,
1398 Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001399 }
1400 startAnimation = true;
1401 } else {
1402 if ((newState & KEYBOARD_BRIGHT_BIT) == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001403 offMask |= KEYBOARD_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001404 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001405 onMask |= KEYBOARD_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001406 }
1407 }
1408 }
1409
1410 if ((difference & BUTTON_BRIGHT_BIT) != 0) {
1411 if (ANIMATE_BUTTON_LIGHTS) {
1412 if ((newState & BUTTON_BRIGHT_BIT) == 0) {
1413 mButtonBrightness.setTargetLocked(Power.BRIGHTNESS_OFF,
Joe Onorato128e7292009-03-24 18:41:31 -07001414 ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
1415 preferredBrightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001416 } else {
1417 mButtonBrightness.setTargetLocked(preferredBrightness,
Joe Onorato128e7292009-03-24 18:41:31 -07001418 ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
1419 Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001420 }
1421 startAnimation = true;
1422 } else {
1423 if ((newState & BUTTON_BRIGHT_BIT) == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001424 offMask |= BUTTON_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001425 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001426 onMask |= BUTTON_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001427 }
1428 }
1429 }
1430
1431 if ((difference & (SCREEN_ON_BIT | SCREEN_BRIGHT_BIT)) != 0) {
1432 if (ANIMATE_SCREEN_LIGHTS) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001433 int nominalCurrentValue = -1;
1434 // If there was an actual difference in the light state, then
1435 // figure out the "ideal" current value based on the previous
1436 // state. Otherwise, this is a change due to the brightness
1437 // override, so we want to animate from whatever the current
1438 // value is.
1439 if ((realDifference & (SCREEN_ON_BIT | SCREEN_BRIGHT_BIT)) != 0) {
1440 switch (oldState & (SCREEN_BRIGHT_BIT|SCREEN_ON_BIT)) {
1441 case SCREEN_BRIGHT_BIT | SCREEN_ON_BIT:
1442 nominalCurrentValue = preferredBrightness;
1443 break;
1444 case SCREEN_ON_BIT:
1445 nominalCurrentValue = Power.BRIGHTNESS_DIM;
1446 break;
1447 case 0:
1448 nominalCurrentValue = Power.BRIGHTNESS_OFF;
1449 break;
1450 case SCREEN_BRIGHT_BIT:
1451 default:
1452 // not possible
1453 nominalCurrentValue = (int)mScreenBrightness.curValue;
1454 break;
1455 }
Joe Onorato128e7292009-03-24 18:41:31 -07001456 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001457 int brightness = preferredBrightness;
1458 int steps = ANIM_STEPS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001459 if ((newState & SCREEN_BRIGHT_BIT) == 0) {
1460 // dim or turn off backlight, depending on if the screen is on
1461 // the scale is because the brightness ramp isn't linear and this biases
1462 // it so the later parts take longer.
1463 final float scale = 1.5f;
1464 float ratio = (((float)Power.BRIGHTNESS_DIM)/preferredBrightness);
1465 if (ratio > 1.0f) ratio = 1.0f;
1466 if ((newState & SCREEN_ON_BIT) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001467 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 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001474 brightness = Power.BRIGHTNESS_OFF;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001475 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001476 if ((oldState & SCREEN_ON_BIT) != 0) {
1477 // was bright
1478 steps = (int)(ANIM_STEPS*(1.0f-ratio)*scale);
1479 } else {
1480 // was dim
1481 steps = (int)(ANIM_STEPS*ratio);
1482 }
1483 if (mStayOnConditions != 0 && mBatteryService.isPowered(mStayOnConditions)) {
1484 // If the "stay on while plugged in" option is
1485 // turned on, then the screen will often not
1486 // automatically turn off while plugged in. To
1487 // still have a sense of when it is inactive, we
1488 // will then count going dim as turning off.
1489 mScreenOffTime = SystemClock.elapsedRealtime();
1490 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001491 brightness = Power.BRIGHTNESS_DIM;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001492 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001493 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001494 long identity = Binder.clearCallingIdentity();
1495 try {
1496 mBatteryStats.noteScreenBrightness(brightness);
1497 } catch (RemoteException e) {
1498 // Nothing interesting to do.
1499 } finally {
1500 Binder.restoreCallingIdentity(identity);
1501 }
1502 mScreenBrightness.setTargetLocked(brightness,
1503 steps, INITIAL_SCREEN_BRIGHTNESS, nominalCurrentValue);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001504 startAnimation = true;
1505 } else {
1506 if ((newState & SCREEN_BRIGHT_BIT) == 0) {
1507 // dim or turn off backlight, depending on if the screen is on
1508 if ((newState & SCREEN_ON_BIT) == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001509 offMask |= SCREEN_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001510 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001511 dimMask |= SCREEN_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001512 }
1513 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001514 onMask |= SCREEN_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001515 }
1516 }
1517 }
1518
1519 if (startAnimation) {
1520 if (mSpew) {
1521 Log.i(TAG, "Scheduling light animator!");
1522 }
1523 mHandler.removeCallbacks(mLightAnimator);
1524 mHandler.post(mLightAnimator);
1525 }
1526
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001527 if (offMask != 0) {
1528 //Log.i(TAG, "Setting brightess off: " + offMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001529 setLightBrightness(offMask, Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001530 }
1531 if (dimMask != 0) {
1532 int brightness = Power.BRIGHTNESS_DIM;
1533 if ((newState & BATTERY_LOW_BIT) != 0 &&
1534 brightness > Power.BRIGHTNESS_LOW_BATTERY) {
1535 brightness = Power.BRIGHTNESS_LOW_BATTERY;
1536 }
1537 //Log.i(TAG, "Setting brightess dim " + brightness + ": " + offMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001538 setLightBrightness(dimMask, brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001539 }
1540 if (onMask != 0) {
1541 int brightness = getPreferredBrightness();
1542 if ((newState & BATTERY_LOW_BIT) != 0 &&
1543 brightness > Power.BRIGHTNESS_LOW_BATTERY) {
1544 brightness = Power.BRIGHTNESS_LOW_BATTERY;
1545 }
1546 //Log.i(TAG, "Setting brightess on " + brightness + ": " + onMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001547 setLightBrightness(onMask, brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001548 }
The Android Open Source Project10592532009-03-18 17:39:46 -07001549 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001550
The Android Open Source Project10592532009-03-18 17:39:46 -07001551 private void setLightBrightness(int mask, int value) {
1552 if ((mask & SCREEN_BRIGHT_BIT) != 0) {
1553 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_BACKLIGHT, value);
1554 }
1555 if ((mask & BUTTON_BRIGHT_BIT) != 0) {
1556 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_BUTTONS, value);
1557 }
1558 if ((mask & KEYBOARD_BRIGHT_BIT) != 0) {
1559 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_KEYBOARD, value);
1560 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001561 }
1562
1563 class BrightnessState {
1564 final int mask;
1565
1566 boolean initialized;
1567 int targetValue;
1568 float curValue;
1569 float delta;
1570 boolean animating;
1571
1572 BrightnessState(int m) {
1573 mask = m;
1574 }
1575
1576 public void dump(PrintWriter pw, String prefix) {
1577 pw.println(prefix + "animating=" + animating
1578 + " targetValue=" + targetValue
1579 + " curValue=" + curValue
1580 + " delta=" + delta);
1581 }
1582
Joe Onorato128e7292009-03-24 18:41:31 -07001583 void setTargetLocked(int target, int stepsToTarget, int initialValue,
1584 int nominalCurrentValue) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001585 if (!initialized) {
1586 initialized = true;
1587 curValue = (float)initialValue;
1588 }
1589 targetValue = target;
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001590 delta = (targetValue -
1591 (nominalCurrentValue >= 0 ? nominalCurrentValue : curValue))
1592 / stepsToTarget;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001593 if (mSpew) {
Joe Onorato128e7292009-03-24 18:41:31 -07001594 String noticeMe = nominalCurrentValue == curValue ? "" : " ******************";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001595 Log.i(TAG, "Setting target " + mask + ": cur=" + curValue
Joe Onorato128e7292009-03-24 18:41:31 -07001596 + " target=" + targetValue + " delta=" + delta
1597 + " nominalCurrentValue=" + nominalCurrentValue
1598 + noticeMe);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001599 }
1600 animating = true;
1601 }
1602
1603 boolean stepLocked() {
1604 if (!animating) return false;
1605 if (false && mSpew) {
1606 Log.i(TAG, "Step target " + mask + ": cur=" + curValue
1607 + " target=" + targetValue + " delta=" + delta);
1608 }
1609 curValue += delta;
1610 int curIntValue = (int)curValue;
1611 boolean more = true;
1612 if (delta == 0) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001613 curValue = curIntValue = targetValue;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001614 more = false;
1615 } else if (delta > 0) {
1616 if (curIntValue >= targetValue) {
1617 curValue = curIntValue = targetValue;
1618 more = false;
1619 }
1620 } else {
1621 if (curIntValue <= targetValue) {
1622 curValue = curIntValue = targetValue;
1623 more = false;
1624 }
1625 }
1626 //Log.i(TAG, "Animating brightess " + curIntValue + ": " + mask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001627 setLightBrightness(mask, curIntValue);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001628 animating = more;
1629 if (!more) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001630 if (mask == SCREEN_BRIGHT_BIT && curIntValue == Power.BRIGHTNESS_OFF) {
Joe Onorato128e7292009-03-24 18:41:31 -07001631 screenOffFinishedAnimatingLocked(mOffBecauseOfUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001632 }
1633 }
1634 return more;
1635 }
1636 }
1637
1638 private class LightAnimator implements Runnable {
1639 public void run() {
1640 synchronized (mLocks) {
1641 long now = SystemClock.uptimeMillis();
1642 boolean more = mScreenBrightness.stepLocked();
1643 if (mKeyboardBrightness.stepLocked()) {
1644 more = true;
1645 }
1646 if (mButtonBrightness.stepLocked()) {
1647 more = true;
1648 }
1649 if (more) {
1650 mHandler.postAtTime(mLightAnimator, now+(1000/60));
1651 }
1652 }
1653 }
1654 }
1655
1656 private int getPreferredBrightness() {
1657 try {
1658 if (mScreenBrightnessOverride >= 0) {
1659 return mScreenBrightnessOverride;
1660 }
1661 final int brightness = Settings.System.getInt(mContext.getContentResolver(),
1662 SCREEN_BRIGHTNESS);
1663 // Don't let applications turn the screen all the way off
1664 return Math.max(brightness, Power.BRIGHTNESS_DIM);
1665 } catch (SettingNotFoundException snfe) {
1666 return Power.BRIGHTNESS_ON;
1667 }
1668 }
1669
1670 boolean screenIsOn() {
1671 synchronized (mLocks) {
1672 return (mPowerState & SCREEN_ON_BIT) != 0;
1673 }
1674 }
1675
1676 boolean screenIsBright() {
1677 synchronized (mLocks) {
1678 return (mPowerState & SCREEN_BRIGHT) == SCREEN_BRIGHT;
1679 }
1680 }
1681
1682 public void userActivityWithForce(long time, boolean noChangeLights, boolean force) {
1683 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1684 userActivity(time, noChangeLights, OTHER_EVENT, force);
1685 }
1686
1687 public void userActivity(long time, boolean noChangeLights) {
1688 userActivity(time, noChangeLights, OTHER_EVENT, false);
1689 }
1690
1691 public void userActivity(long time, boolean noChangeLights, int eventType) {
1692 userActivity(time, noChangeLights, eventType, false);
1693 }
1694
1695 public void userActivity(long time, boolean noChangeLights, int eventType, boolean force) {
1696 //mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1697
1698 if (((mPokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0)
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07001699 && (eventType == CHEEK_EVENT || eventType == TOUCH_EVENT)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001700 if (false) {
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07001701 Log.d(TAG, "dropping cheek or short event mPokey=0x" + Integer.toHexString(mPokey));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001702 }
1703 return;
1704 }
1705
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07001706 if (((mPokey & POKE_LOCK_IGNORE_TOUCH_AND_CHEEK_EVENTS) != 0)
1707 && (eventType == TOUCH_EVENT || eventType == TOUCH_UP_EVENT
1708 || eventType == LONG_TOUCH_EVENT || eventType == CHEEK_EVENT)) {
1709 if (false) {
1710 Log.d(TAG, "dropping touch mPokey=0x" + Integer.toHexString(mPokey));
1711 }
1712 return;
1713 }
1714
1715
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001716 if (false) {
1717 if (((mPokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0)) {
1718 Log.d(TAG, "userActivity !!!");//, new RuntimeException());
1719 } else {
1720 Log.d(TAG, "mPokey=0x" + Integer.toHexString(mPokey));
1721 }
1722 }
1723
1724 synchronized (mLocks) {
1725 if (mSpew) {
1726 Log.d(TAG, "userActivity mLastEventTime=" + mLastEventTime + " time=" + time
1727 + " mUserActivityAllowed=" + mUserActivityAllowed
1728 + " mUserState=0x" + Integer.toHexString(mUserState)
1729 + " mWakeLockState=0x" + Integer.toHexString(mWakeLockState));
1730 }
1731 if (mLastEventTime <= time || force) {
1732 mLastEventTime = time;
1733 if (mUserActivityAllowed || force) {
1734 // Only turn on button backlights if a button was pressed.
1735 if (eventType == BUTTON_EVENT) {
1736 mUserState = (mKeyboardVisible ? ALL_BRIGHT : SCREEN_BUTTON_BRIGHT);
1737 } else {
1738 // don't clear button/keyboard backlights when the screen is touched.
1739 mUserState |= SCREEN_BRIGHT;
1740 }
1741
Dianne Hackborn617f8772009-03-31 15:04:46 -07001742 int uid = Binder.getCallingUid();
1743 long ident = Binder.clearCallingIdentity();
1744 try {
1745 mBatteryStats.noteUserActivity(uid, eventType);
1746 } catch (RemoteException e) {
1747 // Ignore
1748 } finally {
1749 Binder.restoreCallingIdentity(ident);
1750 }
1751
Michael Chane96440f2009-05-06 10:27:36 -07001752 mWakeLockState = mLocks.reactivateScreenLocksLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001753 setPowerState(mUserState | mWakeLockState, noChangeLights, true);
1754 setTimeoutLocked(time, SCREEN_BRIGHT);
1755 }
1756 }
1757 }
1758 }
1759
1760 /**
1761 * The user requested that we go to sleep (probably with the power button).
1762 * This overrides all wake locks that are held.
1763 */
1764 public void goToSleep(long time)
1765 {
1766 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1767 synchronized (mLocks) {
1768 goToSleepLocked(time);
1769 }
1770 }
1771
1772 /**
1773 * Returns the time the screen has been on since boot, in millis.
1774 * @return screen on time
1775 */
1776 public long getScreenOnTime() {
1777 synchronized (mLocks) {
1778 if (mScreenOnStartTime == 0) {
1779 return mScreenOnTime;
1780 } else {
1781 return SystemClock.elapsedRealtime() - mScreenOnStartTime + mScreenOnTime;
1782 }
1783 }
1784 }
1785
1786 private void goToSleepLocked(long time) {
1787
1788 if (mLastEventTime <= time) {
1789 mLastEventTime = time;
1790 // cancel all of the wake locks
1791 mWakeLockState = SCREEN_OFF;
1792 int N = mLocks.size();
1793 int numCleared = 0;
1794 for (int i=0; i<N; i++) {
1795 WakeLock wl = mLocks.get(i);
1796 if (isScreenLock(wl.flags)) {
1797 mLocks.get(i).activated = false;
1798 numCleared++;
1799 }
1800 }
1801 EventLog.writeEvent(LOG_POWER_SLEEP_REQUESTED, numCleared);
Joe Onorato128e7292009-03-24 18:41:31 -07001802 mStillNeedSleepNotification = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001803 mUserState = SCREEN_OFF;
1804 setPowerState(SCREEN_OFF, false, true);
1805 cancelTimerLocked();
1806 }
1807 }
1808
1809 public long timeSinceScreenOn() {
1810 synchronized (mLocks) {
1811 if ((mPowerState & SCREEN_ON_BIT) != 0) {
1812 return 0;
1813 }
1814 return SystemClock.elapsedRealtime() - mScreenOffTime;
1815 }
1816 }
1817
1818 public void setKeyboardVisibility(boolean visible) {
1819 mKeyboardVisible = visible;
1820 }
1821
1822 /**
1823 * When the keyguard is up, it manages the power state, and userActivity doesn't do anything.
1824 */
1825 public void enableUserActivity(boolean enabled) {
1826 synchronized (mLocks) {
1827 mUserActivityAllowed = enabled;
1828 mLastEventTime = SystemClock.uptimeMillis(); // we might need to pass this in
1829 }
1830 }
1831
1832 /** Sets the screen off timeouts:
1833 * mKeylightDelay
1834 * mDimDelay
1835 * mScreenOffDelay
1836 * */
1837 private void setScreenOffTimeoutsLocked() {
1838 if ((mPokey & POKE_LOCK_SHORT_TIMEOUT) != 0) {
1839 mKeylightDelay = mShortKeylightDelay; // Configurable via Gservices
1840 mDimDelay = -1;
1841 mScreenOffDelay = 0;
1842 } else if ((mPokey & POKE_LOCK_MEDIUM_TIMEOUT) != 0) {
1843 mKeylightDelay = MEDIUM_KEYLIGHT_DELAY;
1844 mDimDelay = -1;
1845 mScreenOffDelay = 0;
1846 } else {
1847 int totalDelay = mTotalDelaySetting;
1848 mKeylightDelay = LONG_KEYLIGHT_DELAY;
1849 if (totalDelay < 0) {
1850 mScreenOffDelay = Integer.MAX_VALUE;
1851 } else if (mKeylightDelay < totalDelay) {
1852 // subtract the time that the keylight delay. This will give us the
1853 // remainder of the time that we need to sleep to get the accurate
1854 // screen off timeout.
1855 mScreenOffDelay = totalDelay - mKeylightDelay;
1856 } else {
1857 mScreenOffDelay = 0;
1858 }
1859 if (mDimScreen && totalDelay >= (LONG_KEYLIGHT_DELAY + LONG_DIM_TIME)) {
1860 mDimDelay = mScreenOffDelay - LONG_DIM_TIME;
1861 mScreenOffDelay = LONG_DIM_TIME;
1862 } else {
1863 mDimDelay = -1;
1864 }
1865 }
1866 if (mSpew) {
1867 Log.d(TAG, "setScreenOffTimeouts mKeylightDelay=" + mKeylightDelay
1868 + " mDimDelay=" + mDimDelay + " mScreenOffDelay=" + mScreenOffDelay
1869 + " mDimScreen=" + mDimScreen);
1870 }
1871 }
1872
1873 /**
1874 * Refreshes cached Gservices settings. Called once on startup, and
1875 * on subsequent Settings.Gservices.CHANGED_ACTION broadcasts (see
1876 * GservicesChangedReceiver).
1877 */
1878 private void updateGservicesValues() {
1879 mShortKeylightDelay = Settings.Gservices.getInt(
1880 mContext.getContentResolver(),
1881 Settings.Gservices.SHORT_KEYLIGHT_DELAY_MS,
1882 SHORT_KEYLIGHT_DELAY_DEFAULT);
1883 // Log.i(TAG, "updateGservicesValues(): mShortKeylightDelay now " + mShortKeylightDelay);
1884 }
1885
1886 /**
1887 * Receiver for the Gservices.CHANGED_ACTION broadcast intent,
1888 * which tells us we need to refresh our cached Gservices settings.
1889 */
1890 private class GservicesChangedReceiver extends BroadcastReceiver {
1891 @Override
1892 public void onReceive(Context context, Intent intent) {
1893 // Log.i(TAG, "GservicesChangedReceiver.onReceive(): " + intent);
1894 updateGservicesValues();
1895 }
1896 }
1897
1898 private class LockList extends ArrayList<WakeLock>
1899 {
1900 void addLock(WakeLock wl)
1901 {
1902 int index = getIndex(wl.binder);
1903 if (index < 0) {
1904 this.add(wl);
1905 }
1906 }
1907
1908 WakeLock removeLock(IBinder binder)
1909 {
1910 int index = getIndex(binder);
1911 if (index >= 0) {
1912 return this.remove(index);
1913 } else {
1914 return null;
1915 }
1916 }
1917
1918 int getIndex(IBinder binder)
1919 {
1920 int N = this.size();
1921 for (int i=0; i<N; i++) {
1922 if (this.get(i).binder == binder) {
1923 return i;
1924 }
1925 }
1926 return -1;
1927 }
1928
1929 int gatherState()
1930 {
1931 int result = 0;
1932 int N = this.size();
1933 for (int i=0; i<N; i++) {
1934 WakeLock wl = this.get(i);
1935 if (wl.activated) {
1936 if (isScreenLock(wl.flags)) {
1937 result |= wl.minState;
1938 }
1939 }
1940 }
1941 return result;
1942 }
Michael Chane96440f2009-05-06 10:27:36 -07001943
1944 int reactivateScreenLocksLocked()
1945 {
1946 int result = 0;
1947 int N = this.size();
1948 for (int i=0; i<N; i++) {
1949 WakeLock wl = this.get(i);
1950 if (isScreenLock(wl.flags)) {
1951 wl.activated = true;
1952 result |= wl.minState;
1953 }
1954 }
1955 return result;
1956 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001957 }
1958
1959 void setPolicy(WindowManagerPolicy p) {
1960 synchronized (mLocks) {
1961 mPolicy = p;
1962 mLocks.notifyAll();
1963 }
1964 }
1965
1966 WindowManagerPolicy getPolicyLocked() {
1967 while (mPolicy == null || !mDoneBooting) {
1968 try {
1969 mLocks.wait();
1970 } catch (InterruptedException e) {
1971 // Ignore
1972 }
1973 }
1974 return mPolicy;
1975 }
1976
1977 void systemReady() {
1978 synchronized (mLocks) {
1979 Log.d(TAG, "system ready!");
1980 mDoneBooting = true;
Dianne Hackborn617f8772009-03-31 15:04:46 -07001981 long identity = Binder.clearCallingIdentity();
1982 try {
1983 mBatteryStats.noteScreenBrightness(getPreferredBrightness());
1984 mBatteryStats.noteScreenOn();
1985 } catch (RemoteException e) {
1986 // Nothing interesting to do.
1987 } finally {
1988 Binder.restoreCallingIdentity(identity);
1989 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001990 userActivity(SystemClock.uptimeMillis(), false, BUTTON_EVENT, true);
1991 updateWakeLockLocked();
1992 mLocks.notifyAll();
1993 }
1994 }
1995
1996 public void monitor() {
1997 synchronized (mLocks) { }
1998 }
1999}