power-monitor.ts 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. import { EventEmitter } from 'events';
  2. import { app } from 'electron/main';
  3. const {
  4. createPowerMonitor,
  5. getSystemIdleState,
  6. getSystemIdleTime,
  7. isOnBatteryPower
  8. } = process._linkedBinding('electron_browser_power_monitor');
  9. class PowerMonitor extends EventEmitter {
  10. constructor () {
  11. super();
  12. // Don't start the event source until both a) the app is ready and b)
  13. // there's a listener registered for a powerMonitor event.
  14. this.once('newListener', () => {
  15. app.whenReady().then(() => {
  16. const pm = createPowerMonitor();
  17. pm.emit = this.emit.bind(this);
  18. if (process.platform === 'linux') {
  19. // On Linux, we inhibit shutdown in order to give the app a chance to
  20. // decide whether or not it wants to prevent the shutdown. We don't
  21. // inhibit the shutdown event unless there's a listener for it. This
  22. // keeps the C++ code informed about whether there are any listeners.
  23. pm.setListeningForShutdown(this.listenerCount('shutdown') > 0);
  24. this.on('newListener', (event) => {
  25. if (event === 'shutdown') {
  26. pm.setListeningForShutdown(this.listenerCount('shutdown') + 1 > 0);
  27. }
  28. });
  29. this.on('removeListener', (event) => {
  30. if (event === 'shutdown') {
  31. pm.setListeningForShutdown(this.listenerCount('shutdown') > 0);
  32. }
  33. });
  34. }
  35. });
  36. });
  37. }
  38. getSystemIdleState (idleThreshold: number) {
  39. return getSystemIdleState(idleThreshold);
  40. }
  41. getSystemIdleTime () {
  42. return getSystemIdleTime();
  43. }
  44. isOnBatteryPower () {
  45. return isOnBatteryPower();
  46. }
  47. get onBatteryPower () {
  48. return this.isOnBatteryPower();
  49. }
  50. }
  51. module.exports = new PowerMonitor();