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