window-helpers.ts 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. import { expect } from 'chai';
  2. import { BrowserWindow } from 'electron/main';
  3. import { emittedOnce } from './events-helpers';
  4. async function ensureWindowIsClosed (window: BrowserWindow | null) {
  5. if (window && !window.isDestroyed()) {
  6. if (window.webContents && !window.webContents.isDestroyed()) {
  7. // If a window isn't destroyed already, and it has non-destroyed WebContents,
  8. // then calling destroy() won't immediately destroy it, as it may have
  9. // <webview> children which need to be destroyed first. In that case, we
  10. // await the 'closed' event which signals the complete shutdown of the
  11. // window.
  12. const isClosed = emittedOnce(window, 'closed');
  13. window.destroy();
  14. await isClosed;
  15. } else {
  16. // If there's no WebContents or if the WebContents is already destroyed,
  17. // then the 'closed' event has already been emitted so there's nothing to
  18. // wait for.
  19. window.destroy();
  20. }
  21. }
  22. }
  23. export const closeWindow = async (
  24. window: BrowserWindow | null = null,
  25. { assertNotWindows } = { assertNotWindows: true }
  26. ) => {
  27. await ensureWindowIsClosed(window);
  28. if (assertNotWindows) {
  29. const windows = BrowserWindow.getAllWindows();
  30. try {
  31. expect(windows).to.have.lengthOf(0);
  32. } finally {
  33. for (const win of windows) {
  34. await ensureWindowIsClosed(win);
  35. }
  36. }
  37. }
  38. };
  39. export async function closeAllWindows () {
  40. for (const w of BrowserWindow.getAllWindows()) {
  41. await closeWindow(w, { assertNotWindows: false });
  42. }
  43. }