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