2016-03-25 19:41:24 +00:00
|
|
|
'use strict'
|
2016-01-15 22:31:23 +00:00
|
|
|
|
2016-03-25 19:41:24 +00:00
|
|
|
const v8Util = process.atomBinding('v8_util')
|
2016-01-12 02:40:23 +00:00
|
|
|
|
2016-01-15 22:31:23 +00:00
|
|
|
class CallbacksRegistry {
|
2016-03-25 19:41:24 +00:00
|
|
|
constructor () {
|
|
|
|
this.nextId = 0
|
|
|
|
this.callbacks = {}
|
2016-01-12 02:40:23 +00:00
|
|
|
}
|
|
|
|
|
2016-03-25 19:41:24 +00:00
|
|
|
add (callback) {
|
2016-01-14 18:35:29 +00:00
|
|
|
// The callback is already added.
|
2017-11-16 05:04:33 +00:00
|
|
|
let id = v8Util.getHiddenValue(callback, 'callbackId')
|
|
|
|
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
|
|
|
|
|
|
|
|
let ref
|
|
|
|
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-11-16 13:15:56 +00:00
|
|
|
if (location.includes('native')) continue
|
|
|
|
if (location.includes('electron.asar')) continue
|
2017-11-16 05:04:33 +00:00
|
|
|
|
2016-11-23 22:27:54 +00:00
|
|
|
ref = /([^/^)]*)\)?$/gi.exec(location)
|
2016-03-25 19:41:24 +00:00
|
|
|
filenameAndLine = ref[1]
|
|
|
|
break
|
2016-01-12 02:40:23 +00:00
|
|
|
}
|
2016-03-25 19:41:24 +00:00
|
|
|
this.callbacks[id] = callback
|
|
|
|
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
|
|
|
|
2016-03-25 19:41:24 +00:00
|
|
|
get (id) {
|
2017-11-16 13:40:49 +00:00
|
|
|
return this.callbacks[id] != null ? this.callbacks[id] : function () {}
|
2016-01-15 22:31:23 +00:00
|
|
|
}
|
2016-01-12 02:40:23 +00:00
|
|
|
|
2016-03-25 19:41:24 +00:00
|
|
|
apply (id, ...args) {
|
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
|
|
|
|
2016-03-25 19:41:24 +00:00
|
|
|
remove (id) {
|
2016-06-24 02:21:32 +00:00
|
|
|
const callback = this.callbacks[id]
|
|
|
|
if (callback) {
|
|
|
|
v8Util.deleteHiddenValue(callback, 'callbackId')
|
|
|
|
delete this.callbacks[id]
|
|
|
|
}
|
2016-01-15 22:31:23 +00:00
|
|
|
}
|
|
|
|
}
|
2016-01-12 02:40:23 +00:00
|
|
|
|
2016-03-25 19:41:24 +00:00
|
|
|
module.exports = CallbacksRegistry
|