-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
234 lines (205 loc) · 6.61 KB
/
Copy pathmain.js
File metadata and controls
234 lines (205 loc) · 6.61 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
const { app, BrowserWindow, ipcMain, dialog, Menu } = require('electron');
const path = require('path');
const express = require('express');
const { spawn } = require('child_process');
let mainWindow;
let serverProcess;
// 启动后端服务器
function startServer() {
const serverPath = path.join(__dirname, 'server', 'index.js');
serverProcess = spawn('node', [serverPath], {
cwd: __dirname,
stdio: 'inherit'
});
serverProcess.on('error', (error) => {
console.error('服务器启动失败:', error);
});
}
// 等待服务器就绪
function waitForServer(url, maxAttempts = 30, interval = 1000) {
return new Promise((resolve, reject) => {
const http = require('http');
const urlModule = require('url');
let attempts = 0;
const checkServer = () => {
attempts++;
try {
const urlObj = urlModule.parse(url);
const options = {
hostname: urlObj.hostname || 'localhost',
port: urlObj.port || 3000,
path: urlObj.pathname || '/',
method: 'GET',
timeout: 3000
};
console.log(`尝试连接服务器 (${attempts}/${maxAttempts}):`, options);
const req = http.request(options, (res) => {
// 接受更多状态码(包括重定向等)
if (res.statusCode >= 200 && res.statusCode < 400) {
console.log(`服务器已就绪 (状态码: ${res.statusCode})`);
resolve();
} else {
console.log(`收到状态码: ${res.statusCode},继续等待...`);
if (attempts < maxAttempts) {
setTimeout(checkServer, interval);
} else {
reject(new Error(`服务器返回异常状态码: ${res.statusCode}`));
}
}
});
req.on('error', (error) => {
console.log(`连接错误 (尝试 ${attempts}/${maxAttempts}):`, error.message);
if (attempts < maxAttempts) {
setTimeout(checkServer, interval);
} else {
reject(new Error(`无法连接到开发服务器: ${error.message}`));
}
});
req.on('timeout', () => {
req.destroy();
if (attempts < maxAttempts) {
setTimeout(checkServer, interval);
} else {
reject(new Error('服务器连接超时'));
}
});
req.end();
} catch (error) {
if (attempts < maxAttempts) {
setTimeout(checkServer, interval);
} else {
reject(new Error(`连接失败: ${error.message}`));
}
}
};
checkServer();
});
}
// 创建主窗口
function createWindow() {
mainWindow = new BrowserWindow({
width: 1200,
height: 800,
minWidth: 800,
minHeight: 600,
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
nodeIntegration: false,
contextIsolation: true,
enableRemoteModule: false
},
icon: path.join(__dirname, 'assets', 'icon.png'),
show: false // 先不显示,等加载完成后再显示
});
// 开发环境加载 React 开发服务器,生产环境加载构建文件
const isDev = process.env.NODE_ENV === 'development' || !app.isPackaged;
if (isDev) {
const devUrl = 'http://localhost:3000';
console.log('准备加载 React 开发服务器...');
// 先尝试直接加载,如果失败再等待
const tryLoad = () => {
console.log('尝试直接加载开发服务器:', devUrl);
mainWindow.loadURL(devUrl)
.then(() => {
console.log('✅ 成功加载开发服务器');
mainWindow.webContents.openDevTools();
mainWindow.show();
})
.catch((error) => {
console.log('直接加载失败,开始等待服务器就绪...', error.message);
// 如果直接加载失败,等待服务器就绪
waitForServer(devUrl)
.then(() => {
console.log('✅ 服务器已就绪,重新加载:', devUrl);
return mainWindow.loadURL(devUrl);
})
.then(() => {
console.log('✅ 成功加载开发服务器');
mainWindow.webContents.openDevTools();
mainWindow.show();
})
.catch((waitError) => {
console.error('❌ 等待服务器失败:', waitError);
mainWindow.loadFile(path.join(__dirname, 'public', 'index.html'));
mainWindow.show();
// 显示错误对话框
dialog.showErrorBox(
'开发服务器连接失败',
`无法连接到 React 开发服务器 (http://localhost:3000)\n\n请确保已运行 "npm run dev:react" 或 "npm run dev"\n\n错误: ${waitError.message}`
);
});
});
};
// 延迟一点再尝试,给服务器更多启动时间
setTimeout(tryLoad, 500);
} else {
mainWindow.loadFile(path.join(__dirname, 'build', 'index.html'));
mainWindow.show();
}
mainWindow.on('closed', () => {
mainWindow = null;
});
}
// 处理文件选择对话框
ipcMain.handle('dialog:openFile', async () => {
const { canceled, filePaths } = await dialog.showOpenDialog(mainWindow, {
properties: ['openFile', 'multiSelections'],
filters: [
{ name: 'Markdown文件', extensions: ['md', 'markdown'] },
{ name: '所有文件', extensions: ['*'] }
]
});
if (canceled) {
return null;
} else {
return filePaths;
}
});
// 处理目录选择对话框
ipcMain.handle('dialog:openDirectory', async () => {
const { canceled, filePaths } = await dialog.showOpenDialog(mainWindow, {
properties: ['openDirectory']
});
if (canceled) {
return null;
} else {
return filePaths[0];
}
});
// 处理打开文件位置
ipcMain.handle('shell:showItemInFolder', async (event, filePath) => {
const { shell } = require('electron');
shell.showItemInFolder(filePath);
});
// 处理打开文件
ipcMain.handle('shell:openPath', async (event, filePath) => {
const { shell } = require('electron');
return shell.openPath(filePath);
});
// 应用准备就绪
app.whenReady().then(() => {
// 移除默认菜单栏
Menu.setApplicationMenu(null);
startServer();
createWindow();
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow();
}
});
});
// 所有窗口关闭时退出
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
if (serverProcess) {
serverProcess.kill();
}
app.quit();
}
});
// 应用退出前清理
app.on('before-quit', () => {
if (serverProcess) {
serverProcess.kill();
}
});