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-03-13 19:03:17 +00:00
|
|
|
type IPCHandler = (event: ElectronInternal.IpcMainInternalEvent, ...args: any[]) => any
|
2019-02-01 18:56:46 +00:00
|
|
|
|
2019-02-19 09:24:19 +00:00
|
|
|
const callHandler = async function (handler: IPCHandler, event: ElectronInternal.IpcMainInternalEvent, args: any[], reply: (args: any[]) => void) {
|
2019-02-01 18:56:46 +00:00
|
|
|
try {
|
|
|
|
const result = await handler(event, ...args)
|
|
|
|
reply([null, result])
|
|
|
|
} catch (error) {
|
|
|
|
reply([errorUtils.serialize(error)])
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-02-14 22:29:20 +00:00
|
|
|
export const handle = function <T extends IPCHandler> (channel: string, handler: T) {
|
2019-02-04 22:49:53 +00:00
|
|
|
ipcMainInternal.on(channel, (event, requestId, ...args) => {
|
2019-02-01 18:56:46 +00:00
|
|
|
callHandler(handler, event, args, responseArgs => {
|
2019-02-26 23:48:26 +00:00
|
|
|
if (requestId) {
|
|
|
|
event._replyInternal(`${channel}_RESPONSE_${requestId}`, ...responseArgs)
|
|
|
|
} else {
|
|
|
|
event.returnValue = responseArgs
|
|
|
|
}
|
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
|
|
|
})
|
|
|
|
}
|