main.js 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  1. const { app, BrowserWindow ,ipcMain} = require('electron')
  2. const path = require('path')
  3. const os = require('os')
  4. const fs = require('fs')
  5. const config = require('../configs/config.js')
  6. const isDev = process.env.NODE_ENV === 'development' || !app.isPackaged
  7. // 修复缓存权限问题:设置用户数据目录到有权限的位置
  8. // 必须在 app.whenReady() 之前调用
  9. if (process.platform === 'win32') {
  10. try {
  11. // 设置缓存目录到用户临时目录,避免权限问题
  12. const userDataPath = path.join(os.tmpdir(), 'electron-react-vite-app')
  13. // 确保目录存在
  14. if (!fs.existsSync(userDataPath)) {
  15. fs.mkdirSync(userDataPath, { recursive: true })
  16. }
  17. // 创建缓存子目录
  18. const cacheDir = path.join(userDataPath, 'cache')
  19. const gpuCacheDir = path.join(userDataPath, 'gpu-cache')
  20. if (!fs.existsSync(cacheDir)) {
  21. fs.mkdirSync(cacheDir, { recursive: true })
  22. }
  23. if (!fs.existsSync(gpuCacheDir)) {
  24. fs.mkdirSync(gpuCacheDir, { recursive: true })
  25. }
  26. // 设置用户数据路径(必须在 app.whenReady() 之前)
  27. app.setPath('userData', userDataPath)
  28. // 设置缓存目录到有权限的位置
  29. app.commandLine.appendSwitch('disk-cache-dir', cacheDir)
  30. app.commandLine.appendSwitch('gpu-disk-cache-dir', gpuCacheDir)
  31. console.log(`[OK] Cache directories set to: ${userDataPath}`)
  32. } catch (error) {
  33. console.warn('[WARN] Failed to set cache directories:', error.message)
  34. // 如果设置失败,尝试禁用 GPU 缓存作为备选方案
  35. app.commandLine.appendSwitch('disable-gpu-sandbox')
  36. }
  37. }
  38. // 保存主窗口引用,用于推送消息
  39. let mainWindowInstance = null
  40. function createWindow() {
  41. const mainWindow = new BrowserWindow({
  42. width: config.window.width,
  43. height: config.window.height,
  44. autoHideMenuBar: config.window.autoHideMenuBar, // 从配置文件读取
  45. webPreferences: {
  46. nodeIntegration: false,
  47. contextIsolation: true,
  48. preload: path.join(__dirname, 'preload.js')
  49. }
  50. })
  51. // 保存窗口引用
  52. mainWindowInstance = mainWindow
  53. if (isDev) {
  54. const vitePort = config.vite?.port || 5173
  55. const viteHost = config.vite?.host || 'localhost'
  56. console.log(`Loading Vite dev server at http://${viteHost}:${vitePort}`)
  57. mainWindow.loadURL(`http://${viteHost}:${vitePort}`)
  58. // 根据配置文件决定是否打开调试侧边栏
  59. if (config.devTools.enabled) {
  60. mainWindow.webContents.openDevTools()
  61. }
  62. } else {
  63. mainWindow.loadFile(path.join(__dirname, '../dist/index.html'))
  64. }
  65. }
  66. const { spawn } = require('child_process')
  67. // 存储运行中的进程
  68. const runningProcesses = new Map()
  69. // Execute Node.js script
  70. ipcMain.handle('run-nodejs-script', async (event, scriptName, ...parameters) => {
  71. return new Promise((resolve, reject) => {
  72. const scriptPath = path.join(__dirname, '../nodejs', `${scriptName}.js`)
  73. const processKey = `${scriptName}-${parameters.join('-')}`
  74. // 如果进程已运行,先停止它
  75. if (runningProcesses.has(processKey)) {
  76. const oldProcess = runningProcesses.get(processKey)
  77. oldProcess.kill()
  78. runningProcesses.delete(processKey)
  79. }
  80. const nodeProcess = spawn('node', [scriptPath, ...parameters])
  81. runningProcesses.set(processKey, nodeProcess)
  82. let stdout = ''
  83. let stderr = ''
  84. let resolved = false
  85. const finish = (result) => {
  86. if (resolved) return
  87. resolved = true
  88. resolve(result)
  89. }
  90. nodeProcess.stdout.on('data', (data) => {
  91. const dataStr = data.toString()
  92. stdout += dataStr
  93. const isLongRunning = scriptName.includes('screenshot') || scriptName.includes('adb/')
  94. try {
  95. const lines = dataStr.trim().split('\n')
  96. for (const line of lines) {
  97. if (line.trim().startsWith('{')) {
  98. const json = JSON.parse(line.trim())
  99. if (json.success && isLongRunning) {
  100. finish({ success: true, stdout: line.trim(), stderr: stderr.trim(), exitCode: null })
  101. return
  102. }
  103. }
  104. }
  105. } catch (e) {}
  106. })
  107. nodeProcess.stderr.on('data', (data) => {
  108. stderr += data.toString()
  109. })
  110. const isRunProcess = scriptName === 'run-process'
  111. const timeoutId = isRunProcess ? null : setTimeout(() => {
  112. if (!resolved) {
  113. finish({
  114. success: false,
  115. stdout: stdout.trim(),
  116. stderr: stderr.trim(),
  117. exitCode: 1,
  118. message: 'Script is running in background'
  119. })
  120. }
  121. }, 5000)
  122. nodeProcess.on('close', (code) => {
  123. if (timeoutId) clearTimeout(timeoutId)
  124. runningProcesses.delete(processKey)
  125. const exitCode = (code !== null && code !== undefined) ? code : 1
  126. finish({
  127. success: exitCode === 0,
  128. stdout: stdout.trim(),
  129. stderr: stderr.trim(),
  130. exitCode
  131. })
  132. })
  133. nodeProcess.on('error', (error) => {
  134. clearTimeout(timeoutId)
  135. runningProcesses.delete(processKey)
  136. if (!resolved) {
  137. resolved = true
  138. reject(error)
  139. }
  140. })
  141. })
  142. })
  143. /** 停止指定的 Node.js 脚本进程 */
  144. ipcMain.handle('kill-nodejs-script', async (event, scriptName, ...parameters) => {
  145. const processKey = `${scriptName}-${parameters.join('-')}`
  146. if (runningProcesses.has(processKey)) {
  147. runningProcesses.get(processKey).kill()
  148. runningProcesses.delete(processKey)
  149. return { killed: true }
  150. }
  151. return { killed: false }
  152. })
  153. // Execute Python script
  154. ipcMain.handle('run-python-script', async (event, scriptName, ...parameters) => {
  155. return new Promise((resolve, reject) => {
  156. let pythonPath = 'python'
  157. if (config.pythonPath?.path) {
  158. const configPythonPath = path.join(config.pythonPath.path, 'python.exe')
  159. if (fs.existsSync(configPythonPath)) {
  160. pythonPath = configPythonPath
  161. }
  162. }
  163. const scriptPath = path.join(__dirname, '../python/scripts', `${scriptName}.py`)
  164. if (!fs.existsSync(scriptPath)) {
  165. reject({
  166. success: false,
  167. error: `Script file not found: ${scriptPath}`,
  168. stderr: `Script file not found: ${scriptPath}`
  169. })
  170. return
  171. }
  172. const pythonProcess = spawn(pythonPath, [scriptPath, ...parameters])
  173. let stdout = ''
  174. let stderr = ''
  175. pythonProcess.stdout.on('data', (data) => {
  176. stdout += data.toString()
  177. })
  178. pythonProcess.stderr.on('data', (data) => {
  179. stderr += data.toString()
  180. })
  181. pythonProcess.on('close', (code) => {
  182. resolve({
  183. success: code === 0,
  184. stdout: stdout.trim(),
  185. stderr: stderr.trim(),
  186. exitCode: code
  187. })
  188. })
  189. pythonProcess.on('error', (error) => {
  190. reject({
  191. success: false,
  192. error: error.message,
  193. stderr: error.message
  194. })
  195. })
  196. })
  197. })
  198. // IPC 实时通信处理
  199. // 处理前端请求(异步,返回 Promise)
  200. ipcMain.handle('ipc-request', async (event, channel, data) => {
  201. // 可以根据不同的 channel 处理不同的请求
  202. // 例如:'run-nodejs', 'get-status' 等
  203. if (channel === 'run-nodejs') {
  204. // 通过 IPC 调用 run-nodejs-script
  205. const { scriptName, ...parameters } = data
  206. return new Promise((resolve, reject) => {
  207. const scriptPath = path.join(__dirname, '../nodejs', `${scriptName}.js`)
  208. const processKey = `${scriptName}-${parameters.join('-')}`
  209. if (runningProcesses.has(processKey)) {
  210. const oldProcess = runningProcesses.get(processKey)
  211. oldProcess.kill()
  212. runningProcesses.delete(processKey)
  213. }
  214. const nodeProcess = spawn('node', [scriptPath, ...Object.values(parameters)])
  215. runningProcesses.set(processKey, nodeProcess)
  216. let stdout = ''
  217. let stderr = ''
  218. let resolved = false
  219. nodeProcess.stdout.on('data', (chunk) => {
  220. stdout += chunk.toString()
  221. try {
  222. const lines = chunk.toString().trim().split('\n')
  223. for (const line of lines) {
  224. if (line.trim().startsWith('{')) {
  225. const json = JSON.parse(line.trim())
  226. if (json.success && !resolved) {
  227. resolved = true
  228. resolve({ success: true, stdout: line.trim(), stderr: stderr.trim(), exitCode: null })
  229. }
  230. }
  231. }
  232. } catch (e) {}
  233. })
  234. nodeProcess.stderr.on('data', (chunk) => {
  235. stderr += chunk.toString()
  236. })
  237. nodeProcess.on('close', (code) => {
  238. runningProcesses.delete(processKey)
  239. if (!resolved) {
  240. resolve({ success: code === 0, stdout: stdout.trim(), stderr: stderr.trim(), exitCode: code })
  241. }
  242. })
  243. nodeProcess.on('error', (error) => {
  244. runningProcesses.delete(processKey)
  245. if (!resolved) {
  246. reject(error)
  247. }
  248. })
  249. setTimeout(() => {
  250. if (!resolved) {
  251. resolved = true
  252. resolve({ success: true, stdout: stdout.trim(), stderr: stderr.trim(), exitCode: null, message: 'Script is running in background' })
  253. }
  254. }, 5000)
  255. })
  256. }
  257. // 默认响应
  258. return { success: true, channel, data, timestamp: Date.now() }
  259. })
  260. // 监听前端发送的消息(不需要响应)
  261. ipcMain.on('ipc-message', (event, channel, data) => {
  262. // 处理前端发送的消息
  263. console.log(`[IPC] Received message on channel "${channel}":`, data)
  264. })
  265. // 推送消息到前端的辅助函数
  266. function pushToFrontend(channel, data) {
  267. if (mainWindowInstance && !mainWindowInstance.isDestroyed()) {
  268. mainWindowInstance.webContents.send(channel, data)
  269. }
  270. }
  271. // 导出推送函数供其他模块使用
  272. global.pushToFrontend = pushToFrontend
  273. app.whenReady().then(() => {
  274. createWindow()
  275. app.on('activate', () => {
  276. if (BrowserWindow.getAllWindows().length === 0) {
  277. createWindow()
  278. }
  279. })
  280. })
  281. app.on('window-all-closed', () => {
  282. if (process.platform !== 'darwin') {
  283. app.quit()
  284. }
  285. })