power-monitor.ts 1.6 KB

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