-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
212 lines (186 loc) · 5.65 KB
/
Copy pathmain.js
File metadata and controls
212 lines (186 loc) · 5.65 KB
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
const { app, BrowserWindow, ipcMain, shell, Tray, Menu } = require('electron')
const { spawn, exec } = require('child_process')
const path = require('path')
let mainWindow
let tray = null
let kanbanProcess = null
let kanbanUrl = null
let currentPort = null
let currentStatus = 'Остановлено'
function createWindow() {
mainWindow = new BrowserWindow({
width: 400,
height: 380,
webPreferences: {
nodeIntegration: true,
contextIsolation: false,
},
})
mainWindow.loadFile('index.html')
// Сворачивать в трей вместо закрытия
mainWindow.on('close', event => {
if (!app.isQuitting) {
event.preventDefault()
mainWindow.hide()
}
})
}
function updateTrayMenu() {
const contextMenu = Menu.buildFromTemplate([
{
label: `Статус: ${currentStatus}`,
enabled: false,
},
{ type: 'separator' },
{
label: 'Показать окно',
click: () => mainWindow.show(),
},
{
label: 'Старт',
click: () => mainWindow.webContents.send('tray-start'),
},
{
label: 'Стоп',
click: () => mainWindow.webContents.send('tray-stop'),
},
{ type: 'separator' },
{
label: 'Выход',
click: () => {
app.isQuitting = true
app.quit()
},
},
])
tray.setContextMenu(contextMenu)
tray.setToolTip(`Vibe Kanban - ${currentStatus}`)
}
function createTray() {
const iconPath = path.join(__dirname, 'kanban_icon_32.ico')
tray = new Tray(iconPath)
updateTrayMenu()
// Двойной клик — показать окно
tray.on('double-click', () => {
mainWindow.show()
})
}
// Запуск процесса
ipcMain.on('start-app', event => {
if (kanbanProcess) return
// Заменяем 'npx' на 'npx.cmd' для Windows
const cmd = process.platform === 'win32' ? 'npx.cmd' : 'npx'
kanbanProcess = spawn(cmd, ['vibe-kanban'])
// Буфер для накопления данных
let outputBuffer = ''
kanbanProcess.stdout.on('data', data => {
outputBuffer += data.toString()
// Разбиваем буфер на строки
const lines = outputBuffer.split(/\r?\n/)
// Последняя строка может быть неполной, оставляем её в буфере
outputBuffer = lines.pop()
for (const line of lines) {
// Удаляем ANSI-коды для чистого текста
const cleanLine = line.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g, '')
console.log(`stdout: ${cleanLine}`)
// Обновление статуса при загрузке
if (cleanLine.includes('Downloading') || cleanLine.includes('Download')) {
if (currentStatus !== 'Загрузка...') {
currentStatus = 'Загрузка...'
event.reply('status-changed', currentStatus)
if (tray) updateTrayMenu()
}
continue
}
// Обновление статуса при запуске
if (cleanLine.includes('Starting') || cleanLine.includes('Server running')) {
if (currentStatus !== 'Запуск...') {
currentStatus = 'Запуск...'
event.reply('status-changed', currentStatus)
if (tray) updateTrayMenu()
}
}
// Ищем URL в выводе (например: http://127.0.0.1:16338 или http://localhost:12345)
const urlMatch = cleanLine.match(
/https?:\/\/[\d.]+:(\d+)|https?:\/\/localhost:(\d+)/i,
)
if (urlMatch) {
kanbanUrl = urlMatch[0]
currentPort = urlMatch[1] || urlMatch[2]
console.log(`Найден URL: ${kanbanUrl}, порт: ${currentPort}`)
event.reply('url-detected', kanbanUrl)
// Статус "Работает" ставим только когда нашли URL
event.reply('status-changed', 'Работает')
currentStatus = 'Работает'
if (tray) updateTrayMenu()
}
}
})
kanbanProcess.on('close', () => {
kanbanProcess = null
event.reply('status-changed', 'Остановлено')
currentStatus = 'Остановлено'
if (tray) updateTrayMenu()
})
})
// Функция для убийства процесса по порту
function killProcessOnPort(port, callback) {
if (process.platform === 'win32') {
// Находим PID процесса на порту и убиваем его
exec(
`for /f "tokens=5" %a in ('netstat -aon ^| findstr :${port} ^| findstr LISTENING') do taskkill /F /PID %a`,
{ shell: 'cmd.exe' },
err => {
if (callback) callback(err)
},
)
} else {
exec(`lsof -ti:${port} | xargs kill -9`, err => {
if (callback) callback(err)
})
}
}
// Остановка процесса
ipcMain.on('stop-app', event => {
// Убиваем процесс npx если есть
if (kanbanProcess) {
if (process.platform === 'win32') {
exec(`taskkill /pid ${kanbanProcess.pid} /T /F`, err => {
if (err) console.log('Ошибка завершения npx:', err)
})
} else {
kanbanProcess.kill('SIGTERM')
}
kanbanProcess = null
}
// Убиваем процесс на текущем порту
if (currentPort) {
killProcessOnPort(currentPort, err => {
if (err) console.log('Ошибка завершения сервера:', err)
})
}
kanbanUrl = null
currentPort = null
event.reply('status-changed', 'Остановлено')
event.reply('url-detected', null)
currentStatus = 'Остановлено'
if (tray) updateTrayMenu()
})
// Открытие сайта
ipcMain.on('open-link', () => {
if (kanbanUrl) {
shell.openExternal(kanbanUrl)
}
})
app.whenReady().then(() => {
createWindow()
createTray()
// Автозагрузка при старте Windows
app.setLoginItemSettings({
openAtLogin: true,
path: app.getPath('exe'),
})
})
app.on('before-quit', () => {
app.isQuitting = true
})