2019-02-14 22:29:20 +00:00
|
|
|
import { ipcMainInternal } from '@electron/internal/browser/ipc-main-internal';
|
2019-02-01 18:56:46 +00:00
|
|
|
|
2020-10-08 01:01:23 +00:00
|
|
|
type IPCHandler = (event: ElectronInternal.IpcMainInternalEvent, ...args: any[]) => any
|
2019-08-23 22:45:50 +00:00
|
|
|
|
|
|
|
export const handleSync = function <T extends IPCHandler> (channel: string, handler: T) {
|
|
|
|
ipcMainInternal.on(channel, async (event, ...args) => {
|
|
|
|
try {
|
|
|
|
event.returnValue = [null, await handler(event, ...args)];
|
|
|
|
} catch (error) {
|
2019-10-10 13:59:08 +00:00
|
|
|
event.returnValue = [error];
|
2019-08-23 22:45:50 +00:00
|
|
|
}
|
2019-02-01 18:56:46 +00:00
|
|
|
});
|
|
|
|
};
|
2019-03-13 19:03:17 +00:00
|
|
|
|
|
|
|
let nextId = 0;
|
|
|
|
|
2020-12-03 06:55:50 +00:00
|
|
|
export function invokeInWebContents<T> (sender: Electron.WebContents, command: string, ...args: any[]) {
|
2019-03-13 19:03:17 +00:00
|
|
|
return new Promise<T>((resolve, reject) => {
|
|
|
|
const requestId = ++nextId;
|
2019-03-26 01:15:51 +00:00
|
|
|
const channel = `${command}_RESPONSE_${requestId}`;
|
2020-10-02 02:52:29 +00:00
|
|
|
ipcMainInternal.on(channel, function handler (event, error: Error, result: any) {
|
2019-03-26 01:15:51 +00:00
|
|
|
if (event.sender !== sender) {
|
|
|
|
console.error(`Reply to ${command} sent by unexpected WebContents (${event.sender.id})`);
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
ipcMainInternal.removeListener(channel, handler);
|
|
|
|
|
2019-03-13 19:03:17 +00:00
|
|
|
if (error) {
|
2019-10-10 13:59:08 +00:00
|
|
|
reject(error);
|
2019-03-13 19:03:17 +00:00
|
|
|
} else {
|
|
|
|
resolve(result);
|
|
|
|
}
|
|
|
|
});
|
2019-03-26 02:38:35 +00:00
|
|
|
|
2020-12-03 06:55:50 +00:00
|
|
|
sender._sendInternal(command, requestId, ...args);
|
2019-03-13 19:03:17 +00:00
|
|
|
});
|
|
|
|
}
|