2019-11-28 05:17:01 -09:00
|
|
|
import {EventEmitter} from 'events';
|
2019-12-18 07:28:28 -09:00
|
|
|
import {ipcMain, BrowserWindow} from 'electron';
|
2019-11-28 05:17:01 -09:00
|
|
|
import uuid from 'uuid';
|
2016-06-30 22:01:04 -08:00
|
|
|
|
2019-12-18 07:28:28 -09:00
|
|
|
export class Server extends EventEmitter {
|
|
|
|
|
destroyed = false;
|
|
|
|
|
win: BrowserWindow;
|
|
|
|
|
id!: string;
|
|
|
|
|
constructor(win: BrowserWindow) {
|
2016-07-26 09:47:18 -08:00
|
|
|
super();
|
2016-06-30 22:01:04 -08:00
|
|
|
this.win = win;
|
|
|
|
|
this.ipcListener = this.ipcListener.bind(this);
|
2016-07-25 10:01:01 -08:00
|
|
|
|
2016-09-21 06:27:11 -08:00
|
|
|
if (this.destroyed) {
|
|
|
|
|
return;
|
|
|
|
|
}
|
2016-07-25 10:01:01 -08:00
|
|
|
|
|
|
|
|
const uid = uuid.v4();
|
|
|
|
|
this.id = uid;
|
|
|
|
|
|
|
|
|
|
ipcMain.on(uid, this.ipcListener);
|
|
|
|
|
|
|
|
|
|
// we intentionally subscribe to `on` instead of `once`
|
|
|
|
|
// to support reloading the window and re-initializing
|
|
|
|
|
// the channel
|
|
|
|
|
this.wc.on('did-finish-load', () => {
|
|
|
|
|
this.wc.send('init', uid);
|
2016-06-30 22:01:04 -08:00
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
2016-09-21 06:27:11 -08:00
|
|
|
get wc() {
|
2016-06-30 22:01:04 -08:00
|
|
|
return this.win.webContents;
|
|
|
|
|
}
|
|
|
|
|
|
2019-12-18 07:28:28 -09:00
|
|
|
ipcListener(event: any, {ev, data}: {ev: string; data: any}) {
|
2016-07-26 09:47:18 -08:00
|
|
|
super.emit(ev, data);
|
2016-06-30 22:01:04 -08:00
|
|
|
}
|
|
|
|
|
|
2019-12-18 07:28:28 -09:00
|
|
|
emit(ch: string, data: any): any {
|
2018-12-28 14:13:00 -09:00
|
|
|
// This check is needed because data-batching can cause extra data to be
|
|
|
|
|
// emitted after the window has already closed
|
|
|
|
|
if (!this.win.isDestroyed()) {
|
|
|
|
|
this.wc.send(this.id, {ch, data});
|
|
|
|
|
}
|
2016-06-30 22:01:04 -08:00
|
|
|
}
|
|
|
|
|
|
2016-09-21 06:27:11 -08:00
|
|
|
destroy() {
|
2016-06-30 22:01:04 -08:00
|
|
|
this.removeAllListeners();
|
|
|
|
|
this.wc.removeAllListeners();
|
|
|
|
|
if (this.id) {
|
|
|
|
|
ipcMain.removeListener(this.id, this.ipcListener);
|
|
|
|
|
} else {
|
|
|
|
|
// mark for `genUid` in constructor
|
|
|
|
|
this.destroyed = true;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2019-12-18 07:28:28 -09:00
|
|
|
export default (win: BrowserWindow) => {
|
2016-06-30 22:01:04 -08:00
|
|
|
return new Server(win);
|
|
|
|
|
};
|