Loadable: Add registerCustomProtocol() for e.g. reading assets in mobile.

This commit is contained in:
Alberto Torres 2024-11-29 13:30:32 +01:00
parent 6794b35978
commit 6212b816f0

View file

@ -44,6 +44,7 @@
{.hint[ConvFromXtoItselfNotNeeded]:off.}
import std/tables
import arr_ref # for SliceMem
type LoadableResourceStatus* = enum
@ -236,6 +237,15 @@ func escapeUTF8*(s: string): string =
# TODO: automatically disable threads when not in main thread
type ProtocolHandler* = proc(uri: string): proc(self: LoadableResource)
var custom_protocol_handlers: Table[string, ProtocolHandler]
proc registerCustomProtocol*(prefix: string, handler: ProtocolHandler) =
## Registers a handler for a custom protocol. The function will be run for
## each uri that is requested, and will return a start_func, which in turn
## will call self.onload()
custom_protocol_handlers[prefix] = handler
proc loadUri*(
uri: string,
onload_func: proc(ok: bool, err: string, data: SliceMem[byte]) = nil,
@ -245,6 +255,15 @@ proc loadUri*(
): Fetch {.discardable.} =
echo "fetching ", uri
for k,v in custom_protocol_handlers:
if uri.startswith k:
proc str(): string = uri
var self = newLoadableResource[Fetch](v(uri), str, false)
self.onload_func = onload_func
if auto_start:
start(self)
return self
var start_func: proc(self: LoadableResource)
var self: Fetch
@ -318,3 +337,4 @@ proc loadUri*(
if auto_start:
start(self)
return self