aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--res/config.toml6
-rw-r--r--src/buffer/buffer.nim293
-rw-r--r--src/buffer/container.nim19
-rw-r--r--src/config/bufferconfig.nim10
-rw-r--r--src/config/config.nim2
-rw-r--r--src/display/client.nim261
-rw-r--r--src/display/pager.nim44
-rw-r--r--src/io/socketstream.nim8
-rw-r--r--src/js/javascript.nim5
9 files changed, 349 insertions, 299 deletions
diff --git a/res/config.toml b/res/config.toml
index 5ef2c490..88a76d4f 100644
--- a/res/config.toml
+++ b/res/config.toml
@@ -45,7 +45,7 @@ C-m = 'pager.click()'
C-j = 'pager.click()'
C-l = 'pager.changeLocation()'
M-u = 'pager.dupeBuffer()'
-U = 'pager.reloadPage()'
+U = 'pager.reload()'
r = 'pager.redraw()'
R = 'pager.reshape()'
g = 'pager.cursorFirstLine()'
@@ -56,8 +56,8 @@ v = 'pager.toggleSource()'
D = 'pager.discardBuffer()'
',' = 'pager.prevBuffer()'
'.' = 'pager.nextBuffer()'
-M-c = 'commandMode()'
-C = 'command()'
+M-c = 'pager.commandMode()'
+C = 'pager.command()'
'/' = 'pager.isearchForward()'
'?' = 'pager.isearchBackward()'
n = 'pager.searchNext()'
diff --git a/src/buffer/buffer.nim b/src/buffer/buffer.nim
index 40527d94..9bd1d20a 100644
--- a/src/buffer/buffer.nim
+++ b/src/buffer/buffer.nim
@@ -1,6 +1,8 @@
import macros
+import net
import options
import os
+import selectors
import streams
import tables
import unicode
@@ -14,7 +16,7 @@ import css/cssparser
import css/mediaquery
import css/sheet
import css/stylednode
-import config/config
+import config/bufferconfig
import html/dom
import html/tags
import html/htmlparser
@@ -78,15 +80,15 @@ type
reshape: bool
nostatus: bool
location: Url
+ selector: Selector[int]
istream: Stream
pistream: Stream # for input pipe
postream: Stream # for output pipe
streamclosed: bool
source: string
prevnode: StyledNode
- userstyle: CSSStylesheet
loader: FileLoader
- config: Config
+ config: BufferConfig
macro writeCommand(buffer: Buffer, cmd: ContainerCommand, args: varargs[typed]) =
result = newStmtList()
@@ -346,6 +348,18 @@ proc loadResources(buffer: Buffer, document: Document) =
for child in elem.children_rev:
stack.add(child)
+proc c_setvbuf(f: File, buf: pointer, mode: cint, size: csize_t): cint {.
+ importc: "setvbuf", header: "<stdio.h>", tags: [].}
+
+func getFd(buffer: Buffer): FileHandle =
+ let source = buffer.bsource
+ case source.t
+ of CLONE, LOAD_REQUEST:
+ let istream = SocketStream(buffer.istream)
+ return cast[FileHandle](istream.source.getFd())
+ of LOAD_PIPE:
+ return buffer.bsource.fd
+
proc setupSource(buffer: Buffer): int =
let source = buffer.bsource
let setct = source.contenttype.isNone
@@ -361,6 +375,7 @@ proc setupSource(buffer: Buffer): int =
var f: File
if not open(f, source.fd, fmRead):
return 1
+ discard c_setvbuf(f, nil, IONBF, 0)
buffer.istream = newFileStream(f)
if setct:
buffer.contenttype = "text/plain"
@@ -378,6 +393,7 @@ proc setupSource(buffer: Buffer): int =
buffer.writeCommand(SET_REDIRECT, response.redirect.get)
if setct:
buffer.writeCommand(SET_CONTENT_TYPE, buffer.contenttype)
+ buffer.selector.registerHandle(cast[int](buffer.getFd()), {Read}, 1)
proc load(buffer: Buffer) =
case buffer.contenttype
@@ -394,25 +410,45 @@ proc load(buffer: Buffer) =
buffer.document.location = buffer.location
buffer.loadResources(buffer.document)
else:
- if not buffer.streamclosed:
- buffer.source = buffer.istream.readAll()
- buffer.istream.close()
- buffer.streamclosed = true
+ discard
+ #if not buffer.streamclosed:
+ # if buffer.bsource.t != LOAD_PIPE:
+ # buffer.source = buffer.istream.readAll()
+ # buffer.istream.close()
+ # buffer.streamclosed = true
proc render(buffer: Buffer) =
case buffer.contenttype
of "text/html":
if buffer.viewport == nil:
buffer.viewport = Viewport(term: buffer.attrs)
- if buffer.userstyle == nil:
- buffer.userstyle = buffer.config.stylesheet.parseStylesheet()
- let ret = renderDocument(buffer.document, buffer.attrs, buffer.userstyle, buffer.viewport, buffer.prevstyled)
+ let ret = renderDocument(buffer.document, buffer.attrs, buffer.config.userstyle, buffer.viewport, buffer.prevstyled)
buffer.lines = ret[0]
buffer.prevstyled = ret[1]
else:
- if not buffer.rendered:
- buffer.lines = renderPlainText(buffer.source)
- buffer.rendered = true
+ buffer.lines = renderPlainText(buffer.source)
+
+proc load2(buffer: Buffer) =
+ case buffer.contenttype
+ of "text/html":
+ assert false, "Not implemented yet..."
+ else:
+ # This is incredibly stupid but it works so whatever.
+ # (We're basically recv'ing single bytes, but nim std/net does buffering
+ # for us so we should be ok?)
+ if not buffer.streamclosed:
+ let c = buffer.istream.readChar()
+ buffer.source &= c
+ buffer.reshape = true
+
+proc finishLoad(buffer: Buffer) =
+ if not buffer.streamclosed:
+ if not buffer.istream.atEnd:
+ buffer.source &= buffer.istream.readAll()
+ buffer.reshape = true
+ buffer.selector.unregister(int(buffer.getFd()))
+ buffer.istream.close()
+ buffer.streamclosed = true
# https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#constructing-the-form-data-set
proc constructEntryList(form: HTMLFormElement, submitter: Element = nil, encoding: string = ""): seq[tuple[name, value: string]] =
@@ -709,113 +745,130 @@ proc drawBuffer(buffer: Buffer, ostream: Stream) =
ostream.swrite("")
ostream.flush()
-proc runBuffer(buffer: Buffer, istream, ostream: Stream) =
- buffer.pistream = istream
- buffer.postream = ostream
- while true:
- var cmd: BufferCommand
- try:
- istream.sread(cmd)
- #eprint "cmd", cmd
- case cmd
- of LOAD:
- let code = buffer.setupSource()
- buffer.load()
- buffer.writeCommand(LOAD_DONE, code)
- of GOTO_ANCHOR:
- var anchor: string
- istream.sread(anchor)
- if buffer.document != nil and buffer.document.getElementById(anchor) != nil:
- buffer.writeCommand(ANCHOR_FOUND)
- else:
- buffer.writeCommand(ANCHOR_FAIL)
- of RENDER:
- buffer.render()
- buffer.gotoAnchor()
- of GET_LINES:
- var w: Slice[int]
- istream.sread(w)
- ostream.swrite(SET_LINES)
- ostream.swrite(buffer.lines.len)
- w.b = min(buffer.lines.high, w.b)
- ostream.swrite(w)
- for y in w:
- ostream.swrite(buffer.lines[y])
- ostream.flush()
- ostream.flush()
- of DRAW_BUFFER:
- buffer.drawBuffer(ostream)
- of WINDOW_CHANGE:
- istream.sread(buffer.attrs)
- buffer.windowChange()
- of FIND_PREV_LINK:
- var cx, cy: int
- istream.sread(cx)
- istream.sread(cy)
- let pl = buffer.findPrevLink(cx, cy)
- buffer.writeCommand(JUMP, pl.x, pl.y)
- of FIND_NEXT_LINK:
- var cx, cy: int
- istream.sread(cx)
- istream.sread(cy)
- let nl = buffer.findNextLink(cx, cy)
- buffer.writeCommand(JUMP, nl.x, nl.y)
- of FIND_PREV_MATCH:
- var cx, cy: int
- var regex: Regex
- var wrap: bool
- istream.sread(cx)
- istream.sread(cy)
- istream.sread(regex)
- istream.sread(wrap)
- let match = buffer.findPrevMatch(regex, cx, cy, wrap)
- if match.success:
- buffer.writeCommand(JUMP, match.x, match.y, match.x + match.str.width() - 1)
- of FIND_NEXT_MATCH:
- var cx, cy: int
- var regex: Regex
- var wrap: bool
- istream.sread(cx)
- istream.sread(cy)
- istream.sread(regex)
- istream.sread(wrap)
- let match = buffer.findNextMatch(regex, cx, cy, wrap)
- if match.success:
- buffer.writeCommand(JUMP, match.x, match.y, match.x + match.str.width() - 1)
- of READ_SUCCESS:
- var s: string
- istream.sread(s)
- buffer.lineInput(s)
- of READ_CANCELED:
- buffer.input = nil
- of CLICK:
- var cx, cy: int
- istream.sread(cx)
- istream.sread(cy)
- buffer.click(cx, cy)
- of MOVE_CURSOR:
- var cx, cy: int
- istream.sread(cx)
- istream.sread(cy)
- buffer.updateHover(cx, cy)
- of GET_SOURCE:
- let ssock = initServerSocket(getpid())
- buffer.writeCommand(SOURCE_READY)
- let stream = ssock.acceptSocketStream()
- if not buffer.streamclosed:
- buffer.source = buffer.istream.readAll()
- buffer.streamclosed = true
- stream.write(buffer.source)
- stream.close()
- ssock.close()
+proc readCommand(buffer: Buffer) =
+ let istream = buffer.pistream
+ let ostream = buffer.postream
+ var cmd: BufferCommand
+ istream.sread(cmd)
+ case cmd
+ of LOAD:
+ let code = buffer.setupSource()
+ buffer.load()
+ buffer.writeCommand(LOAD_DONE, code)
+ of GOTO_ANCHOR:
+ var anchor: string
+ istream.sread(anchor)
+ if buffer.document != nil and buffer.document.getElementById(anchor) != nil:
+ buffer.writeCommand(ANCHOR_FOUND)
+ else:
+ buffer.writeCommand(ANCHOR_FAIL)
+ of RENDER:
+ buffer.render()
+ buffer.gotoAnchor()
+ of GET_LINES:
+ var w: Slice[int]
+ istream.sread(w)
+ ostream.swrite(SET_LINES)
+ ostream.swrite(buffer.lines.len)
+ w.b = min(buffer.lines.high, w.b)
+ ostream.swrite(w)
+ for y in w:
+ ostream.swrite(buffer.lines[y])
+ ostream.flush()
+ ostream.flush()
+ of DRAW_BUFFER:
+ buffer.drawBuffer(ostream)
+ of WINDOW_CHANGE:
+ istream.sread(buffer.attrs)
+ buffer.windowChange()
+ of FIND_PREV_LINK:
+ var cx, cy: int
+ istream.sread(cx)
+ istream.sread(cy)
+ let pl = buffer.findPrevLink(cx, cy)
+ buffer.writeCommand(JUMP, pl.x, pl.y, 0)
+ of FIND_NEXT_LINK:
+ var cx, cy: int
+ istream.sread(cx)
+ istream.sread(cy)
+ let nl = buffer.findNextLink(cx, cy)
+ buffer.writeCommand(JUMP, nl.x, nl.y, 0)
+ of FIND_PREV_MATCH:
+ var cx, cy: int
+ var regex: Regex
+ var wrap: bool
+ istream.sread(cx)
+ istream.sread(cy)
+ istream.sread(regex)
+ istream.sread(wrap)
+ let match = buffer.findPrevMatch(regex, cx, cy, wrap)
+ if match.success:
+ buffer.writeCommand(JUMP, match.x, match.y, match.x + match.str.width() - 1)
+ of FIND_NEXT_MATCH:
+ var cx, cy: int
+ var regex: Regex
+ var wrap: bool
+ istream.sread(cx)
+ istream.sread(cy)
+ istream.sread(regex)
+ istream.sread(wrap)
+ let match = buffer.findNextMatch(regex, cx, cy, wrap)
+ if match.success:
+ buffer.writeCommand(JUMP, match.x, match.y, match.x + match.str.width() - 1)
+ of READ_SUCCESS:
+ var s: string
+ istream.sread(s)
+ buffer.lineInput(s)
+ of READ_CANCELED:
+ buffer.input = nil
+ of CLICK:
+ var cx, cy: int
+ istream.sread(cx)
+ istream.sread(cy)
+ buffer.click(cx, cy)
+ of MOVE_CURSOR:
+ var cx, cy: int
+ istream.sread(cx)
+ istream.sread(cy)
+ buffer.updateHover(cx, cy)
+ of GET_SOURCE:
+ let ssock = initServerSocket(getpid())
+ buffer.writeCommand(SOURCE_READY)
+ let stream = ssock.acceptSocketStream()
+ if not buffer.streamclosed:
+ buffer.source = buffer.istream.readAll()
+ buffer.streamclosed = true
+ stream.write(buffer.source)
+ stream.close()
+ ssock.close()
+
+proc runBuffer(buffer: Buffer, readf, writef: File) =
+ buffer.pistream = newFileStream(readf)
+ buffer.postream = newFileStream(writef)
+ let rfd = readf.getFileHandle()
+ block loop:
+ while true:
+ let events = buffer.selector.select(-1)
+ for event in events:
+ if Read in event.events:
+ if event.fd == rfd:
+ try:
+ buffer.readCommand()
+ except IOError:
+ break loop
+ else:
+ buffer.load2()
+ if Error in event.events:
+ if event.fd == rfd:
+ break loop
+ elif event.fd == buffer.getFd():
+ buffer.finishLoad()
if buffer.reshape:
buffer.reshape = false
buffer.render()
buffer.writeCommand(RESHAPE)
- except IOError:
- break
- istream.close()
- ostream.close()
+ buffer.pistream.close()
+ buffer.postream.close()
when defined(posix):
#TODO remove this
if buffer.loader != nil:
@@ -823,12 +876,14 @@ proc runBuffer(buffer: Buffer, istream, ostream: Stream) =
buffer.loader = nil
quit(0)
-proc launchBuffer*(config: Config, source: BufferSource, attrs: TermAttributes,
- istream, ostream: Stream) =
+proc launchBuffer*(config: BufferConfig, source: BufferSource,
+ attrs: TermAttributes, readf, writef: File) =
let buffer = new Buffer
buffer.attrs = attrs
buffer.windowChange()
buffer.config = config
buffer.loader = newFileLoader()
buffer.bsource = source
- buffer.runBuffer(istream, ostream)
+ buffer.selector = newSelector[int]()
+ buffer.selector.registerHandle(int(readf.getFileHandle()), {Read}, 0)
+ buffer.runBuffer(readf, writef)
diff --git a/src/buffer/container.nim b/src/buffer/container.nim
index a96aae5c..35071f1e 100644
--- a/src/buffer/container.nim
+++ b/src/buffer/container.nim
@@ -9,6 +9,7 @@ when defined(posix):
import buffer/buffer
import buffer/cell
+import config/bufferconfig
import config/config
import io/request
import io/serialize
@@ -93,6 +94,7 @@ proc newBuffer*(config: Config, source: BufferSource, tty: FileHandle, ispipe =
if pid == -1:
raise newException(Defect, "Failed to fork buffer process")
elif pid == 0:
+ let bconfig = config.loadBufferConfig()
discard close(tty)
discard close(stdout.getFileHandle())
# child process
@@ -103,10 +105,8 @@ proc newBuffer*(config: Config, source: BufferSource, tty: FileHandle, ispipe =
raise newException(Defect, "Failed to open input handle")
if not open(writef, pipefd_out[1], fmWrite):
raise newException(Defect, "Failed to open output handle")
- discard c_setvbuf(writef, nil, IONBF, 0)
- let istream = newFileStream(readf)
- let ostream = newFileStream(writef)
- launchBuffer(config, source, attrs, istream, ostream)
+ discard c_setvbuf(readf, nil, IONBF, 0)
+ launchBuffer(bconfig, source, attrs, readf, writef)
else:
discard close(pipefd_in[0]) # close read
discard close(pipefd_out[1]) # close write
@@ -228,13 +228,13 @@ func lineWindow(container: Container): Slice[int] =
let n = (container.height * 5) div 2
var x = container.fromy - n + container.height div 2
var y = container.fromy + n + container.height div 2
- if x < 0:
- y += -x
- x = 0
if y >= container.numLines:
x -= y - container.numLines
y = container.numLines
- return max(x, 0) .. min(y, container.numLines - 1)
+ if x < 0:
+ y += -x
+ x = 0
+ return x .. y
func contains*(hl: Highlight, x, y: int): bool =
if hl.rect:
@@ -574,9 +574,6 @@ proc render*(container: Container) =
container.writeCommand(GET_LINES, container.lineWindow)
proc dupeBuffer*(container: Container, config: Config, location = none(URL), contenttype = none(string)): Container =
- var pipefd: array[0..1, cint]
- if pipe(pipefd) == -1:
- raise newException(Defect, "Failed to open dupe pipe.")
let source = BufferSource(
t: CLONE,
location: location.get(container.source.location),
diff --git a/src/config/bufferconfig.nim b/src/config/bufferconfig.nim
new file mode 100644
index 00000000..984df24e
--- /dev/null
+++ b/src/config/bufferconfig.nim
@@ -0,0 +1,10 @@
+import config/config
+import css/sheet
+
+type BufferConfig* = ref object
+ userstyle*: CSSStylesheet
+
+proc loadBufferConfig*(config: Config): BufferConfig =
+ new(result)
+ result.userstyle = parseStylesheet(config.stylesheet)
+ zeroMem(addr config[], sizeof(ConfigObj))
diff --git a/src/config/config.nim b/src/config/config.nim
index 9db896e5..a97be9cd 100644
--- a/src/config/config.nim
+++ b/src/config/config.nim
@@ -9,7 +9,7 @@ import utils/twtstr
type
ActionMap = Table[string, string]
Config* = ref ConfigObj
- ConfigObj = object
+ ConfigObj* = object
nmap*: ActionMap
lemap*: ActionMap
stylesheet*: string
diff --git a/src/display/client.nim b/src/display/client.nim
index cf5842b1..54fca3c1 100644
--- a/src/display/client.nim
+++ b/src/display/client.nim
@@ -1,16 +1,14 @@
import options
import os
+import selectors
import streams
import tables
import terminal
-import times
when defined(posix):
import posix
-import std/monotimes
-import std/selectors
-
+import bindings/quickjs
import buffer/container
import css/sheet
import config/config
@@ -42,16 +40,16 @@ type
jsrt: JSRuntime
jsctx: JSContext
timeoutid: int
- timeouts: Table[int, tuple[handler: proc(), time: int64]]
- added_timeouts: Table[int, tuple[handler: proc(), time: int64]]
- removed_timeouts: seq[int]
- intervals: Table[int, tuple[handler: proc(), time: int64, wait: int, del: JSValue]]
- added_intervals: Table[int, tuple[handler: proc(), time: int64, wait: int, del: JSValue]]
- removed_intervals: seq[int]
-
- Console* = ref object
- err*: Stream
- lastcontainer*: Container
+ timeouts: Table[int, tuple[handler: (proc()), fdi: int]]
+ intervals: Table[int, tuple[handler: (proc()), fdi: int, tofree: JSValue]]
+ timeout_fdis: Table[int, int]
+ interval_fdis: Table[int, int]
+
+ Console = ref object
+ err: Stream
+ pager: Pager
+ container: Container
+ prev: Container
ibuf: string
tty: File
@@ -67,10 +65,6 @@ proc `=destroy`(client: var ClientObj) =
if client.jsrt != nil:
free(client.jsrt)
-proc statusMode(client: Client) =
- print(HVP(client.attrs.height + 1, 1))
- print(EL())
-
proc doRequest(client: Client, req: Request): Response {.jsfunc.} =
client.loader.doRequest(req)
@@ -104,37 +98,13 @@ proc command0(client: Client, src: string, filename = "<command>", silence = fal
let str = ret.toString()
if str.issome:
client.console.err.write(str.get & '\n')
+ client.console.err.flush()
free(ret)
- for k, v in client.added_timeouts:
- client.timeouts[k] = v
- client.added_timeouts.clear()
- for k, v in client.added_intervals:
- client.intervals = client.added_intervals
- client.added_intervals.clear()
proc command(client: Client, src: string) =
restoreStdin(client.console.tty.getFileHandle())
- let previ = client.console.err.getPosition()
client.command0(src)
- client.console.err.setPosition(previ)
- #TODO yeah this won't work...
- #if client.console.lastcontainer == nil:
- # let source = BufferSource(t: STRING, slocation: parseUrl("javascript:void(0);").get, str: client.console.err.readAll(), contenttype: some("text/plain"))
- # let container = newBuffer(client.config, client.console.tty, source)
- # client.console.lastcontainer = container
- # client.pager.addContainer(container)
- #else:
- # client.console.lastbuf.istream = newStringStream(client.console.lastbuf.source & client.console.err.readAll())
- # client.console.lastbuf.streamclosed = false
- #client.console.lastbuf.setupBuffer()
- #client.console.lastbuf.cursorLastLine()
-
-proc command(client: Client): bool {.jsfunc.} =
- client.statusMode()
- client.pager.lineedit = some(readLine("COMMAND: ", client.attrs.width, config = client.config, tty = client.console.tty))
-
-proc commandMode(client: Client) {.jsfunc.} =
- client.pager.commandMode = client.command()
+ client.console.container.cursorLastLine()
proc quit(client: Client, code = 0) {.jsfunc.} =
if stdout.isatty():
@@ -151,9 +121,6 @@ proc feedNext(client: Client) {.jsfunc.} =
proc input(client: Client) =
restoreStdin(client.console.tty.getFileHandle())
- if client.pager.commandMode:
- client.commandMode()
- return
let c = client.console.readChar()
client.s &= c
if client.pager.lineedit.isSome:
@@ -189,11 +156,62 @@ proc input(client: Client) =
client.pager.displayStatus()
client.pager.displayCursor()
-proc c_setvbuf(f: File, buf: pointer, mode: cint, size: csize_t): cint {.
- importc: "setvbuf", header: "<stdio.h>", tags: [].}
+proc setTimeout[T: JSObject|string](client: Client, handler: T, timeout = 0): int {.jsfunc.} =
+ let id = client.timeoutid
+ inc client.timeoutid
+ let fdi = client.pager.selector.registerTimer(timeout, true, nil)
+ client.timeout_fdis[fdi] = id
+ when T is string:
+ client.timeouts[id] = ((proc() =
+ client.evalJSFree(handler, "setTimeout handler")
+ ), fdi)
+ else:
+ let fun = JS_DupValue(handler.ctx, handler.val)
+ client.timeouts[id] = ((proc() =
+ let ret = JSObject(ctx: handler.ctx, val: fun).callFunction()
+ if ret.isException():
+ ret.ctx.writeException(client.console.err)
+ JS_FreeValue(ret.ctx, ret.val)
+ JS_FreeValue(ret.ctx, fun)
+ ), fdi)
+ return id
+
+proc setInterval[T: JSObject|string](client: Client, handler: T, interval = 0): int {.jsfunc.} =
+ let id = client.timeoutid
+ inc client.timeoutid
+ let fdi = client.pager.selector.registerTimer(interval, false, nil)
+ client.interval_fdis[fdi] = id
+ when T is string:
+ client.intervals[id] = ((proc() =
+ client.evalJSFree(handler, "setInterval handler")
+ ), fdi, JS_NULL)
+ else:
+ let fun = JS_DupValue(handler.ctx, handler.val)
+ client.intervals[id] = ((proc() =
+ let obj = JSObject(ctx: handler.ctx, val: fun)
+ let ret = obj.callFunction()
+ if ret.isException():
+ ret.ctx.writeException(client.console.err)
+ JS_FreeValue(ret.ctx, ret.val)
+ ), fdi, fun)
+ return id
+
+proc clearTimeout(client: Client, id: int) {.jsfunc.} =
+ if id in client.timeouts:
+ let timeout = client.timeouts[id]
+ client.pager.selector.unregister(timeout.fdi)
+ client.timeout_fdis.del(timeout.fdi)
+ client.timeouts.del(id)
+
+proc clearInterval(client: Client, id: int) {.jsfunc.} =
+ if id in client.intervals:
+ let interval = client.intervals[id]
+ client.pager.selector.unregister(interval.fdi)
+ JS_FreeValue(client.jsctx, interval.tofree)
+ client.interval_fdis.del(interval.fdi)
+ client.intervals.del(id)
proc inputLoop(client: Client) =
- discard c_setvbuf(client.console.tty, nil, IONBF, 0) #??? I thought raw mode would take care of this
client.pager.selector.registerHandle(int(client.console.tty.getFileHandle()), {Read}, nil)
while true:
let events = client.pager.selector.select(-1)
@@ -201,6 +219,13 @@ proc inputLoop(client: Client) =
if event.fd == client.console.tty.getFileHandle():
client.input()
stdout.flushFile()
+ elif event.fd in client.interval_fdis:
+ client.intervals[client.interval_fdis[event.fd]].handler()
+ elif event.fd in client.timeout_fdis:
+ let id = client.timeout_fdis[event.fd]
+ let timeout = client.timeouts[id]
+ timeout.handler()
+ client.clearTimeout(id)
else:
let container = client.pager.fdmap[FileHandle(event.fd)]
if not client.pager.handleEvent(container):
@@ -208,14 +233,14 @@ proc inputLoop(client: Client) =
for msg in client.pager.status:
eprint msg
client.quit(1)
+ if client.pager.scommand != "":
+ client.command(client.pager.scommand)
+ client.pager.scommand = ""
if client.pager.lineedit.isNone and client.pager.redraw or client.pager.container.redraw:
client.pager.refreshDisplay(client.pager.container)
- client.pager.displayPage()
+ client.pager.draw()
client.pager.redraw = false
client.pager.container.redraw = false
- if client.pager.command != "":
- client.command(client.pager.command)
- client.pager.command = ""
#TODO this is dumb
proc readFile(client: Client, path: string): string {.jsfunc.} =
@@ -228,106 +253,25 @@ proc readFile(client: Client, path: string): string {.jsfunc.} =
proc writeFile(client: Client, path: string, content: string) {.jsfunc.} =
writeFile(path, content)
-import bindings/quickjs
-
-proc setTimeout[T: JSObject|string](client: Client, handler: T, timeout = 0): int {.jsfunc.} =
- let id = client.timeoutid
- inc client.timeoutid
- when T is string:
- client.added_timeouts[id] = ((proc() =
- client.evalJSFree(handler, "setTimeout handler")
- ), getMonoTime().ticks div 1_000_000 + timeout)
- else:
- let fun = JS_DupValue(handler.ctx, handler.val)
- client.added_timeouts[id] = ((proc() =
- let ret = JSObject(ctx: handler.ctx, val: fun).callFunction()
- if ret.isException():
- ret.ctx.writeException(client.console.err)
- JS_FreeValue(ret.ctx, ret.val)
- JS_FreeValue(ret.ctx, fun)
- ), getMonoTime().ticks div 1_000_000 + timeout)
- return id
-
-proc setInterval[T: JSObject|string](client: Client, handler: T, interval = 0): int {.jsfunc.} =
- let id = client.timeoutid
- inc client.timeoutid
- when T is string:
- client.added_intervals[id] = ((proc() =
- client.evalJSFree(handler, "setInterval handler")
- ), getMonoTime().ticks div 1_000_000 + interval, interval, JS_NULL)
- else:
- let fun = JS_DupValue(handler.ctx, handler.val)
- client.added_intervals[id] = ((proc() =
- let ret = JSObject(ctx: handler.ctx, val: fun).callFunction()
- if ret.isException():
- ret.ctx.writeException(client.console.err)
- JS_FreeValue(ret.ctx, ret.val)
- ), getMonoTime().ticks div 1_000_000 + interval, interval, fun)
- return id
-
-proc clearTimeout(client: Client, id: int) {.jsfunc.} =
- client.removed_timeouts.add(id)
-
-proc clearInterval(client: Client, id: int) {.jsfunc.} =
- client.removed_intervals.add(id)
-
-proc jsEventLoop(client: Client) =
- while client.timeouts.len > 0 or client.intervals.len > 0:
- var wait = -1
- let curr = getMonoTime().ticks div 1_000_000
- for k, v in client.timeouts:
- if v.time <= curr:
- v.handler()
- client.removed_timeouts.add(k)
- for k, v in client.intervals.mpairs:
- if v.time <= curr:
- v.handler()
- v.time = curr + v.wait
- for k, v in client.added_timeouts:
- client.timeouts[k] = v
- client.added_timeouts.clear()
- for k, v in client.added_intervals:
- client.intervals[k] = v
- client.added_intervals.clear()
- for k in client.removed_timeouts:
- client.timeouts.del(k)
- for k in client.removed_intervals:
- if k in client.intervals and client.intervals[k].del != JS_NULL:
- JS_FreeValue(client.jsctx, client.intervals[k].del)
- client.intervals.del(k)
- client.removed_timeouts.setLen(0)
- client.removed_intervals.setLen(0)
- for k, v in client.timeouts:
- if wait != -1:
- wait = min(wait, int(v.time - curr))
- else:
- wait = int(v.time - curr)
- for k, v in client.intervals:
- if wait != -1:
- wait = min(wait, int(v.time - curr))
- else:
- wait = int(v.time - curr)
- if wait > 0:
- sleep(wait)
-
proc launchClient*(client: Client, pages: seq[string], ctype: Option[string], dump: bool) =
if client.config.startup != "":
let s = readFile(client.config.startup)
client.console.err = newFileStream(stderr)
client.command0(s, client.config.startup, silence = true)
- client.jsEventLoop()
+ #TODO
client.console.err = newStringStream()
quit()
client.userstyle = client.config.stylesheet.parseStylesheet()
if not stdin.isatty:
- client.pager.readPipe(ctype)
+ client.pager.readPipe(ctype, stdin.getFileHandle())
+ stdin.close()
else:
client.console.tty = stdin
for page in pages:
client.pager.loadURL(page, ctype = ctype)
- if stdout.isatty and not dump:
+ if stdout.isatty() and not dump:
when defined(posix):
enableRawMode(client.console.tty.getFileHandle())
client.inputLoop()
@@ -346,9 +290,20 @@ proc nimGCStats(client: Client): string {.jsfunc.} =
proc jsGCStats(client: Client): string {.jsfunc.} =
return client.jsrt.getMemoryUsage()
-func newConsole(): Console =
+proc newConsole(pager: Pager): Console =
new(result)
- result.err = newStringStream()
+ var pipefd: array[0..1, cint]
+ if pipe(pipefd) == -1:
+ raise newException(Defect, "Failed to open console pipe.")
+ let url = newURL("javascript:console.show()")
+ result.container = pager.readPipe0(some("text/plain"), pipefd[0], option(url))
+ pager.registerContainer(result.container)
+ discard close(pipefd[0])
+ var f: File
+ if not open(f, pipefd[1], fmWrite):
+ raise newException(Defect, "Failed to open file for console pipe.")
+ result.err = newFileStream(f)
+ result.pager = pager
proc log(console: Console, ss: varargs[string]) {.jsfunc.} =
for i in 0..<ss.len:
@@ -356,6 +311,16 @@ proc log(console: Console, ss: varargs[string]) {.jsfunc.} =
if i != ss.high:
console.err.write(' ')
console.err.write('\n')
+ console.err.flush()
+
+proc show(console: Console) {.jsfunc.} =
+ if console.pager.container != console.container:
+ console.prev = console.pager.container
+ console.pager.setContainer(console.container)
+
+proc hide(console: Console) {.jsfunc.} =
+ if console.pager.container == console.container:
+ console.pager.setContainer(console.prev)
proc sleep(client: Client, millis: int) {.jsfunc.} =
sleep millis
@@ -363,14 +328,16 @@ proc sleep(client: Client, millis: int) {.jsfunc.} =
proc newClient*(config: Config): Client =
new(result)
result.config = config
- result.console = newConsole()
- if stdin.isatty():
- result.console.tty = stdin
- elif stdout.isatty():
- discard open(result.console.tty, "/dev/tty", fmRead)
result.attrs = getTermAttributes(stdout)
result.loader = newFileLoader()
- result.pager = newPager(config, result.attrs, result.console.tty)
+ var tty: File
+ if stdin.isatty():
+ tty = stdin
+ elif stdout.isatty():
+ discard open(tty, "/dev/tty", fmRead)
+ result.pager = newPager(config, result.attrs, tty)
+ result.console = newConsole(result.pager)
+ result.console.tty = tty
let rt = newJSRuntime()
rt.setInterruptHandler(interruptHandler, cast[pointer](result))
let ctx = rt.newJSContext()
diff --git a/src/display/pager.nim b/src/display/pager.nim
index f8e012eb..d4a2dc99 100644
--- a/src/display/pager.nim
+++ b/src/display/pager.nim
@@ -1,12 +1,11 @@
import options
import os
+import selectors
import streams
import tables
import terminal
import unicode
-import std/selectors
-
import buffer/buffer
import buffer/cell
import buffer/container
@@ -31,7 +30,7 @@ type
lineedit*: Option[LineEdit]
linemode*: LineMode
username: string
- command*: string
+ scommand*: string
config: Config
regex: Option[Regex]
iregex: Option[Regex]
@@ -112,7 +111,7 @@ proc statusMode(pager: Pager) =
print(SGR())
print(EL())
-proc setLineEdit(pager: Pager, edit: LineEdit, mode: LineMode) =
+proc setLineEdit*(pager: Pager, edit: LineEdit, mode: LineMode) =
pager.statusMode()
edit.writeStart()
stdout.flushFile()
@@ -290,14 +289,17 @@ proc draw*(pager: Pager) =
pager.refreshStatusMsg()
pager.displayPage()
+proc registerContainer*(pager: Pager, container: Container) =
+ pager.fdmap[container.ifd] = container
+ pager.selector.registerHandle(int(container.ifd), {Read}, pager.container)
+
proc addContainer*(pager: Pager, container: Container) =
container.parent = pager.container
if pager.container != nil:
pager.container.children.add(container)
pager.setContainer(container)
assert int(container.ifd) != 0
- pager.fdmap[container.ifd] = container
- pager.selector.registerHandle(int(container.ifd), {Read}, pager.container)
+ pager.registerContainer(container)
proc dupeContainer(pager: Pager, container: Container, location: Option[URL]): Container =
return container.dupeBuffer(pager.config, location)
@@ -456,16 +458,27 @@ proc loadURL*(pager: Pager, url: string, ctype = none(string)) =
if pager.container != prevc:
pager.container.retry = urls
-proc readPipe*(pager: Pager, ctype: Option[string]) =
+proc readPipe0*(pager: Pager, ctype: Option[string], fd: FileHandle, location: Option[URL]): Container =
let source = BufferSource(
t: LOAD_PIPE,
- fd: stdin.getFileHandle(),
+ fd: fd,
contenttype: some(ctype.get("text/plain")),
- location: parseUrl("file://-").get
+ location: location.get(newURL("file://-"))
)
let container = newBuffer(pager.config, source, pager.tty.getFileHandle(), ispipe = true)
- pager.addContainer(container)
container.load()
+ return container
+
+proc readPipe*(pager: Pager, ctype: Option[string], fd: FileHandle) =
+ let container = pager.readPipe0(ctype, fd, none(URL))
+ pager.addContainer(container)
+
+proc command(pager: Pager) {.jsfunc.} =
+ pager.setLineEdit(readLine("COMMAND: ", pager.attrs.width, config = pager.config, tty = pager.tty), COMMAND)
+
+proc commandMode(pager: Pager) {.jsfunc.} =
+ pager.commandMode = true
+ pager.command()
proc updateReadLineISearch(pager: Pager, linemode: LineMode) =
let lineedit = pager.lineedit.get
@@ -516,7 +529,10 @@ proc updateReadLine*(pager: Pager) =
url.password = s
pager.username = ""
pager.gotoURL(newRequest(url), some(pager.container.source.location), replace = pager.container)
- of COMMAND: pager.command = s
+ of COMMAND:
+ pager.scommand = s
+ if pager.commandmode:
+ pager.command()
of BUFFER: pager.container.readSuccess(s)
of SEARCH_F:
let x = s
@@ -536,13 +552,11 @@ proc updateReadLine*(pager: Pager) =
pager.username = ""
pager.discardBuffer()
of BUFFER: pager.container.readCanceled()
+ of COMMAND: pager.commandmode = false
else: discard
if lineedit.state in {CANCEL, FINISH}:
if pager.lineedit.get == lineedit:
pager.clearLineEdit()
- print('\r')
- print(EL())
- pager.displayPage()
# Open a URL prompt and visit the specified URL.
proc changeLocation(pager: Pager) {.jsfunc.} =
@@ -550,7 +564,7 @@ proc changeLocation(pager: Pager) {.jsfunc.} =
pager.setLineEdit(readLine("URL: ", pager.attrs.width, current = url, config = pager.config, tty = pager.tty), LOCATION)
# Reload the page in a new buffer, then kill the previous buffer.
-proc reloadPage(pager: Pager) {.jsfunc.} =
+proc reload(pager: Pager) {.jsfunc.} =
pager.gotoURL(newRequest(pager.container.source.location), none(URL), pager.container.contenttype, pager.container)
proc click(pager: Pager) {.jsfunc.} =
diff --git a/src/io/socketstream.nim b/src/io/socketstream.nim
index d7f43625..d6340b2a 100644
--- a/src/io/socketstream.nim
+++ b/src/io/socketstream.nim
@@ -1,12 +1,14 @@
+import nativesockets
import net
import streams
+
when defined(posix):
import posix
import io/process
type SocketStream* = ref object of Stream
- source: Socket
+ source*: Socket
isend: bool
proc sockReadData(s: Stream, buffer: pointer, len: int): int =
@@ -29,7 +31,9 @@ proc sockClose(s: Stream) = {.cast(tags: []).}: #...sigh
func newSocketStream*(): SocketStream =
new(result)
- result.readDataImpl = sockReadData
+ result.readDataImpl = cast[proc (s: Stream, buffer: pointer, bufLen: int): int
+ {.nimcall, raises: [Defect, IOError, OSError], tags: [ReadIOEffect], gcsafe.}
+ ](sockReadData) # ... ???
result.writeDataImpl = sockWriteData
result.atEndImpl = sockAtEnd
result.closeImpl = sockClose
diff --git a/src/js/javascript.nim b/src/js/javascript.nim
index 08639aa9..11bcb65d 100644
--- a/src/js/javascript.nim
+++ b/src/js/javascript.nim
@@ -209,7 +209,9 @@ func getOpaque*(ctx: JSContext, val: JSValue, class: string): pointer =
let opaque = JS_GetOpaque(global.val, 1) # JS_CLASS_OBJECT
free(global)
return opaque
- return JS_GetOpaque(val, val.getClassID())
+ if JS_VALUE_GET_TAG(val) == JS_TAG_OBJECT:
+ return JS_GetOpaque(val, val.getClassID())
+ return nil
func getOpaque*(obj: JSObject, class: string): pointer = getOpaque(obj.ctx, obj.val, class)
@@ -236,6 +238,7 @@ proc writeException*(ctx: JSContext, s: Stream) =
let str = toString(ctx, stack)
if str.issome:
s.write(str.get)
+ s.flush()
JS_FreeValue(ctx, stack)
JS_FreeValue(ctx, ex)