window.ts 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. import type {BrowserWindowConstructorOptions} from 'electron';
  2. import {app, BrowserWindow, dialog} from 'electron';
  3. import path from 'path';
  4. import {_PATHS} from '../paths';
  5. import {$env, isDev} from '../env';
  6. import {createTray} from './tray';
  7. // 获取公共窗口选项
  8. export function getBrowserWindowOptions(options?: BrowserWindowConstructorOptions): BrowserWindowConstructorOptions {
  9. return {
  10. width: 1200,
  11. height: 800,
  12. webPreferences: {
  13. preload: path.join(_PATHS.preloadRoot, 'index.js'),
  14. nodeIntegration: false,
  15. contextIsolation: true,
  16. },
  17. // 应用图标
  18. icon: isDev ? _PATHS.appIcon : void 0,
  19. ...options,
  20. }
  21. }
  22. // 创建窗口
  23. export function createBrowserWindow(options?: BrowserWindowConstructorOptions) {
  24. const win = new BrowserWindow(getBrowserWindowOptions(options));
  25. // 代码逻辑说明: 【JHHB-13】桌面应用消息通知
  26. if (process.platform === 'darwin') { // 仅 macOS 生效
  27. if (app.dock) {
  28. app.dock.setIcon(path.join(_PATHS.electronRoot, './icons/mac/dock.png').replace(/[\\/]dist[\\/]/, '/'));
  29. }
  30. }
  31. // 设置窗口打开处理器
  32. win.webContents.setWindowOpenHandler(() => {
  33. return {
  34. action: 'allow',
  35. // 覆写新窗口的选项,用于调整默认尺寸和加载preload脚本等
  36. overrideBrowserWindowOptions: getBrowserWindowOptions(),
  37. }
  38. });
  39. // 当 beforeunload 阻止窗口关闭时触发
  40. win.webContents.on('will-prevent-unload', () => {
  41. const choice = dialog.showMessageBoxSync(win, {
  42. type: 'question',
  43. title: '确认关闭吗?',
  44. message: '系统可能不会保存您所做的更改。',
  45. buttons: ['关闭', '取消'],
  46. defaultId: 1,
  47. cancelId: 1,
  48. noLink: true,
  49. });
  50. // 用户选择了关闭,直接销毁窗口
  51. if (choice === 0) {
  52. win.destroy();
  53. }
  54. });
  55. return win;
  56. }
  57. // 创建主窗口、系统托盘
  58. export function createMainWindow() {
  59. const win = createIndexWindow()
  60. // 设置系统托盘图标
  61. createTray(win);
  62. // 主窗口尝试关闭时,默认不直接退出应用,而是隐藏到托盘
  63. win.on('close', (event) => {
  64. event.preventDefault();
  65. win.hide();
  66. });
  67. return win;
  68. }
  69. // 创建索引窗口
  70. export function createIndexWindow() {
  71. const win = createBrowserWindow({
  72. width: 1600,
  73. height: 1000,
  74. title: $env.VITE_GLOB_APP_TITLE!,
  75. });
  76. // 开发环境加载Vite服务,生产加载打包文件
  77. if (isDev) {
  78. let serverUrl = $env.VITE_DEV_SERVER_URL! as string;
  79. // 【JHHB-936】由于wps预览不能使用localhost访问,所以把localhost替换为127.0.0.1
  80. serverUrl = serverUrl.replace('localhost', '127.0.0.1');
  81. win.loadURL(serverUrl)
  82. // 开发环境下,自动打开调试工具
  83. // win.webContents.openDevTools()
  84. } else {
  85. win.loadFile(path.join(_PATHS.publicRoot, 'index.html'));
  86. }
  87. return win;
  88. }