main.js 12 KB

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