main.js 17 KB

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