main.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  1. import { app, BrowserWindow, Event, Input, ipcMain, Menu, WebContentsView } from 'electron'
  2. import { fileURLToPath } from 'node:url'
  3. import path from 'node:path'
  4. import fs from 'node:fs'
  5. const __dirname = path.dirname(fileURLToPath(import.meta.url))
  6. // The built directory structure
  7. //
  8. // ├─┬─┬ dist
  9. // │ │ └── index.html
  10. // │ │
  11. // │ ├─┬ dist-electron
  12. // │ │ ├── main.js
  13. // │ │ └── preload.mjs
  14. // │
  15. process.env.APP_ROOT = path.join(__dirname, '..')
  16. // 🚧 Use ['ENV_NAME'] avoid vite:define plugin - Vite@2.x
  17. export const VITE_DEV_SERVER_URL = process.env['VITE_DEV_SERVER_URL']
  18. export const MAIN_DIST = path.join(process.env.APP_ROOT, 'dist-electron')
  19. export const RENDERER_DIST = path.join(process.env.APP_ROOT, 'dist')
  20. process.env.VITE_PUBLIC = VITE_DEV_SERVER_URL ? path.join(process.env.APP_ROOT, 'public') : RENDERER_DIST
  21. let mainWindow: BrowserWindow | null
  22. let childView: WebContentsView | null
  23. let isSideOpen = true
  24. let childViewAspectRatio = 0;
  25. const SIDE_WIDTH = 250
  26. const EXPAND_VIEW_SIZE = 40
  27. const LOADING_VIEW_WIDTH = 150
  28. const LOADING_VIEW_HEIGHT = 100
  29. function loadWindowPage(window: BrowserWindow, subPath: string) {
  30. if (VITE_DEV_SERVER_URL) {
  31. window.loadURL(VITE_DEV_SERVER_URL + "#" + subPath)
  32. } else {
  33. window.loadFile(path.join(RENDERER_DIST, 'index.html'), {
  34. hash: subPath,
  35. })
  36. }
  37. }
  38. function loadViewUrl(view: WebContentsView, subPath: string) {
  39. if (!mainWindow) {
  40. return
  41. }
  42. if (VITE_DEV_SERVER_URL) {
  43. view.webContents.loadURL(VITE_DEV_SERVER_URL + "#" + subPath)
  44. } else {
  45. view.webContents.loadFile(path.join(RENDERER_DIST, 'index.html'), {
  46. hash: subPath,
  47. })
  48. }
  49. }
  50. Menu.setApplicationMenu(null)
  51. function createWindow() {
  52. mainWindow = new BrowserWindow({
  53. icon: path.join(process.env.VITE_PUBLIC, 'icon.ico'),
  54. webPreferences: {
  55. preload: path.join(__dirname, 'preload.mjs'),
  56. contextIsolation: true,
  57. allowRunningInsecureContent: true,
  58. },
  59. width: 1200,
  60. height: 800,
  61. })
  62. childView = new WebContentsView({
  63. webPreferences: {
  64. allowRunningInsecureContent: true,
  65. },
  66. })
  67. const expandButtonView = new WebContentsView({
  68. webPreferences: {
  69. preload: path.join(__dirname, 'preload.mjs'),
  70. contextIsolation: true,
  71. },
  72. })
  73. const loadingView = new BrowserWindow({
  74. skipTaskbar: true,
  75. width: LOADING_VIEW_WIDTH,
  76. height: LOADING_VIEW_HEIGHT,
  77. parent: mainWindow,
  78. thickFrame: true,
  79. titleBarStyle: 'hidden',
  80. webPreferences: {
  81. preload: path.join(__dirname, 'preload.mjs'),
  82. contextIsolation: true,
  83. },
  84. })
  85. mainWindow.contentView.addChildView(childView)
  86. mainWindow.contentView.addChildView(expandButtonView)
  87. expandButtonView.setVisible(false)
  88. childView.webContents.on('did-start-loading', () => {
  89. loadingView.show()
  90. });
  91. childView.webContents.on('did-stop-loading', () => {
  92. loadingView.hide()
  93. });
  94. childView.webContents.on('did-fail-load', (_, errorCode, errorDescription) => {
  95. loadingView.hide()
  96. loadWindowPage(loadingView, '/error?code=' + errorCode + '&message=' + errorDescription);
  97. });
  98. function updateChildWindowBounds() {
  99. const bounds = mainWindow!.getBounds();
  100. expandButtonView.setBounds({
  101. x: 0,
  102. y: bounds.height - 100,
  103. width: EXPAND_VIEW_SIZE,
  104. height: EXPAND_VIEW_SIZE
  105. })
  106. loadingView.setBounds({
  107. x: bounds.x + (bounds.width - LOADING_VIEW_WIDTH) / 2,
  108. y: bounds.y + (bounds.height - LOADING_VIEW_HEIGHT) / 2,
  109. width: LOADING_VIEW_WIDTH,
  110. height: LOADING_VIEW_HEIGHT
  111. })
  112. if (childViewAspectRatio) {
  113. // 保持子页纵横比
  114. const rect = {
  115. x: isSideOpen ? SIDE_WIDTH : 0,
  116. y: 0,
  117. width: bounds.width - (isSideOpen ? SIDE_WIDTH : 0),
  118. height: bounds.height
  119. };
  120. // 计算子窗口的最佳尺寸(contain模式)
  121. const availableRatio = rect.width / rect.height;
  122. let childWidth, childHeight;
  123. if (availableRatio > childViewAspectRatio) {
  124. // 高度受限制
  125. childHeight = rect.height;
  126. childWidth = childHeight * childViewAspectRatio;
  127. } else {
  128. // 宽度受限制
  129. childWidth = rect.width;
  130. childHeight = childWidth / childViewAspectRatio;
  131. }
  132. // 计算居中位置
  133. const childX = rect.x + (rect.width - childWidth) / 2;
  134. const childY = rect.y + (rect.height - childHeight) / 2;
  135. // 应用到子窗口
  136. childView!.setBounds({
  137. x: Math.round(childX),
  138. y: Math.round(childY),
  139. width: Math.round(childWidth),
  140. height: Math.round(childHeight)
  141. });
  142. } else {
  143. childView!.setBounds({
  144. x: isSideOpen ? SIDE_WIDTH : 0,
  145. y: 0,
  146. width: bounds.width - (isSideOpen ? SIDE_WIDTH : 0),
  147. height: bounds.height
  148. });
  149. }
  150. }
  151. loadWindowPage(mainWindow, '/');
  152. loadWindowPage(loadingView, '/loading');
  153. loadViewUrl(childView, '/hello');
  154. loadViewUrl(expandButtonView, '/expand');
  155. updateChildWindowBounds();
  156. mainWindow.on('resize', () => {
  157. updateChildWindowBounds()
  158. })
  159. mainWindow.webContents.on('did-finish-load', () => {
  160. mainWindow?.webContents.send('main-process-message', (new Date).toLocaleString())
  161. })
  162. function handleWindowFullScreenKeys(event: Event, input: Input) {
  163. if (input.key === 'F11' && input.type === 'keyDown') {
  164. event.preventDefault();
  165. mainWindow?.setFullScreen(!mainWindow?.isFullScreen())
  166. } else if (input.key === 'F12' && input.type === 'keyDown') {
  167. event.preventDefault();
  168. mainWindow?.webContents.toggleDevTools();
  169. }
  170. }
  171. // 添加F11全屏切换功能
  172. mainWindow.webContents.on('before-input-event', (event, input) => {
  173. handleWindowFullScreenKeys(event, input)
  174. })
  175. childView.webContents.on('before-input-event', (event, input) => {
  176. handleWindowFullScreenKeys(event, input)
  177. })
  178. // 处理退出应用事件
  179. ipcMain.on('exit-app', () => {
  180. app.quit()
  181. })
  182. // 处理全屏切换事件
  183. ipcMain.on('toggle-fullscreen', (_event, isFullScreen: boolean) => {
  184. if (mainWindow) {
  185. if (isFullScreen) {
  186. mainWindow.setFullScreen(true)
  187. } else {
  188. mainWindow.setFullScreen(false)
  189. }
  190. }
  191. })
  192. // 加载子页URL
  193. ipcMain.on('load-child-url', (_event, url: string, aspectRatio: number) => {
  194. if (childView)
  195. childView.webContents.loadURL(url)
  196. childViewAspectRatio = aspectRatio
  197. updateChildWindowBounds()
  198. })
  199. // 子页侧边栏开关
  200. ipcMain.on('toggle-child-side', (_event, value: boolean) => {
  201. isSideOpen = value
  202. expandButtonView.setVisible(!isSideOpen)
  203. mainWindow?.webContents.send('main-side-state-changed', isSideOpen)
  204. updateChildWindowBounds()
  205. })
  206. // 处理获取应用路径事件
  207. ipcMain.handle('get-app-path', () => {
  208. return app.getAppPath()
  209. })
  210. // 处理打开窗口事件
  211. ipcMain.on('open-window', (_event, url: string) => {
  212. const newWin = new BrowserWindow({
  213. icon: path.join(process.env.VITE_PUBLIC, 'icon.ico'),
  214. webPreferences: {
  215. preload: path.join(__dirname, 'preload.mjs'),
  216. contextIsolation: true,
  217. allowRunningInsecureContent: true,
  218. },
  219. fullscreenable: true,
  220. maximizable: true,
  221. width: 1200,
  222. height: 800,
  223. })
  224. newWin.loadURL(url)
  225. newWin.maximize();
  226. // 添加F11全屏切换功能
  227. newWin.webContents.on('before-input-event', (event, input) => {
  228. if (input.key === 'F11' && input.type === 'keyDown') {
  229. event.preventDefault();
  230. newWin?.setFullScreen(!newWin?.fullScreen)
  231. } else if (input.key === 'F12' && input.type === 'keyDown') {
  232. event.preventDefault();
  233. newWin?.webContents.toggleDevTools();
  234. }
  235. })
  236. })
  237. // 处理加载apps.json事件
  238. ipcMain.handle('load-apps-json', async () => {
  239. const appPath = process.cwd()
  240. const appsJsonPath = path.join(appPath, 'apps.json')
  241. try {
  242. if (fs.existsSync(appsJsonPath)) {
  243. const data = fs.readFileSync(appsJsonPath, 'utf8')
  244. return JSON.parse(data)
  245. } else {
  246. // 开发环境下回退到public目录
  247. const devAppsJsonPath = path.join(process.env.VITE_PUBLIC || '', 'apps.json')
  248. if (fs.existsSync(devAppsJsonPath)) {
  249. const data = fs.readFileSync(devAppsJsonPath, 'utf8')
  250. return JSON.parse(data)
  251. }
  252. throw new Error('apps.json not found')
  253. }
  254. } catch (error) {
  255. console.error('Error loading apps.json:', error)
  256. throw error
  257. }
  258. })
  259. // 处理加载默认apps.json事件
  260. ipcMain.handle('load-default-apps-json', async () => {
  261. const devAppsJsonPath = path.join(process.env.VITE_PUBLIC || '', 'apps.json')
  262. if (fs.existsSync(devAppsJsonPath)) {
  263. const data = fs.readFileSync(devAppsJsonPath, 'utf8')
  264. return JSON.parse(data)
  265. }
  266. throw new Error('apps.json not found')
  267. })
  268. // 处理显示配置窗口事件
  269. ipcMain.on('show-config', () => {
  270. const configWindow = new BrowserWindow({
  271. icon: path.join(process.env.VITE_PUBLIC, 'icon.ico'),
  272. webPreferences: {
  273. preload: path.join(__dirname, 'preload.mjs'),
  274. contextIsolation: true,
  275. allowRunningInsecureContent: true,
  276. },
  277. title: '列表配置',
  278. parent: mainWindow || undefined,
  279. skipTaskbar: true,
  280. minimizable: false,
  281. maximizable: false,
  282. modal: true,
  283. width: 800,
  284. height: 600,
  285. })
  286. loadWindowPage(configWindow, '/config')
  287. });
  288. // 处理保存apps.json事件
  289. ipcMain.on('save-apps-json', (_event, appsJson: string) => {
  290. const appPath = process.cwd()
  291. const appsJsonPath = path.join(appPath, 'apps.json')
  292. try {
  293. fs.writeFileSync(appsJsonPath, appsJson)
  294. mainWindow?.webContents.send('main-config-changed')
  295. } catch (error) {
  296. console.error('Error saving apps.json:', error)
  297. throw error
  298. }
  299. })
  300. // 处理显示关于窗口事件
  301. ipcMain.on('show-about', () => {
  302. const aboutWindow = new BrowserWindow({
  303. icon: path.join(process.env.VITE_PUBLIC, 'icon.ico'),
  304. webPreferences: {
  305. preload: path.join(__dirname, 'preload.mjs'),
  306. contextIsolation: true,
  307. allowRunningInsecureContent: true,
  308. },
  309. parent: mainWindow || undefined,
  310. title: '关于程序',
  311. skipTaskbar: true,
  312. maximizable: false,
  313. minimizable: false,
  314. modal: true,
  315. width: 450,
  316. height: 470,
  317. })
  318. loadWindowPage(aboutWindow, '/about')
  319. });
  320. }
  321. // Quit when all mainWindowdows are closed, except on macOS. There, it's common
  322. // for applications and their menu bar to stay active until the user quits
  323. // explicitly with Cmd + Q.
  324. app.on('window-all-closed', () => {
  325. if (process.platform !== 'darwin') {
  326. app.quit()
  327. mainWindow = null
  328. }
  329. })
  330. app.on('activate', () => {
  331. // On OS X it's common to re-create a mainWindowdow in the app when the
  332. // dock icon is clicked and there are no other mainWindowdows open.
  333. if (BrowserWindow.getAllWindows().length === 0) {
  334. createWindow()
  335. }
  336. })
  337. app.whenReady().then(createWindow)