main.js 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  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 timeoutId = setTimeout(() => {
  111. if (!resolved) {
  112. finish({
  113. success: false,
  114. stdout: stdout.trim(),
  115. stderr: stderr.trim(),
  116. exitCode: 1,
  117. message: 'Script is running in background'
  118. })
  119. }
  120. }, 5000)
  121. nodeProcess.on('close', (code) => {
  122. clearTimeout(timeoutId)
  123. runningProcesses.delete(processKey)
  124. const exitCode = (code !== null && code !== undefined) ? code : 1
  125. finish({
  126. success: exitCode === 0,
  127. stdout: stdout.trim(),
  128. stderr: stderr.trim(),
  129. exitCode
  130. })
  131. })
  132. nodeProcess.on('error', (error) => {
  133. clearTimeout(timeoutId)
  134. runningProcesses.delete(processKey)
  135. if (!resolved) {
  136. resolved = true
  137. reject(error)
  138. }
  139. })
  140. })
  141. })
  142. // Execute Python script
  143. ipcMain.handle('run-python-script', async (event, scriptName, ...parameters) => {
  144. return new Promise((resolve, reject) => {
  145. let pythonPath = 'python'
  146. if (config.pythonPath?.path) {
  147. const configPythonPath = path.join(config.pythonPath.path, 'python.exe')
  148. if (fs.existsSync(configPythonPath)) {
  149. pythonPath = configPythonPath
  150. }
  151. }
  152. const scriptPath = path.join(__dirname, '../python/scripts', `${scriptName}.py`)
  153. if (!fs.existsSync(scriptPath)) {
  154. reject({
  155. success: false,
  156. error: `Script file not found: ${scriptPath}`,
  157. stderr: `Script file not found: ${scriptPath}`
  158. })
  159. return
  160. }
  161. const pythonProcess = spawn(pythonPath, [scriptPath, ...parameters])
  162. let stdout = ''
  163. let stderr = ''
  164. pythonProcess.stdout.on('data', (data) => {
  165. stdout += data.toString()
  166. })
  167. pythonProcess.stderr.on('data', (data) => {
  168. stderr += data.toString()
  169. })
  170. pythonProcess.on('close', (code) => {
  171. resolve({
  172. success: code === 0,
  173. stdout: stdout.trim(),
  174. stderr: stderr.trim(),
  175. exitCode: code
  176. })
  177. })
  178. pythonProcess.on('error', (error) => {
  179. reject({
  180. success: false,
  181. error: error.message,
  182. stderr: error.message
  183. })
  184. })
  185. })
  186. })
  187. // IPC 实时通信处理
  188. // 处理前端请求(异步,返回 Promise)
  189. ipcMain.handle('ipc-request', async (event, channel, data) => {
  190. // 可以根据不同的 channel 处理不同的请求
  191. // 例如:'run-nodejs', 'get-status' 等
  192. if (channel === 'run-nodejs') {
  193. // 通过 IPC 调用 run-nodejs-script
  194. const { scriptName, ...parameters } = data
  195. return new Promise((resolve, reject) => {
  196. const scriptPath = path.join(__dirname, '../nodejs', `${scriptName}.js`)
  197. const processKey = `${scriptName}-${parameters.join('-')}`
  198. if (runningProcesses.has(processKey)) {
  199. const oldProcess = runningProcesses.get(processKey)
  200. oldProcess.kill()
  201. runningProcesses.delete(processKey)
  202. }
  203. const nodeProcess = spawn('node', [scriptPath, ...Object.values(parameters)])
  204. runningProcesses.set(processKey, nodeProcess)
  205. let stdout = ''
  206. let stderr = ''
  207. let resolved = false
  208. nodeProcess.stdout.on('data', (chunk) => {
  209. stdout += chunk.toString()
  210. try {
  211. const lines = chunk.toString().trim().split('\n')
  212. for (const line of lines) {
  213. if (line.trim().startsWith('{')) {
  214. const json = JSON.parse(line.trim())
  215. if (json.success && !resolved) {
  216. resolved = true
  217. resolve({ success: true, stdout: line.trim(), stderr: stderr.trim(), exitCode: null })
  218. }
  219. }
  220. }
  221. } catch (e) {}
  222. })
  223. nodeProcess.stderr.on('data', (chunk) => {
  224. stderr += chunk.toString()
  225. })
  226. nodeProcess.on('close', (code) => {
  227. runningProcesses.delete(processKey)
  228. if (!resolved) {
  229. resolve({ success: code === 0, stdout: stdout.trim(), stderr: stderr.trim(), exitCode: code })
  230. }
  231. })
  232. nodeProcess.on('error', (error) => {
  233. runningProcesses.delete(processKey)
  234. if (!resolved) {
  235. reject(error)
  236. }
  237. })
  238. setTimeout(() => {
  239. if (!resolved) {
  240. resolved = true
  241. resolve({ success: true, stdout: stdout.trim(), stderr: stderr.trim(), exitCode: null, message: 'Script is running in background' })
  242. }
  243. }, 5000)
  244. })
  245. }
  246. // 默认响应
  247. return { success: true, channel, data, timestamp: Date.now() }
  248. })
  249. // 监听前端发送的消息(不需要响应)
  250. ipcMain.on('ipc-message', (event, channel, data) => {
  251. // 处理前端发送的消息
  252. console.log(`[IPC] Received message on channel "${channel}":`, data)
  253. })
  254. // 推送消息到前端的辅助函数
  255. function pushToFrontend(channel, data) {
  256. if (mainWindowInstance && !mainWindowInstance.isDestroyed()) {
  257. mainWindowInstance.webContents.send(channel, data)
  258. }
  259. }
  260. // 导出推送函数供其他模块使用
  261. global.pushToFrontend = pushToFrontend
  262. app.whenReady().then(() => {
  263. createWindow()
  264. app.on('activate', () => {
  265. if (BrowserWindow.getAllWindows().length === 0) {
  266. createWindow()
  267. }
  268. })
  269. })
  270. app.on('window-all-closed', () => {
  271. if (process.platform !== 'darwin') {
  272. app.quit()
  273. }
  274. })