-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
81 lines (70 loc) · 2.32 KB
/
main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
const path = require('path')
const { Monitor, ACTION_EVENT } = require('./src/monitor')
const { app, Notification, nativeImage, ipcMain } = require('electron')
const { isDev, getIpcStoreKey } = require('./src/tool')
const { store, STORE_KEY } = require('./src/store')
const { MenuTray, MENU_CLICK_EVENT } = require('./src/menu')
const logger = require('electron-log')
const monitorConfig = isDev() ? { windowSize: 5, intervalMs: 1000 } : { intervalMs: store.get(STORE_KEY.intervalTimeSd, 1000) }
const monitor = new Monitor(monitorConfig)
monitor.on(ACTION_EVENT.REMOVE, ({ pid }) => {
logger.warn(`pid: ${pid} becomes normal`)
menuTray.removePid({ pid })
})
monitor.on(ACTION_EVENT.ADD, ({ pid, stat }) => {
const command = path.basename(stat.command)
logger.warn(`pid: ${pid}, command: ${stat.command} drains the battery fast`)
new Notification({ title: 'ooops', body: `The command "${command}" is draining the battery fast and pid is ${pid}` }).show()
menuTray.addPid({
pid,
stat,
clickFn: () => {
process.kill(pid)
logger.info(`sent SIGTERM to command ${stat.command} pid ${pid}`)
}
})
})
let menuTray
function initMenuBar () {
const icon = nativeImage.createFromPath(path.join(__dirname, 'asserts', 'BlackIconTemplate.png'))
menuTray = new MenuTray(icon)
menuTray.on(MENU_CLICK_EVENT.ON, () => {
monitor.start()
})
menuTray.on(MENU_CLICK_EVENT.OFF, () => {
monitor.stop()
})
menuTray.updateUi()
}
function initListeners () {
ipcMain.on(getIpcStoreKey(STORE_KEY.autoLaunch), (event, value) => {
app.setLoginItemSettings({
openAtLogin: value
})
})
ipcMain.on(getIpcStoreKey(STORE_KEY.intervalTimeSd), (event, intervalMs) => {
monitor.setInterval(intervalMs)
})
}
function startMonitor () {
monitor.start()
}
// This method will be called when Electron has done everything
// initialization and ready for creating menu bar.
app.whenReady()
.then(() => {
logger.info('It\'s time to initialize')
store.set(STORE_KEY.appInfo, `${app.getName()}:${app.getVersion()}`)
})
.then(initListeners)
.then(initMenuBar)
.then(startMonitor)
.then(() => {
logger.info('initialized')
})
.catch(error => {
logger.error(`Failed to initialize: ${error.message}`)
})
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') app.quit()
})