main.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  1. const { app, BrowserWindow, ipcMain } = require('electron')
  2. const path = require('path')
  3. const os = require('os')
  4. const fs = require('fs')
  5. const unpackedRoot = app.isPackaged
  6. ? path.join(path.dirname(process.execPath), 'resources', 'app.asar.unpacked')
  7. : path.join(__dirname, '..')
  8. // static 不打包,放在打包根目录(与 exe 同级)作为沙盒目录
  9. const sandboxRoot = app.isPackaged ? path.dirname(process.execPath) : path.join(__dirname, '..')
  10. const staticDir = path.join(sandboxRoot, 'static')
  11. if (!fs.existsSync(staticDir)) {
  12. fs.mkdirSync(staticDir, { recursive: true })
  13. }
  14. const config = require(path.join(unpackedRoot, 'configs', 'config.js'))
  15. const isDev = process.env.NODE_ENV === 'development' || !app.isPackaged
  16. // Set Content-Security-Policy for packaged app (removes Electron security warning in production)
  17. if (!isDev) {
  18. const { session } = require('electron')
  19. session.defaultSession.webRequest.onHeadersReceived((details, callback) => {
  20. const url = details.url || ''
  21. if (url.startsWith('file://')) {
  22. const csp = "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:"
  23. callback({ responseHeaders: { ...details.responseHeaders, 'Content-Security-Policy': [csp] } })
  24. } else {
  25. callback({ responseHeaders: details.responseHeaders })
  26. }
  27. })
  28. }
  29. // 打包后:userData 放在 exe 同目录 UserData,实现「开包即用」— 整包复制到任意电脑即可使用
  30. // 开发时:使用临时目录,避免污染项目
  31. if (process.platform === 'win32') {
  32. const userDataPath = app.isPackaged
  33. ? path.join(sandboxRoot, 'UserData')
  34. : path.join(os.tmpdir(), 'AndroidRemoteController')
  35. if (!fs.existsSync(userDataPath)) {
  36. fs.mkdirSync(userDataPath, { recursive: true })
  37. }
  38. const cacheDir = path.join(userDataPath, 'Cache')
  39. const gpuCacheDir = path.join(userDataPath, 'GPUCache')
  40. if (!fs.existsSync(cacheDir)) fs.mkdirSync(cacheDir, { recursive: true })
  41. if (!fs.existsSync(gpuCacheDir)) fs.mkdirSync(gpuCacheDir, { recursive: true })
  42. app.setPath('userData', userDataPath)
  43. app.commandLine.appendSwitch('disk-cache-dir', cacheDir)
  44. app.commandLine.appendSwitch('gpu-disk-cache-dir', gpuCacheDir)
  45. app.commandLine.appendSwitch('disable-gpu-shader-disk-cache')
  46. }
  47. // 保存主窗口引用,用于推送消息
  48. let mainWindowInstance = null
  49. // 启动日志:写入 userData/startup.log,便于排查“无 UI”问题
  50. const startupLogPath = path.join(app.getPath('userData'), 'startup.log')
  51. function startupLog (msg) {
  52. const line = `[${new Date().toISOString()}] ${msg}\n`
  53. try {
  54. fs.appendFileSync(startupLogPath, line)
  55. } catch (e) {}
  56. console.log(msg)
  57. }
  58. function createWindow() {
  59. startupLog(`createWindow: isPackaged=${app.isPackaged} isDev=${isDev} unpackedRoot=${unpackedRoot}`)
  60. const mainWindow = new BrowserWindow({
  61. width: config.window.width,
  62. height: config.window.height,
  63. autoHideMenuBar: config.window.autoHideMenuBar, // 从配置文件读取
  64. webPreferences: {
  65. nodeIntegration: false,
  66. contextIsolation: true,
  67. preload: path.join(__dirname, 'preload.js')
  68. }
  69. })
  70. // 保存窗口引用
  71. mainWindowInstance = mainWindow
  72. if (isDev) {
  73. const vitePort = config.vite?.port || 5173
  74. const viteHost = config.vite?.host || 'localhost'
  75. startupLog(`Loading Vite dev server at http://${viteHost}:${vitePort}`)
  76. // Clear cache before dev load to avoid ERR_CACHE_READ_FAILURE with react-refresh
  77. mainWindow.webContents.session.clearCache().then(() => {
  78. mainWindow.loadURL(`http://${viteHost}:${vitePort}`)
  79. })
  80. // 根据配置文件决定是否打开调试侧边栏
  81. if (config.devTools.enabled) {
  82. mainWindow.webContents.openDevTools()
  83. }
  84. } else {
  85. // 前端 dist(含 assets)通过 extraFiles 拷贝到 exe 同级 dist/,从沙盒根加载
  86. const indexPath = path.join(sandboxRoot, 'dist', 'index.html')
  87. const indexExists = fs.existsSync(indexPath)
  88. startupLog(`Packaged load: index.html path=${indexPath} exists=${indexExists}`)
  89. if (!indexExists) {
  90. startupLog('ERROR: dist/index.html 不存在,请先 npm run build 再打包,并确认 extraFiles 含 dist')
  91. }
  92. mainWindow.webContents.on('did-fail-load', (event, errorCode, errorDescription, validatedURL, isMainFrame) => {
  93. startupLog(`did-fail-load: mainFrame=${isMainFrame} code=${errorCode} desc=${errorDescription} url=${validatedURL}`)
  94. })
  95. mainWindow.webContents.on('did-finish-load', () => {
  96. startupLog(`did-finish-load: url=${mainWindow.webContents.getURL()}`)
  97. })
  98. mainWindow.loadFile(indexPath)
  99. }
  100. startupLog(`启动日志文件: ${startupLogPath}`)
  101. }
  102. const { spawn } = require('child_process')
  103. // 存储运行中的进程
  104. const runningProcesses = new Map()
  105. // Execute Node.js script
  106. ipcMain.handle('run-nodejs-script', async (event, scriptName, ...parameters) => {
  107. return new Promise((resolve, reject) => {
  108. const scriptPath = path.join(unpackedRoot, 'nodejs', `${scriptName}.js`)
  109. const processKey = `${scriptName}-${parameters.join('-')}`
  110. // 如果进程已运行,先停止它
  111. if (runningProcesses.has(processKey)) {
  112. const oldProcess = runningProcesses.get(processKey)
  113. oldProcess.kill()
  114. runningProcesses.delete(processKey)
  115. }
  116. const nodeProcess = spawn('node', [scriptPath, ...parameters], {
  117. env: { ...process.env, STATIC_ROOT: staticDir },
  118. cwd: unpackedRoot
  119. })
  120. runningProcesses.set(processKey, nodeProcess)
  121. let stdout = ''
  122. let stderr = ''
  123. let resolved = false
  124. const finish = (result) => {
  125. if (resolved) return
  126. resolved = true
  127. resolve(result)
  128. }
  129. nodeProcess.stdout.on('data', (data) => {
  130. const dataStr = data.toString()
  131. stdout += dataStr
  132. const isLongRunning = scriptName.includes('screenshot') || scriptName.includes('adb/')
  133. try {
  134. const lines = dataStr.trim().split('\n')
  135. for (const line of lines) {
  136. if (line.trim().startsWith('{')) {
  137. const json = JSON.parse(line.trim())
  138. if (json.success && isLongRunning) {
  139. finish({ success: true, stdout: line.trim(), stderr: stderr.trim(), exitCode: null })
  140. return
  141. }
  142. }
  143. }
  144. } catch (e) {}
  145. })
  146. nodeProcess.stderr.on('data', (data) => {
  147. stderr += data.toString()
  148. })
  149. const waitForExit = scriptName === 'run-process' || scriptName === 'enable-wirless-connect'
  150. const timeoutId = waitForExit ? null : setTimeout(() => {
  151. if (!resolved) {
  152. finish({
  153. success: false,
  154. stdout: stdout.trim(),
  155. stderr: stderr.trim(),
  156. exitCode: 1,
  157. message: 'Script is running in background'
  158. })
  159. }
  160. }, 5000)
  161. nodeProcess.on('close', (code) => {
  162. if (timeoutId) clearTimeout(timeoutId)
  163. runningProcesses.delete(processKey)
  164. const exitCode = (code !== null && code !== undefined) ? code : 1
  165. finish({
  166. success: exitCode === 0,
  167. stdout: stdout.trim(),
  168. stderr: stderr.trim(),
  169. exitCode
  170. })
  171. })
  172. nodeProcess.on('error', (error) => {
  173. clearTimeout(timeoutId)
  174. runningProcesses.delete(processKey)
  175. if (!resolved) {
  176. resolved = true
  177. reject(error)
  178. }
  179. })
  180. })
  181. })
  182. /** 停止指定的 Node.js 脚本进程 */
  183. ipcMain.handle('kill-nodejs-script', async (event, scriptName, ...parameters) => {
  184. const processKey = `${scriptName}-${parameters.join('-')}`
  185. if (runningProcesses.has(processKey)) {
  186. runningProcesses.get(processKey).kill()
  187. runningProcesses.delete(processKey)
  188. return { killed: true }
  189. }
  190. return { killed: false }
  191. })
  192. /** 检查 scrcpy 是否仍在运行(读 pid 文件并用 process.kill(pid,0) 探测),用于用户直接关窗口时同步按钮状态 */
  193. ipcMain.handle('check-scrcpy-running', async () => {
  194. const pidFile = path.join(staticDir, 'scrcpy-pid.json')
  195. if (!fs.existsSync(pidFile)) return { running: false }
  196. let pid
  197. try {
  198. pid = JSON.parse(fs.readFileSync(pidFile, 'utf-8')).pid
  199. } catch (_) {
  200. return { running: false }
  201. }
  202. try {
  203. process.kill(pid, 0)
  204. return { running: true }
  205. } catch (_) {
  206. return { running: false }
  207. }
  208. })
  209. // Execute Python script
  210. ipcMain.handle('run-python-script', async (event, scriptName, ...parameters) => {
  211. return new Promise((resolve, reject) => {
  212. let pythonPath = 'python'
  213. if (config.pythonPath?.path) {
  214. const configPythonPath = path.join(config.pythonPath.path, 'python.exe')
  215. if (fs.existsSync(configPythonPath)) {
  216. pythonPath = configPythonPath
  217. }
  218. }
  219. const scriptPath = path.join(unpackedRoot, 'python', 'scripts', `${scriptName}.py`)
  220. if (!fs.existsSync(scriptPath)) {
  221. reject({
  222. success: false,
  223. error: `Script file not found: ${scriptPath}`,
  224. stderr: `Script file not found: ${scriptPath}`
  225. })
  226. return
  227. }
  228. const pythonProcess = spawn(pythonPath, [scriptPath, ...parameters])
  229. let stdout = ''
  230. let stderr = ''
  231. pythonProcess.stdout.on('data', (data) => {
  232. stdout += data.toString()
  233. })
  234. pythonProcess.stderr.on('data', (data) => {
  235. stderr += data.toString()
  236. })
  237. pythonProcess.on('close', (code) => {
  238. resolve({
  239. success: code === 0,
  240. stdout: stdout.trim(),
  241. stderr: stderr.trim(),
  242. exitCode: code
  243. })
  244. })
  245. pythonProcess.on('error', (error) => {
  246. reject({
  247. success: false,
  248. error: error.message,
  249. stderr: error.message
  250. })
  251. })
  252. })
  253. })
  254. // IPC 实时通信处理
  255. // 处理前端请求(异步,返回 Promise)
  256. ipcMain.handle('ipc-request', async (event, channel, data) => {
  257. // 可以根据不同的 channel 处理不同的请求
  258. // 例如:'run-nodejs', 'get-status' 等
  259. if (channel === 'run-nodejs') {
  260. // 通过 IPC 调用 run-nodejs-script
  261. const { scriptName, ...parameters } = data
  262. return new Promise((resolve, reject) => {
  263. const scriptPath = path.join(unpackedRoot, 'nodejs', `${scriptName}.js`)
  264. const processKey = `${scriptName}-${parameters.join('-')}`
  265. if (runningProcesses.has(processKey)) {
  266. const oldProcess = runningProcesses.get(processKey)
  267. oldProcess.kill()
  268. runningProcesses.delete(processKey)
  269. }
  270. const nodeProcess = spawn('node', [scriptPath, ...Object.values(parameters)], {
  271. env: { ...process.env, STATIC_ROOT: staticDir },
  272. cwd: unpackedRoot
  273. })
  274. runningProcesses.set(processKey, nodeProcess)
  275. let stdout = ''
  276. let stderr = ''
  277. let resolved = false
  278. nodeProcess.stdout.on('data', (chunk) => {
  279. stdout += chunk.toString()
  280. try {
  281. const lines = chunk.toString().trim().split('\n')
  282. for (const line of lines) {
  283. if (line.trim().startsWith('{')) {
  284. const json = JSON.parse(line.trim())
  285. if (json.success && !resolved) {
  286. resolved = true
  287. resolve({ success: true, stdout: line.trim(), stderr: stderr.trim(), exitCode: null })
  288. }
  289. }
  290. }
  291. } catch (e) {}
  292. })
  293. nodeProcess.stderr.on('data', (chunk) => {
  294. stderr += chunk.toString()
  295. })
  296. nodeProcess.on('close', (code) => {
  297. runningProcesses.delete(processKey)
  298. if (!resolved) {
  299. resolve({ success: code === 0, stdout: stdout.trim(), stderr: stderr.trim(), exitCode: code })
  300. }
  301. })
  302. nodeProcess.on('error', (error) => {
  303. runningProcesses.delete(processKey)
  304. if (!resolved) {
  305. reject(error)
  306. }
  307. })
  308. setTimeout(() => {
  309. if (!resolved) {
  310. resolved = true
  311. resolve({ success: true, stdout: stdout.trim(), stderr: stderr.trim(), exitCode: null, message: 'Script is running in background' })
  312. }
  313. }, 5000)
  314. })
  315. }
  316. // 默认响应
  317. return { success: true, channel, data, timestamp: Date.now() }
  318. })
  319. // 监听前端发送的消息(不需要响应)
  320. ipcMain.on('ipc-message', (event, channel, data) => {
  321. // 处理前端发送的消息
  322. console.log(`[IPC] Received message on channel "${channel}":`, data)
  323. })
  324. // 推送消息到前端的辅助函数
  325. function pushToFrontend(channel, data) {
  326. if (mainWindowInstance && !mainWindowInstance.isDestroyed()) {
  327. mainWindowInstance.webContents.send(channel, data)
  328. }
  329. }
  330. // 导出推送函数供其他模块使用
  331. global.pushToFrontend = pushToFrontend
  332. app.whenReady().then(() => {
  333. startupLog('========== 本次启动 ==========')
  334. createWindow()
  335. app.on('activate', () => {
  336. if (BrowserWindow.getAllWindows().length === 0) {
  337. createWindow()
  338. }
  339. })
  340. })
  341. // 退出时结束 adb.exe,避免残留在后台
  342. function killAdbOnExit() {
  343. try {
  344. if (process.platform === 'win32') {
  345. require('child_process').execSync('taskkill /IM adb.exe /F', { stdio: 'ignore', windowsHide: true })
  346. } else {
  347. require('child_process').execSync('pkill -x adb || true', { stdio: 'ignore' })
  348. }
  349. } catch (e) {}
  350. }
  351. app.on('before-quit', () => {
  352. killAdbOnExit()
  353. })
  354. app.on('window-all-closed', () => {
  355. if (process.platform !== 'darwin') {
  356. app.quit()
  357. }
  358. })