import { IpcMain, IpcRenderer, ipcMain, ipcRenderer } from 'electron' import { Event } from './Events' export interface EventBusInterface { subscribe(event: Event, callback:(msg: MessageType) => void): void unsubscribeAll(event: Event): void emit(event: Event, msg: MessageType): void unsubscribe(event: Event, callback: any): void } interface CallbackStore { wrappedCallback: any callback: any } class IpcMainEventBus implements EventBusInterface { private ipc: IpcMain private client: any constructor(ipc: IpcMain) { this.ipc = ipc } public subscribe(event: Event, callback:(msg: MessageType) => void) { console.log('subscribing', event.topic) this.ipc.on(event.topic, (event: any, arg: any) => { this.client = event.sender callback(arg) }) } public unsubscribeAll(event: Event) { this.ipc.removeAllListeners(event.topic) } public unsubscribe(event: Event, callback: any) { throw new Error('Not implemented') // Todo: implement } public emit(event: Event, msg: MessageType) { if (!this.client.isDestroyed()) { this.client.send(event.topic, msg) } } } class IpcRendererEventBus implements EventBusInterface { private ipc: IpcRenderer private callbacks: CallbackStore[] = [] constructor(ipc: IpcRenderer) { this.ipc = ipc } public subscribe(event: Event, callback:(msg: MessageType) => void) { const wrappedCallback = (_event: any, arg: any) => { callback(arg) } this.ipc.on(event.topic, wrappedCallback) this.callbacks.push({ callback, wrappedCallback, }) } public unsubscribeAll(event: Event) { this.ipc.removeAllListeners(event.topic) } public unsubscribe(event: Event, callback: any) { debugger const item = this.callbacks.find(store => store.callback === callback) if (!item) { return } this.ipc.removeListener(event.topic, item.wrappedCallback) this.callbacks = this.callbacks.filter(a => a !== item) } public emit(event: Event, msg: MessageType) { this.ipc.send(event.topic, msg) } } export const rendererEvents = new IpcRendererEventBus(ipcRenderer) export const backendEvents = new IpcMainEventBus(ipcMain)