| 1 | import { BrowserWindow, ipcMain, type IpcMainInvokeEvent } from 'electron' |
| 2 | |
| 3 | type WindowControlState = { |
| 4 | isFullscreen: boolean |
| 5 | } |
| 6 | |
| 7 | function getSenderWindow(event: IpcMainInvokeEvent): BrowserWindow | null { |
| 8 | const window = BrowserWindow.fromWebContents(event.sender) |
| 9 | return window && !window.isDestroyed() ? window : null |
| 10 | } |
| 11 | |
| 12 | function getWindowState(window: BrowserWindow): WindowControlState { |
| 13 | return { isFullscreen: window.isFullScreen() } |
| 14 | } |
| 15 | |
| 16 | function emitWindowState(window: BrowserWindow): void { |
| 17 | if (!window.isDestroyed()) window.webContents.send('window:control:stateChanged', getWindowState(window)) |
| 18 | } |
| 19 | |
| 20 | export function registerWindowControlHandlers(): void { |
| 21 | ipcMain.handle('window:control:getState', (event): WindowControlState => { |
| 22 | const window = getSenderWindow(event) |
| 23 | return { isFullscreen: window?.isFullScreen() ?? false } |
| 24 | }) |
| 25 | |
| 26 | ipcMain.handle('window:control:minimize', (event): void => { |
| 27 | getSenderWindow(event)?.minimize() |
| 28 | }) |
| 29 | |
| 30 | ipcMain.handle('window:control:toggleFullscreen', (event): WindowControlState => { |
| 31 | const window = getSenderWindow(event) |
| 32 | if (!window) return { isFullscreen: false } |
| 33 | |
| 34 | window.setFullScreen(!window.isFullScreen()) |
| 35 | return getWindowState(window) |
| 36 | }) |
| 37 | |
| 38 | ipcMain.handle('window:control:close', (event): void => { |
| 39 | getSenderWindow(event)?.close() |
| 40 | }) |
| 41 | } |
| 42 | |
| 43 | export function attachWindowControlStateEvents(window: BrowserWindow): void { |
| 44 | window.on('enter-full-screen', () => emitWindowState(window)) |
| 45 | window.on('leave-full-screen', () => emitWindowState(window)) |
| 46 | window.webContents.on('before-input-event', (event, input) => { |
| 47 | if (!window.isFullScreen() || input.type !== 'keyDown' || input.key !== 'Escape') return |
| 48 | event.preventDefault() |
| 49 | window.setFullScreen(false) |
| 50 | }) |
| 51 | } |
| 52 |