aboutsummaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rw-r--r--src/bindings/quickjs.nim1
-rw-r--r--src/display/client.nim6
-rw-r--r--src/html/dom.nim88
-rw-r--r--src/js/javascript.nim65
4 files changed, 108 insertions, 52 deletions
diff --git a/src/bindings/quickjs.nim b/src/bindings/quickjs.nim
index a7dd368a..b5aeaf37 100644
--- a/src/bindings/quickjs.nim
+++ b/src/bindings/quickjs.nim
@@ -298,6 +298,7 @@ proc JS_FreeRuntime*(rt: JSRuntime)
proc JS_GetRuntime*(ctx: JSContext): JSRuntime
proc JS_ComputeMemoryUsage*(rt: JSRuntime, s: ptr JSMemoryUsage)
+proc JS_RunGC*(rt: JSRuntime)
proc JS_NewContext*(rt: JSRuntime): JSContext
proc JS_NewContextRaw*(rt: JSRuntime): JSContext
diff --git a/src/display/client.nim b/src/display/client.nim
index 2e6528a3..928fd32d 100644
--- a/src/display/client.nim
+++ b/src/display/client.nim
@@ -446,6 +446,12 @@ proc nimGCStats(client: Client): string {.jsfunc.} =
proc jsGCStats(client: Client): string {.jsfunc.} =
return client.jsrt.getMemoryUsage()
+proc nimCollect(client: Client) {.jsfunc.} =
+ GC_fullCollect()
+
+proc jsCollect(client: Client) {.jsfunc.} =
+ JS_RunGC(client.jsrt)
+
proc show(console: Console) {.jsfunc.} =
if console.pager.container != console.container:
console.prev = console.pager.container
diff --git a/src/html/dom.nim b/src/html/dom.nim
index c610c909..90ec690e 100644
--- a/src/html/dom.nim
+++ b/src/html/dom.nim
@@ -108,17 +108,15 @@ type
EventTarget* = ref object of RootObj
- #TODO this has caching, but invalidation is pretty expensive... not sure if
- # it's worth the trouble at all...
Collection = ref CollectionObj
CollectionObj = object of RootObj
islive: bool
- invalid: bool
childonly: bool
root: Node
match: proc(node: Node): bool {.noSideEffect.}
snapshot: seq[Node]
livelen: int
+ id: int
NodeList = ref object of Collection
@@ -138,10 +136,12 @@ type
parentElement* {.jsget.}: Element
root: Node
document*: Document
- # Live collection cache: if parentHasCollections is true, recursively
- # invalidate all of them on insert.
- parentHasCollections: bool
- liveCollections: seq[Collection]
+ # Live collection cache: ids of live collections are saved in all
+ # nodes they refer to. These are removed when the collection is destroyed,
+ # and invalidated when the owner node's children or attributes change.
+ # (We can't just store pointers, because those may be invalidated by
+ # the JavaScript finalizers.)
+ liveCollections: HashSet[int]
Attr* = ref object of Node
namespaceURI* {.jsget.}: string
@@ -176,6 +176,9 @@ type
renderBlockingElements: seq[Element]
+ invalidCollections: HashSet[int] # collection ids
+ colln: int
+
CharacterData* = ref object of Node
data* {.jsget.}: string
@@ -300,15 +303,6 @@ type
form* {.jsget.}: HTMLFormElement
value* {.jsget.}: string
-proc `=destroy`(collection: var CollectionObj) =
- var i = -1
- for j in 0 ..< collection.root.liveCollections.len:
- if cast[pointer](collection.root.liveCollections[j]) == addr collection:
- i = j
- break
- assert i != -1
- collection.root.liveCollections.del(i)
-
# Forward declarations
func attrb*(element: Element, s: string): bool
proc attr*(element: Element, name, value: string)
@@ -457,12 +451,32 @@ proc populateCollection(collection: Collection) =
for desc in collection.root.descendants:
if collection.match == nil or collection.match(desc):
collection.snapshot.add(desc)
+ if collection.islive:
+ for child in collection.snapshot:
+ child.liveCollections.incl(collection.id)
proc refreshCollection(collection: Collection) =
- if collection.invalid:
+ let document = collection.root.document
+ if collection.id in document.invalidCollections:
+ for child in collection.snapshot:
+ assert collection.id in child.liveCollections
+ child.liveCollections.excl(collection.id)
collection.snapshot.setLen(0)
collection.populateCollection()
- collection.invalid = false
+ document.invalidCollections.excl(collection.id)
+
+proc finalize0(collection: Collection) =
+ if collection.islive:
+ for child in collection.snapshot:
+ assert collection.id in child.liveCollections
+ child.liveCollections.excl(collection.id)
+ collection.root.document.invalidCollections.excl(collection.id)
+
+proc finalize(collection: HTMLCollection) {.jsfin.} =
+ collection.finalize0()
+
+proc finalize(collection: NodeList) {.jsfin.} =
+ collection.finalize0()
func ownerDocument(node: Node): Document {.jsfget.} =
if node.nodeType == DOCUMENT_NODE:
@@ -480,13 +494,11 @@ func newCollection[T: Collection](root: Node, match: proc(node: Node): bool {.no
result = T(
islive: islive,
match: match,
- root: root
+ root: root,
+ id: root.document.colln
)
+ inc root.document.colln
result.populateCollection()
- if islive:
- root.liveCollections.add(result)
- for desc in root.descendants:
- desc.parentHasCollections = true
func isElement(node: Node): bool =
return node.nodeType == ELEMENT_NODE
@@ -608,7 +620,7 @@ func getter(nodeList: NodeList, i: int): Option[Node] {.jsgetprop.} =
return option(nodeList.item(i))
# HTMLCollection
-func length(collection: HTMLCollection): int {.jsfget.} =
+proc length(collection: HTMLCollection): int {.jsfget.} =
return collection.len
func hasprop(collection: HTMLCollection, i: int): bool {.jshasprop.} =
@@ -1335,13 +1347,9 @@ func value*(option: HTMLOptionElement): string {.jsfget.} =
return option.attr("value")
return option.childTextContent.stripAndCollapse()
-proc invalidateCollections(node: Node): bool {.discardable.} =
- for collection in node.liveCollections:
- collection.invalid = true
- if node.parentHasCollections:
- if not node.parentNode.invalidateCollections():
- node.parentHasCollections = false
- return node.liveCollections.len != 0 or node.parentHasCollections
+proc invalidateCollections(node: Node) =
+ for id in node.liveCollections:
+ node.document.invalidCollections.incl(id)
proc delAttr(element: Element, i: int) =
if i != -1:
@@ -1532,7 +1540,7 @@ proc id(element: Element, id: string) {.jsfset.} =
element.id = id
element.attr("id", id)
-# Pass an index to avoid searching for it.
+# Pass an index to avoid searching for the node in parent's child list.
proc remove*(node: Node, index: int, suppressObservers: bool) =
let parent = node.parentNode
assert parent != nil
@@ -1546,8 +1554,7 @@ proc remove*(node: Node, index: int, suppressObservers: bool) =
oldPreviousSibling.nextSibling = oldNextSibling
if oldNextSibling != nil:
oldNextSibling.previousSibling = oldPreviousSibling
- discard node.parentNode.invalidateCollections()
- node.parentHasCollections = false
+ node.parentNode.invalidateCollections()
node.parentNode = nil
node.parentElement = nil
node.root = nil
@@ -1560,9 +1567,18 @@ proc remove*(node: Node, suppressObservers = false) =
node.remove(index, suppressObservers)
proc adopt(document: Document, node: Node) =
+ let oldDocument = node.document
if node.parentNode != nil:
remove(node)
- #TODO shadow root
+ if oldDocument != document:
+ #TODO shadow root
+ for desc in node.descendants:
+ desc.document = document
+ if desc.nodeType == ELEMENT_NODE:
+ for attr in Element(desc).attributes.attrlist:
+ attr.document = document
+ #TODO custom elements
+ #..adopting steps
proc applyChildInsert(parent, child: Node, index: int) =
child.root = parent.rootNode
@@ -1576,8 +1592,6 @@ proc applyChildInsert(parent, child: Node, index: int) =
child.nextSibling = parent.childList[index + 1]
child.nextSibling.previousSibling = child
child.invalidateCollections()
- child.parentHasCollections = parent.liveCollections.len > 0 or parent.parentHasCollections
- child.invalidateCollections()
proc resetElement*(element: Element) =
case element.tagType
diff --git a/src/js/javascript.nim b/src/js/javascript.nim
index 1876326d..d7d0486c 100644
--- a/src/js/javascript.nim
+++ b/src/js/javascript.nim
@@ -14,12 +14,12 @@
# following pragmas. As mentioned before, overloading doesn't work but OR
# generics do. Bare objects (returned by value) can't be passed either, for
# now. Otherwise, most types should work.
-#{.jsfget.} and {.jsfset.} for getters/setters. Note the `f'; bare jsget/jsset
+# {.jsfget.} and {.jsfset.} for getters/setters. Note the `f'; bare jsget/jsset
# can only be used on object fields. (I initially wanted to use the same
# keyword, unfortunately that didn't work out.)
-#{.jsgetprop.} for property getters. Called when GetOwnProperty would return
+# {.jsgetprop.} for property getters. Called when GetOwnProperty would return
# nothing. The key should probably be either a string or an integer.
-#{.jshasprop.} for overriding has_property. Must return a boolean.
+# {.jshasprop.} for overriding has_property. Must return a boolean.
import macros
import options
@@ -71,6 +71,7 @@ type
JSRuntimeOpaque* = ref object
plist: Table[pointer, pointer]
flist: seq[seq[JSCFunctionListEntry]]
+ fins: Table[JSClassID, proc(val: JSValue)]
JSFunctionList* = openArray[JSCFunctionListEntry]
@@ -250,7 +251,10 @@ proc setProperty*(ctx: JSContext, val: JSValue, name: string, prop: JSValue) =
proc setProperty*(ctx: JSContext, val: JSValue, name: string, fun: JSCFunction, argc: int = 0) =
ctx.setProperty(val, name, ctx.newJSCFunction(name, fun, argc))
-func newJSClass*(ctx: JSContext, cdef: JSClassDefConst, tname: string, ctor: JSCFunction, funcs: JSFunctionList, nimt: pointer, parent: JSClassID, asglobal: bool, nointerface: bool): JSClassID {.discardable.} =
+func newJSClass*(ctx: JSContext, cdef: JSClassDefConst, tname: string,
+ ctor: JSCFunction, funcs: JSFunctionList, nimt: pointer,
+ parent: JSClassID, asglobal: bool, nointerface: bool,
+ finalizer: proc(val: JSValue)): JSClassID {.discardable.} =
let rt = JS_GetRuntime(ctx)
discard JS_NewClassID(addr result)
var ctxOpaque = ctx.getOpaque()
@@ -259,6 +263,8 @@ func newJSClass*(ctx: JSContext, cdef: JSClassDefConst, tname: string, ctor: JSC
raise newException(Defect, "Failed to allocate JS class: " & $cdef.class_name)
ctxOpaque.typemap[nimt] = result
ctxOpaque.creg[tname] = result
+ if finalizer != nil:
+ rtOpaque.fins[result] = finalizer
var proto: JSValue
if parent != 0:
let parentProto = JS_GetClassProto(ctx, parent)
@@ -795,6 +801,7 @@ type
SETTER = "js_set"
PROPERTY_GET = "js_prop_get"
PROPERTY_HAS = "js_prop_has"
+ FINALIZER = "js_fin"
var BoundFunctions {.compileTime.}: Table[string, seq[BoundFunction]]
@@ -1426,6 +1433,11 @@ macro jsfunc*(fun: typed) =
gen.registerFunction()
result = newStmtList(fun, jsProc)
+macro jsfin*(fun: typed) =
+ var gen = setupGenerator(fun, FINALIZER, thisname = some("fin"))
+ registerFunction(gen.thisType, FINALIZER, gen.funcName, ident(gen.newName))
+ fun
+
# Having the same names for these and the macros leads to weird bugs, so the
# macros get an additional f.
template jsget*() {.pragma.}
@@ -1434,8 +1446,8 @@ template jsset*() {.pragma.}
proc nim_finalize_for_js[T](obj: T) =
for rt in runtimes:
let rtOpaque = rt.getOpaque()
- if tables.hasKey(rtOpaque.plist, cast[pointer](obj)):
- let p = rtOpaque.plist[cast[pointer](obj)]
+ rtOpaque.plist.withValue(cast[pointer](obj), v):
+ let p = v[]
let val = JS_MKPTR(JS_TAG_OBJECT, p)
let header = cast[ptr JSRefCountHeader](p)
if header.ref_count > 1:
@@ -1445,8 +1457,8 @@ proc nim_finalize_for_js[T](obj: T) =
# * set the new value as the new opaque
# * add the new value to the pointer table
# Now it's on JS to decrement the new object's refcount.
- # (Yeah, kind of an ugly hack. But it starts to look better when
- # the alternative is writing a cycle collector...)
+ # (Yeah, it's an ugly hack, but I couldn't come up with anything
+ # better.)
let newop = new(T)
newop[] = obj[]
GC_ref(newop)
@@ -1455,7 +1467,10 @@ proc nim_finalize_for_js[T](obj: T) =
rtOpaque.plist[np] = p
else:
# This was the last reference to the JS value.
- # Clear val's opaque so our refcount isn't decreased again.
+ # First, trigger the custom finalizer (if there is one.)
+ rtOpaque.fins.withValue(val.getClassID(), fin):
+ fin[](val)
+ # Then clear val's opaque, so that our refcount isn't decreased again.
JS_SetOpaque(val, nil)
tables.del(rtOpaque.plist, cast[pointer](obj))
# Decrement jsvalue's refcount. This is needed in both cases to
@@ -1512,6 +1527,9 @@ macro registerType*(ctx: typed, t: typed, parent: JSClassID = 0, asglobal = fals
# constructor
var ctorFun: NimNode
var ctorImpl: NimNode
+ # custom finalizer
+ var finName = newNilLit()
+ var finFun = newNilLit()
# generic property getter (e.g. attribute["id"])
var propGetFun = newNilLit()
var propHasFun = newNilLit()
@@ -1570,6 +1588,10 @@ macro registerType*(ctx: typed, t: typed, parent: JSClassID = 0, asglobal = fals
propGetFun = f1
of PROPERTY_HAS:
propHasFun = f1
+ of FINALIZER:
+ f0 = fun.name
+ finFun = ident(f0)
+ finName = f1
for k, v in getters:
if k in setters:
@@ -1585,13 +1607,26 @@ macro registerType*(ctx: typed, t: typed, parent: JSClassID = 0, asglobal = fals
sctr = ctorFun
result.add(ctorImpl)
+ let val = ident("val")
+ var finStmt = newStmtList()
+ if finFun.kind != nnkNilLit:
+ finStmt = quote do:
+ let opaque = JS_GetOpaque(`val`, `val`.getClassID())
+ if opaque != nil:
+ `finFun`(cast[`t`](opaque))
+ result.add(quote do:
+ proc `finName`(`val`: JSValue) =
+ `finStmt`
+ )
+
result.add(quote do:
- proc `sfin`(rt: JSRuntime, val: JSValue) {.cdecl.} =
- let opaque = JS_GetOpaque(val, val.getClassID())
+ proc `sfin`(rt: JSRuntime, `val`: JSValue) {.cdecl.} =
+ let opaque = JS_GetOpaque(`val`, `val`.getClassID())
if opaque != nil:
# This means the nim value is no longer referenced by anything but this
# JSValue. Meaning we can just unref and remove it from the pointer
# table.
+ `finStmt` # run custom finalizer, if any
GC_unref(cast[`t`](opaque))
let rtOpaque = rt.getOpaque()
rtOpaque.plist.del(opaque)
@@ -1602,11 +1637,11 @@ macro registerType*(ctx: typed, t: typed, parent: JSClassID = 0, asglobal = fals
let classDef = ident("classDef")
if propGetFun.kind != nnkNilLit or propHasFun.kind != nnkNilLit:
endstmts.add(quote do:
- # YES! IT COMPILES! AHAHAHAHAHAHA
+ # No clue how to do this in pure nim.
{.emit: ["""
static JSClassExoticMethods exotic = {
- .get_own_property = """, `propGetFun`, """,
- .has_property = """, `propHasFun`, """
+ .get_own_property = """, `propGetFun`, """,
+ .has_property = """, `propHasFun`, """
};
static JSClassDef """, `cdname`, """ = {
""", "\"", `name`, "\"", """,
@@ -1634,7 +1669,7 @@ static JSClassDef """, `cdname`, """ = {
# any associated JS object from all relevant runtimes.
var x: `t`
new(x, nim_finalize_for_js)
- `ctx`.newJSClass(`classDef`, `tname`, `sctr`, `tabList`, getTypePtr(x), `parent`, `asglobal`, `nointerface`)
+ `ctx`.newJSClass(`classDef`, `tname`, `sctr`, `tabList`, getTypePtr(x), `parent`, `asglobal`, `nointerface`, `finName`)
)
result.add(newBlockStmt(endstmts))