main.js 16 KB

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