2019-02-14 22:29:20 +00:00
|
|
|
import { ipcMainInternal } from '@electron/internal/browser/ipc-main-internal'
|
|
|
|
import * as errorUtils from '@electron/internal/common/error-utils'
|
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 {
|
|
|
|
event.returnValue = [null, await handler(event, ...args)]
|
|
|
|
} catch (error) {
|
|
|
|
event.returnValue = [errorUtils.serialize(error)]
|
|
|
|
}
|
2019-02-01 18:56:46 +00:00
|
|
|
})
|
|
|
|
}
|
2019-03-13 19:03:17 +00:00
|
|
|
|
|
|
|
let nextId = 0
|
|
|
|
|
2019-03-26 02:38:35 +00:00
|
|
|
export function invokeInWebContents<T> (sender: Electron.WebContentsInternal, sendToAll: boolean, 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}`
|
|
|
|
ipcMainInternal.on(channel, function handler (
|
|
|
|
event, error: Electron.SerializedError, result: any
|
|
|
|
) {
|
|
|
|
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) {
|
|
|
|
reject(errorUtils.deserialize(error))
|
|
|
|
} else {
|
|
|
|
resolve(result)
|
|
|
|
}
|
|
|
|
})
|
2019-03-26 02:38:35 +00:00
|
|
|
|
|
|
|
if (sendToAll) {
|
|
|
|
sender._sendInternalToAll(command, requestId, ...args)
|
|
|
|
} else {
|
|
|
|
sender._sendInternal(command, requestId, ...args)
|
|
|
|
}
|
2019-03-13 19:03:17 +00:00
|
|
|
})
|
|
|
|
}
|