power-monitor.ts 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import { EventEmitter } from 'events';
  2. const {
  3. createPowerMonitor,
  4. getSystemIdleState,
  5. getSystemIdleTime,
  6. getCurrentThermalState,
  7. isOnBatteryPower
  8. } = process._linkedBinding('electron_browser_power_monitor');
  9. class PowerMonitor extends EventEmitter implements Electron.PowerMonitor {
  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. const pm = createPowerMonitor();
  16. pm.emit = this.emit.bind(this);
  17. if (process.platform === 'linux') {
  18. // On Linux, we inhibit shutdown in order to give the app a chance to
  19. // decide whether or not it wants to prevent the shutdown. We don't
  20. // inhibit the shutdown event unless there's a listener for it. This
  21. // keeps the C++ code informed about whether there are any listeners.
  22. pm.setListeningForShutdown(this.listenerCount('shutdown') > 0);
  23. this.on('newListener', (event) => {
  24. if (event === 'shutdown') {
  25. pm.setListeningForShutdown(this.listenerCount('shutdown') + 1 > 0);
  26. }
  27. });
  28. this.on('removeListener', (event) => {
  29. if (event === 'shutdown') {
  30. pm.setListeningForShutdown(this.listenerCount('shutdown') > 0);
  31. }
  32. });
  33. }
  34. });
  35. }
  36. getSystemIdleState (idleThreshold: number) {
  37. return getSystemIdleState(idleThreshold);
  38. }
  39. getCurrentThermalState () {
  40. return getCurrentThermalState();
  41. }
  42. getSystemIdleTime () {
  43. return getSystemIdleTime();
  44. }
  45. isOnBatteryPower () {
  46. return isOnBatteryPower();
  47. }
  48. get onBatteryPower () {
  49. return this.isOnBatteryPower();
  50. }
  51. }
  52. module.exports = new PowerMonitor();