useWinProcess.ts 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. webSecurity: false,
  35. },
  36. });
  37. const pageUrl = `${loadPageUrl}&winId=${childWin.id}`;
  38. if (process.env.ELECTRON_RENDERER_URL) {
  39. // Load the url of the dev server if in development mode
  40. await childWin.loadURL(process.env.ELECTRON_RENDERER_URL + pageUrl);
  41. // childWin.webContents.openDevTools();
  42. } else {
  43. // Load the index.html when not in development
  44. await childWin.loadFile(join(__dirname, '../renderer/index.html'), {
  45. hash: pageUrl,
  46. });
  47. }
  48. return childWin;
  49. }
  50. function handleStopWinProcess() {
  51. if (!childrenWindows.length) return;
  52. childrenWindows.forEach((cwin) => {
  53. cwin.webContents.send('stop-running');
  54. });
  55. }
  56. function handleCloseProcessWindow(event: Electron.IpcMainEvent, winId: number) {
  57. if (!childrenWindows.length) return;
  58. const pos = childrenWindows.findIndex((item) => item.id === winId);
  59. if (pos !== -1) {
  60. childrenWindows[pos].close();
  61. childrenWindows.splice(pos, 1);
  62. }
  63. }
  64. export default function useWinProcess() {
  65. ipcMain.on('start-win-process', handleStartWinProcess);
  66. ipcMain.on('stop-win-process', handleStopWinProcess);
  67. ipcMain.on('close-process-window', handleCloseProcessWindow);
  68. }