main.js 17 KB

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