useWinProcess.ts 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import { ipcMain, BrowserWindow } from 'electron';
  2. import { join } from 'path';
  3. // export
  4. let childrenWindows: BrowserWindow[] = [];
  5. async function handleStartWinProcess(
  6. event: Electron.IpcMainEvent,
  7. processCount: number,
  8. loadPageUrl: string
  9. ) {
  10. if (childrenWindows.length) {
  11. childrenWindows.forEach((win) => win && win.close());
  12. childrenWindows = [] as BrowserWindow[];
  13. }
  14. const parentWindow = BrowserWindow.getFocusedWindow();
  15. if (!parentWindow) return;
  16. const createWins = [] as Promise<BrowserWindow>[];
  17. for (let i = 0; i < processCount; i++) {
  18. createWins.push(buildChildWindow(parentWindow, loadPageUrl));
  19. }
  20. childrenWindows = await Promise.all(createWins);
  21. }
  22. async function buildChildWindow(
  23. parentWindow: BrowserWindow,
  24. loadPageUrl: string
  25. ) {
  26. const childWin = new BrowserWindow({
  27. width: 400,
  28. height: 400,
  29. show: false,
  30. parent: parentWindow,
  31. webPreferences: {
  32. preload: join(__dirname, '../preload/index.js'),
  33. sandbox: false,
  34. },
  35. });
  36. // const exportPdfHash = '#/export-track-pdf';
  37. if (process.env.WEBPACK_DEV_SERVER_URL) {
  38. // Load the url of the dev server if in development mode
  39. await childWin.loadURL(process.env.WEBPACK_DEV_SERVER_URL + loadPageUrl);
  40. // childWin.webContents.openDevTools();
  41. } else {
  42. // Load the index.html when not in development
  43. await childWin.loadURL(`app://./index.html${loadPageUrl}`);
  44. }
  45. return childWin;
  46. }
  47. function handleStopWinProcess() {
  48. if (!childrenWindows.length) return;
  49. childrenWindows.forEach((cwin) => {
  50. cwin.webContents.send('stop-running');
  51. });
  52. }
  53. function handleCloseProcessWindow(event: Electron.IpcMainEvent, winId: number) {
  54. if (!childrenWindows.length) return;
  55. const pos = childrenWindows.findIndex((item) => item.id === winId);
  56. if (pos !== -1) {
  57. childrenWindows[pos].close();
  58. childrenWindows.splice(pos, 1);
  59. }
  60. }
  61. export default function useWinProcess() {
  62. ipcMain.on('start-win-process', handleStartWinProcess);
  63. ipcMain.on('stop-win-process', handleStopWinProcess);
  64. ipcMain.on('close-process-window', handleCloseProcessWindow);
  65. }