forked from siddu-k/bashmanager
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
260 lines (228 loc) · 7.12 KB
/
Copy pathmain.js
File metadata and controls
260 lines (228 loc) · 7.12 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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
const { app, BrowserWindow, dialog } = require('electron');
const { spawn } = require('child_process');
const path = require('path');
const fs = require('fs');
const http = require('http');
const net = require('net');
let mainWindow;
let flaskProcess;
let activePort;
let serverReady = false;
let startupInterval = null;
let startupTimeout = null;
const HOST = '127.0.0.1';
const DEFAULT_PORT = 5000;
const MAX_SCAN_PORT = 5100;
const POLL_MS = 200;
const STARTUP_TIMEOUT_MS = 60_000;
const SAFE_EXTERNAL_PROTOCOLS = new Set(['http:', 'https:']);
// We must preserve the python path to our bundled app or local python
function resolvePythonCmd() {
const venv = process.env.VIRTUAL_ENV;
if (venv) {
const venvPython = process.platform === 'win32'
? path.join(venv, 'Scripts', 'python.exe')
: path.join(venv, 'bin', 'python');
if (fs.existsSync(venvPython)) {
return venvPython;
}
}
return process.platform === 'win32' ? 'python' : 'python3';
}
const pythonCmd = resolvePythonCmd();
function parseDevShellPort(raw) {
if (raw === undefined || raw === '') {
return null;
}
const port = Number(raw);
if (!Number.isInteger(port) || port < 1 || port > 65535) {
throw new Error(
`Invalid DEVSHELL_PORT: ${JSON.stringify(raw)} (must be integer 1-65535)`
);
}
return port;
}
function isPortFree(port, host) {
return new Promise((resolve, reject) => {
const server = net.createServer();
server.once('error', (err) => {
if (err.code === 'EADDRINUSE') {
resolve(false);
} else {
reject(err);
}
});
server.once('listening', () => {
server.close(() => resolve(true));
});
server.listen(port, host);
});
}
async function resolvePort() {
const override = parseDevShellPort(process.env.DEVSHELL_PORT);
if (override !== null) {
if (!(await isPortFree(override, HOST))) {
throw new Error(
`DEVSHELL_PORT ${override} is already in use on ${HOST}`
);
}
return override;
}
for (let p = DEFAULT_PORT; p <= MAX_SCAN_PORT; p++) {
if (await isPortFree(p, HOST)) {
return p;
}
}
throw new Error(
`No free port on ${HOST} in range ${DEFAULT_PORT}-${MAX_SCAN_PORT}`
);
}
function clearStartupTimers() {
if (startupInterval) {
clearInterval(startupInterval);
startupInterval = null;
}
if (startupTimeout) {
clearTimeout(startupTimeout);
startupTimeout = null;
}
}
function showStartupError(title, message) {
clearStartupTimers();
dialog.showErrorBox(title, message);
if (mainWindow) {
const body = `${message}\n\nIf port 5000 is in use (e.g. macOS AirPlay Receiver), unset DEVSHELL_PORT and restart, or set DEVSHELL_PORT to a free port.`;
mainWindow.loadURL(
`data:text/html,${encodeURIComponent(
`<html><body style="font-family:sans-serif;padding:2em"><h1>${title}</h1><pre>${body}</pre></body></html>`
)}`
);
}
}
function onServerReady(url) {
if (serverReady) {
return;
}
serverReady = true;
clearStartupTimers();
console.log('Server is ready. Loading UI...');
mainWindow.loadURL(url);
}
function loadWhenReady(url) {
clearStartupTimers();
serverReady = false;
const checkServer = () => {
http.get(url, (res) => {
if (res.statusCode && res.statusCode < 500) {
onServerReady(url);
}
res.resume();
}).on('error', () => {});
};
startupInterval = setInterval(checkServer, POLL_MS);
checkServer();
startupTimeout = setTimeout(() => {
if (!serverReady) {
showStartupError(
'DevShell failed to start',
'The backend server did not respond in time. Another process may be using the port, or Flask failed to start.'
);
app.quit();
}
}, STARTUP_TIMEOUT_MS);
}
function createWindow(port) {
const baseUrl = `http://${HOST}:${port}`;
mainWindow = new BrowserWindow({
width: 1200,
height: 800,
minWidth: 900,
minHeight: 600,
title: "DevShell",
autoHideMenuBar: true,
webPreferences: {
nodeIntegration: false,
contextIsolation: true
}
});
mainWindow.webContents.setWindowOpenHandler(({ url }) => {
let target;
try {
target = new URL(url);
} catch {
return { action: 'deny' };
}
if (target.origin === baseUrl) {
return { action: 'allow' };
}
if (SAFE_EXTERNAL_PROTOCOLS.has(target.protocol)) {
require('electron').shell.openExternal(url);
}
return { action: 'deny' };
});
loadWhenReady(baseUrl);
mainWindow.on('closed', function () {
mainWindow = null;
});
}
function startFlaskServer(port) {
console.log(`Starting Python server on ${HOST}:${port} (using ${pythonCmd})`);
flaskProcess = spawn(pythonCmd, ['app.py'], {
cwd: __dirname,
env: {
...process.env,
DEVSHELL_PORT: String(port),
DEV_SHELL_DATA_DIR: app.getPath('userData'),
}
});
flaskProcess.on('error', (err) => {
showStartupError(
'DevShell failed to start',
`Failed to launch Python backend: ${err.message}. Make sure Python is installed and available as "${pythonCmd}".`
);
app.quit();
});
flaskProcess.stdout.on('data', (data) => {
console.log(`Flask: ${data}`);
});
flaskProcess.stderr.on('data', (data) => {
console.error(`Flask Err: ${data}`);
});
flaskProcess.on('close', (code) => {
console.log(`Flask process exited with code ${code}`);
if (!serverReady && code !== 0) {
showStartupError(
'DevShell failed to start',
`The backend server exited unexpectedly (code ${code}). If Flask fails to bind even after port resolution, this error is shown instead of polling forever.`
);
app.quit();
}
});
}
app.whenReady().then(async () => {
try {
const port = await resolvePort();
activePort = port;
startFlaskServer(port);
createWindow(port);
} catch (err) {
showStartupError('DevShell failed to start', err.message);
app.quit();
}
});
app.on('window-all-closed', function () {
if (process.platform !== 'darwin') {
app.quit();
}
});
app.on('activate', function () {
if (mainWindow === null && activePort) {
createWindow(activePort);
}
});
app.on('will-quit', () => {
clearStartupTimers();
if (flaskProcess) {
flaskProcess.kill();
}
});