2013-10-05 12:21:57 +00:00
|
|
|
EventEmitter = require('events').EventEmitter
|
2013-07-26 08:39:22 +00:00
|
|
|
v8Util = process.atomBinding 'v8_util'
|
2013-04-24 08:43:01 +00:00
|
|
|
|
2013-10-05 12:53:31 +00:00
|
|
|
class ObjectsRegistry extends EventEmitter
|
2013-10-05 12:21:57 +00:00
|
|
|
constructor: ->
|
2013-12-15 08:15:18 +00:00
|
|
|
@setMaxListeners Number.MAX_VALUE
|
2015-08-27 11:01:34 +00:00
|
|
|
@nextId = 0
|
|
|
|
|
|
|
|
# Stores all objects by ref-counting.
|
|
|
|
# (id) => {object, count}
|
|
|
|
@storage = {}
|
2013-12-15 08:15:18 +00:00
|
|
|
|
2015-08-27 11:01:34 +00:00
|
|
|
# Stores the IDs of objects referenced by WebContents.
|
|
|
|
# (webContentsId) => {(id) => (count)}
|
|
|
|
@owners = {}
|
2013-10-05 12:21:57 +00:00
|
|
|
|
|
|
|
# Register a new object, the object would be kept referenced until you release
|
|
|
|
# it explicitly.
|
2015-08-27 11:01:34 +00:00
|
|
|
add: (webContentsId, obj) ->
|
|
|
|
id = @saveToStorage obj
|
|
|
|
# Remember the owner.
|
|
|
|
@owners[webContentsId] ?= {}
|
|
|
|
@owners[webContentsId][id] ?= 0
|
|
|
|
@owners[webContentsId][id]++
|
|
|
|
# Returns object's id
|
|
|
|
id
|
2013-10-05 12:21:57 +00:00
|
|
|
|
2015-08-27 11:01:34 +00:00
|
|
|
# Get an object according to its ID.
|
2013-10-05 12:21:57 +00:00
|
|
|
get: (id) ->
|
2015-08-27 11:01:34 +00:00
|
|
|
@storage[id]?.object
|
|
|
|
|
|
|
|
# Dereference an object according to its ID.
|
|
|
|
remove: (webContentsId, id) ->
|
|
|
|
@dereference id, 1
|
|
|
|
# Also reduce the count in owner.
|
|
|
|
pointer = @owners[webContentsId]
|
|
|
|
--pointer[id]
|
|
|
|
delete pointer[id] if pointer[id] is 0
|
|
|
|
|
|
|
|
# Clear all references to objects refrenced by the WebContents.
|
|
|
|
clear: (webContentsId) ->
|
|
|
|
@emit "clear-#{webContentsId}"
|
|
|
|
return unless @owners[webContentsId]?
|
|
|
|
@dereference id, count for id, count of @owners[webContentsId]
|
|
|
|
delete @owners[webContentsId]
|
|
|
|
|
|
|
|
# Private: Saves the object into storage and assigns an ID for it.
|
|
|
|
saveToStorage: (object) ->
|
|
|
|
id = v8Util.getHiddenValue object, 'atomId'
|
|
|
|
unless id
|
|
|
|
id = ++@nextId
|
|
|
|
@storage[id] = {count: 0, object}
|
|
|
|
v8Util.setHiddenValue object, 'atomId', id
|
|
|
|
++@storage[id].count
|
|
|
|
id
|
2013-10-05 12:21:57 +00:00
|
|
|
|
2015-08-27 11:01:34 +00:00
|
|
|
# Private: Dereference the object from store.
|
|
|
|
dereference: (id, count) ->
|
|
|
|
pointer = @storage[id]
|
|
|
|
pointer.count -= count
|
|
|
|
if pointer.count is 0
|
|
|
|
v8Util.deleteHiddenValue pointer.object, 'atomId'
|
|
|
|
delete @storage[id]
|
2013-10-05 12:21:57 +00:00
|
|
|
|
|
|
|
module.exports = new ObjectsRegistry
|