2019-03-18 19:37:06 +00:00
|
|
|
const v8Util = process.electronBinding('v8_util')
|
2016-01-12 02:40:23 +00:00
|
|
|
|
2019-06-15 08:18:25 +00:00
|
|
|
export class CallbacksRegistry {
|
|
|
|
private nextId: number = 0
|
2019-10-15 16:14:41 +00:00
|
|
|
private callbacks = new Map<number, Function>()
|
2016-01-12 02:40:23 +00:00
|
|
|
|
2019-06-15 08:18:25 +00:00
|
|
|
add (callback: Function) {
|
2016-01-14 18:35:29 +00:00
|
|
|
// The callback is already added.
|
2019-06-15 08:18:25 +00:00
|
|
|
let id = v8Util.getHiddenValue<number>(callback, 'callbackId')
|
2017-11-16 05:04:33 +00:00
|
|
|
if (id != null) return id
|
|
|
|
|
|
|
|
id = this.nextId += 1
|
2016-01-12 02:40:23 +00:00
|
|
|
|
2016-01-14 18:44:21 +00:00
|
|
|
// Capture the location of the function and put it in the ID string,
|
|
|
|
// so that release errors can be tracked down easily.
|
2017-11-16 05:04:33 +00:00
|
|
|
const regexp = /at (.*)/gi
|
|
|
|
const stackString = (new Error()).stack
|
2019-06-15 08:18:25 +00:00
|
|
|
if (!stackString) return
|
2017-11-16 05:04:33 +00:00
|
|
|
|
|
|
|
let filenameAndLine
|
|
|
|
let match
|
|
|
|
|
2016-01-12 02:40:23 +00:00
|
|
|
while ((match = regexp.exec(stackString)) !== null) {
|
2017-11-16 05:04:33 +00:00
|
|
|
const location = match[1]
|
2017-10-31 03:23:12 +00:00
|
|
|
if (location.includes('(native)')) continue
|
|
|
|
if (location.includes('(<anonymous>)')) continue
|
2019-06-04 00:03:59 +00:00
|
|
|
if (location.includes('electron/js2c')) continue
|
2017-11-16 05:04:33 +00:00
|
|
|
|
2017-11-16 18:39:07 +00:00
|
|
|
const ref = /([^/^)]*)\)?$/gi.exec(location)
|
2019-06-15 08:18:25 +00:00
|
|
|
if (ref) filenameAndLine = ref![1]
|
2016-03-25 19:41:24 +00:00
|
|
|
break
|
2016-01-12 02:40:23 +00:00
|
|
|
}
|
2019-06-15 08:18:25 +00:00
|
|
|
|
2019-10-15 16:14:41 +00:00
|
|
|
this.callbacks.set(id, callback)
|
2016-03-25 19:41:24 +00:00
|
|
|
v8Util.setHiddenValue(callback, 'callbackId', id)
|
|
|
|
v8Util.setHiddenValue(callback, 'location', filenameAndLine)
|
|
|
|
return id
|
2016-01-15 22:31:23 +00:00
|
|
|
}
|
2016-01-12 02:40:23 +00:00
|
|
|
|
2019-06-15 08:18:25 +00:00
|
|
|
get (id: number) {
|
2019-10-15 16:14:41 +00:00
|
|
|
return this.callbacks.get(id) || function () {}
|
2016-01-15 22:31:23 +00:00
|
|
|
}
|
2016-01-12 02:40:23 +00:00
|
|
|
|
2019-06-15 08:18:25 +00:00
|
|
|
apply (id: number, ...args: any[]) {
|
2016-12-01 22:37:03 +00:00
|
|
|
return this.get(id).apply(global, ...args)
|
2016-01-15 22:31:23 +00:00
|
|
|
}
|
2016-01-12 02:40:23 +00:00
|
|
|
|
2019-06-15 08:18:25 +00:00
|
|
|
remove (id: number) {
|
2019-10-15 16:14:41 +00:00
|
|
|
const callback = this.callbacks.get(id)
|
2016-06-24 02:21:32 +00:00
|
|
|
if (callback) {
|
|
|
|
v8Util.deleteHiddenValue(callback, 'callbackId')
|
2019-10-15 16:14:41 +00:00
|
|
|
this.callbacks.delete(id)
|
2016-06-24 02:21:32 +00:00
|
|
|
}
|
2016-01-15 22:31:23 +00:00
|
|
|
}
|
|
|
|
}
|