diff options
| author | bptato <nincsnevem662@gmail.com> | 2021-12-21 17:11:58 +0100 |
|---|---|---|
| committer | bptato <nincsnevem662@gmail.com> | 2021-12-21 17:11:58 +0100 |
| commit | 8a1611e1c6c81b4ee5b7f33f3f539ee1db53045e (patch) | |
| tree | 998ca1deeb00092f70de183515b2df847e1dfaa0 /src | |
| parent | bbb14729f8b0c612f79ba96566d0118fc8c2290d (diff) | |
| download | chawan-8a1611e1c6c81b4ee5b7f33f3f539ee1db53045e.tar.gz | |
Honestly I'm not sure what I added here...
Diffstat (limited to 'src')
| -rw-r--r-- | src/client.nim | 156 | ||||
| -rw-r--r-- | src/config/config.nim | 1 | ||||
| -rw-r--r-- | src/html/parser.nim | 64 | ||||
| -rw-r--r-- | src/io/buffer.nim | 138 | ||||
| -rw-r--r-- | src/io/cell.nim | 29 | ||||
| -rw-r--r-- | src/io/term.nim | 4 | ||||
| -rw-r--r-- | src/layout/box.nim | 3 | ||||
| -rw-r--r-- | src/layout/engine.nim | 38 | ||||
| -rw-r--r-- | src/types/url.nim | 245 | ||||
| -rw-r--r-- | src/utils/twtstr.nim | 3 |
10 files changed, 497 insertions, 184 deletions
diff --git a/src/client.nim b/src/client.nim index 41962288..b644f5d9 100644 --- a/src/client.nim +++ b/src/client.nim @@ -2,21 +2,45 @@ import httpclient import streams import uri import terminal +import os import io/buffer import io/lineedit import config/config import html/parser import utils/twtstr +#import types/url type Client* = ref object http: HttpClient buffers: seq[Buffer] - prevuri: Uri + currentbuffer: int feednext: bool s: string +proc die() = + eprint "Invalid parameters. Usage:\ntwt <url>" + quit(1) + +proc newClient*(): Client = + new(result) + result.http = newHttpClient() + result.currentbuffer = -1 + +func pbuffer(client: Client): Buffer = + return client.buffers[client.currentbuffer - 1] + +func buffer(client: Client): Buffer = + return client.buffers[client.currentbuffer] + +func nbuffer(client: Client): Buffer = + return client.buffers[client.currentbuffer + 1] + +func puri(client: Client): Uri = + if client.currentbuffer > 0: + return client.pbuffer.location + proc loadRemotePage*(client: Client, url: string): string = return client.http.getContent(url) @@ -31,35 +55,46 @@ proc getLocalPage*(url: string): Stream = proc getPageUri(client: Client, uri: Uri): Stream = var moduri = uri - moduri.anchor = "" - if uri.scheme == "" or uri.scheme == "file": + if moduri.scheme == "file": + moduri.scheme = "" return getLocalPage($moduri) - else: + elif moduri.scheme == "http" or moduri.scheme == "https": return client.getRemotePage($moduri) -proc die() = - eprint "Invalid parameters. Usage:\ntwt <url>" - quit(1) - -proc newClient*(): Client = - new(result) - result.http = newHttpClient() - proc addBuffer(client: Client) = - client.buffers.add(newBuffer()) - -func buffer(client: Client): Buffer = - return client.buffers[^1] + inc client.currentbuffer + client.buffers.insert(newBuffer(), client.currentbuffer) + +proc prevBuffer(client: Client) = + if client.currentbuffer > 0: + dec client.currentbuffer + client.buffer.redraw = true + +proc nextBuffer(client: Client) = + if client.currentbuffer < client.buffers.len - 1: + inc client.currentbuffer + client.buffer.redraw = true + +proc discardBuffer(client: Client) = + if client.currentbuffer < client.buffers.len - 1: + client.buffers.delete(client.currentbuffer) + client.buffer.redraw = true + elif client.currentbuffer > 0: + client.buffers.delete(client.currentbuffer) + dec client.currentbuffer + client.buffer.redraw = true + else: + client.buffer.setStatusMessage("Can't discard last buffer!") -proc setupBuffer*(client: Client) = +proc setupBuffer(client: Client) = let buffer = client.buffer - buffer.setLocation(client.prevuri) buffer.document = parseHtml(newStringStream(client.buffer.source)) buffer.render() buffer.gotoAnchor() buffer.redraw = true proc readPipe(client: Client) = + client.addBuffer() if not stdin.isatty: client.buffer.showsource = true try: @@ -72,26 +107,51 @@ proc readPipe(client: Client) = die() client.setupBuffer() +proc mergeURLs(client: Client, urla, urlb: Uri): Uri = + var moduri = urlb + if moduri.scheme == "": + moduri.scheme = urla.scheme + if moduri.scheme == "": + moduri.scheme = "file" + if moduri.hostname == "": + moduri.hostname = urla.hostname + if moduri.path == "": + moduri.path = urla.path + elif urla.path != "": + moduri.path = urla.path.splitFile().dir / moduri.path + return moduri + +proc gotoURL(client: Client, url: Uri) = + var newuri = url + client.addBuffer() + newuri = client.mergeUrls(client.puri, newuri) + if client.puri != url or newuri.anchor == "": + let s = client.getPageUri(newuri) + if s != nil: + client.buffer.source = s.readAll() #TODO + else: + client.discardBuffer() + client.buffer.setStatusMessage("Couldn't load " & $newuri) + return + elif newuri.anchor != "": + client.buffer.source = client.pbuffer.source + let newanchor = newuri.anchor + newuri = client.buffer.location + newuri.anchor = newanchor + client.buffer.setLocation(newuri) + client.setupBuffer() + proc gotoURL(client: Client, url: string) = - var newuri = parseUri(url) - let newanchor = newuri.anchor - let prevanchor = client.prevuri.anchor - client.prevuri.anchor = "" - newuri.anchor = "" - let prevs = $client.prevuri - let news = $newuri - client.prevuri.anchor = prevanchor - newuri.anchor = newanchor - if news != "": - client.addBuffer() - client.buffer.source = client.getPageUri(newuri).readAll() #TODO - elif prevanchor != newanchor: - let psource = client.buffer.source - client.addBuffer() - client.buffer.source = psource + client.gotoURL(parseUri(url)) - client.prevuri = newuri - client.setupBuffer() +proc reloadPage(client: Client) = + let buffer = client.buffer + var location = buffer.location + location.anchor = "" + client.gotoURL(location) + client.buffer.setCursorXY(client.pbuffer.cursorx, client.pbuffer.cursory) + client.buffer.setFromXY(client.pbuffer.fromx, client.pbuffer.fromy) + client.buffer.showsource = client.pbuffer.showsource proc changeLocation(client: Client) = let buffer = client.buffer @@ -107,6 +167,21 @@ proc click(client: Client) = if s != "": client.gotoURL(s) +proc toggleSource*(client: Client) = + let buffer = client.buffer + if buffer.sourcepair != nil: + for i in 0..high(client.buffers): + if client.buffers[i] == buffer.sourcepair: + client.currentbuffer = i + break + eprint "Fatal error (???)" + else: + client.addBuffer() + client.buffer.sourcepair = client.pbuffer + client.buffer.source = client.pbuffer.source + client.buffer.showsource = not client.pbuffer.showsource + client.setupBuffer() + proc input(client: Client) = let buffer = client.buffer if not client.feednext: @@ -154,15 +229,16 @@ proc input(client: Client) = of ACTION_CHANGE_LOCATION: client.changeLocation() of ACTION_LINE_INFO: buffer.lineInfo() of ACTION_FEED_NEXT: client.feednext = true - of ACTION_RELOAD: client.gotoURL($buffer.location) + of ACTION_RELOAD: client.reloadPage() of ACTION_RESHAPE: buffer.reshape = true of ACTION_REDRAW: buffer.redraw = true - of ACTION_TOGGLE_SOURCE: buffer.toggleSource() + of ACTION_TOGGLE_SOURCE: client.toggleSource() + of ACTION_PREV_BUFFER: client.prevBuffer() + of ACTION_NEXT_BUFFER: client.nextBuffer() + of ACTION_DISCARD_BUFFER: client.discardBuffer() else: discard proc launchClient*(client: Client, params: seq[string]) = - client.addBuffer() - if params.len < 1: client.readPipe() else: diff --git a/src/config/config.nim b/src/config/config.nim index 04cefb33..411a26a8 100644 --- a/src/config/config.nim +++ b/src/config/config.nim @@ -21,6 +21,7 @@ type ACTION_SCROLL_DOWN, ACTION_SCROLL_UP, ACTION_SCROLL_LEFT, ACTION_SCROLL_RIGHT, ACTION_CLICK, ACTION_CHANGE_LOCATION, + ACTION_PREV_BUFFER, ACTION_NEXT_BUFFER, ACTION_DISCARD_BUFFER, ACTION_RELOAD, ACTION_RESHAPE, ACTION_REDRAW, ACTION_TOGGLE_SOURCE, ACTION_CURSOR_FIRST_LINE, ACTION_CURSOR_LAST_LINE, ACTION_CURSOR_TOP, ACTION_CURSOR_MIDDLE, ACTION_CURSOR_BOTTOM, diff --git a/src/html/parser.nim b/src/html/parser.nim index 8c92b5d6..b882d68e 100644 --- a/src/html/parser.nim +++ b/src/html/parser.nim @@ -332,18 +332,18 @@ proc processDocumentEndElement(state: var HTMLParseState, tag: DOMParsedTag) = proc processDocumentTag(state: var HTMLParseState, tag: DOMParsedTag) = if state.in_script: - if tag.tagid == TAG_SCRIPT: + if not tag.open and tag.tagid == TAG_SCRIPT: state.in_script = false else: return if state.in_style: - if tag.tagid == TAG_STYLE: + if not tag.open and tag.tagid == TAG_STYLE: state.in_style = false else: return - if state.in_noscript: + if not tag.open and state.in_noscript: if tag.tagid == TAG_NOSCRIPT: state.in_noscript = false else: @@ -361,16 +361,33 @@ proc processDocumentPart(state: var HTMLParseState, buf: string) = max = buf.len + template process_char(c: char) = + if state.in_comment: + state.commentNode.data &= c + else: + if not (state.skip_lf and c == '\n'): + processDocumentText(state) + state.textNode.data &= c + state.skip_lf = false + + template process_text(s: string) = + if state.in_comment: + state.commentNode.data &= s + else: + if not (state.skip_lf and s[0] == '\n'): + processDocumentText(state) + state.textNode.data &= s + state.skip_lf = false + + template has(buf: string, s: string): bool = + (at + s.len < buf.len and buf.substr(at, at + 8) == "</script>") + while at < max: case buf[at] of '&': inc at let p = getescapecmd(buf, at) - if state.in_comment: - state.commentNode.data &= p - else: - processDocumentText(state) - state.textNode.data &= p + process_text(p) of '<': if state.in_comment: state.commentNode.data &= buf[at] @@ -402,19 +419,16 @@ proc processDocumentPart(state: var HTMLParseState, buf: string) = if state.textNode != nil: state.textNode = nil p = at - var tag = parse_tag(buf, at) - was_script = state.in_script - - processDocumentTag(state, tag) -# if (was_script) { -# if (state->in_script) { -# ptr = p; -# processDocumentText(&state->parentNode, &state->textNode); -# Strcat_char(((CharacterData *)state->textNode)->data, *ptr++); -# } else if (buffer->javascript_enabled) { -# loadJSToBuffer(buffer, childTextContentNode(state->parentNode->lastChild)->ptr, "<inline>", state->document); -# } -# } + if state.in_script: + if buf.has("</script>"): + var tag = parse_tag(buf, at) + processDocumentTag(state, tag) + else: + process_char(buf[at]) + inc at + else: + var tag = parse_tag(buf, at) + processDocumentTag(state, tag) elif buf[at] == '-' and state.in_comment: var p = at inc p @@ -430,13 +444,7 @@ proc processDocumentPart(state: var HTMLParseState, buf: string) = state.commentNode.data &= buf[at] inc at else: - if state.in_comment: - state.commentNode.data &= buf[at] - else: - if not (state.skip_lf and buf[at] == '\n'): - processDocumentText(state) - state.textNode.data &= buf[at] - state.skip_lf = false + process_char(buf[at]) inc at proc parseHtml*(inputStream: Stream): Document = diff --git a/src/io/buffer.nim b/src/io/buffer.nim index 3180aa2b..775e6557 100644 --- a/src/io/buffer.nim +++ b/src/io/buffer.nim @@ -43,6 +43,7 @@ type showsource*: bool rootbox*: CSSBox prevnodes*: seq[Node] + sourcepair*: Buffer proc newBuffer*(): Buffer = new(result) @@ -68,7 +69,6 @@ func generateFullOutput*(buffer: Buffer): string = x = 0 w = 0 - result &= formatting.processFormatting(cell.formatting) result &= $cell.runes @@ -82,7 +82,7 @@ func generateFullOutput*(buffer: Buffer): string = # generate a sequence of instructions to replace the previous frame with the # current one. ideally should be used when small changes are made (e.g. hover # changes underlining) -func generateSwapOutput*(buffer: Buffer): string = +func generateSwapOutput(buffer: Buffer): string = var formatting = newFormatting() let curr = buffer.display let prev = buffer.prevdisplay @@ -151,17 +151,24 @@ func generateSwapOutput*(buffer: Buffer): string = #if text.len > 0: # result &= $text -func generateStatusMessage*(buffer: Buffer): string = +func generateStatusMessage(buffer: Buffer): string = + result &= HVP(buffer.height + 1, 1) + result &= SGR() + var formatting = newFormatting() + var w = 0 for cell in buffer.statusmsg: - for r in cell.runes: - if r != Rune(0): - result &= $r + result &= formatting.processFormatting(cell.formatting) + result &= $cell.runes + w += cell.width() + if w < buffer.width: + result &= EL() + result &= SGR() -func numLines*(buffer: Buffer): int = buffer.lines.len +func numLines(buffer: Buffer): int = buffer.lines.len -func lastVisibleLine*(buffer: Buffer): int = min(buffer.fromy + buffer.height, buffer.numLines) +func lastVisibleLine(buffer: Buffer): int = min(buffer.fromy + buffer.height, buffer.numLines) -func currentLineWidth*(buffer: Buffer): int = +func currentLineWidth(buffer: Buffer): int = if buffer.cursory > buffer.lines.len: return 0 return buffer.lines[buffer.cursory].width() @@ -224,33 +231,22 @@ func maxScreenWidth*(buffer: Buffer): int = for line in buffer.lines[buffer.fromy..buffer.lastVisibleLine - 1]: result = max(line.width(), result) -func atPercentOf*(buffer: Buffer): int = +func atPercentOf(buffer: Buffer): int = if buffer.lines.len == 0: return 100 return (100 * (buffer.cursory + 1)) div buffer.numLines -func canScroll*(buffer: Buffer): bool = - return buffer.numLines >= buffer.height - proc addLine(buffer: Buffer) = buffer.lines.addLine() -proc clearText*(buffer: Buffer) = +proc clearText(buffer: Buffer) = buffer.lines.setLen(0) buffer.addLine() -proc clearBuffer*(buffer: Buffer) = - buffer.clearText() - buffer.cursorx = 0 - buffer.cursory = 0 - buffer.fromx = 0 - buffer.fromy = 0 - buffer.hovertext = "" - -proc clearDisplay*(buffer: Buffer) = +proc clearDisplay(buffer: Buffer) = buffer.prevdisplay = buffer.display buffer.display = newFixedGrid(buffer.width, buffer.height) -proc refreshDisplay*(buffer: Buffer) = +proc refreshDisplay(buffer: Buffer) = var r: Rune var y = 0 buffer.clearDisplay() @@ -297,33 +293,7 @@ proc refreshDisplay*(buffer: Buffer) = proc restoreCursorX(buffer: Buffer) = buffer.cursorx = max(min(buffer.currentLineWidth() - 1, buffer.xend), 0) -proc scrollTo*(buffer: Buffer, y: int) = - if y == buffer.fromy: - return - buffer.fromy = min(max(buffer.numLines - buffer.height, 0), y) - buffer.cursory = min(max(buffer.fromy, buffer.cursory), buffer.fromy + buffer.height) - buffer.redraw = true - buffer.restoreCursorX() - -proc cursorTo*(buffer: Buffer, x, y: int) = - buffer.redraw = false - buffer.cursory = min(max(y, 0), buffer.numLines - 1) - if buffer.fromy > buffer.cursory: - buffer.fromy = max(buffer.cursory, 0) - buffer.redraw = true - elif buffer.fromy + buffer.height - 1 <= buffer.cursory: - buffer.fromy = max(buffer.cursory - buffer.height + 1, 0) - buffer.redraw = true - - buffer.cursorx = min(max(x, 0), buffer.currentLineWidth()) - if buffer.fromx < buffer.cursorx - buffer.width: - buffer.fromx = max(0, buffer.cursorx - buffer.width) - buffer.redraw = true - elif buffer.fromx > buffer.cursorx: - buffer.fromx = buffer.cursorx - buffer.redraw = true - -proc setCursorXB*(buffer: Buffer, byte: int) = +proc setCursorXB(buffer: Buffer, byte: int) = var b = buffer.currentCursorBytes() if byte == b: return @@ -352,8 +322,7 @@ proc setCursorXB*(buffer: Buffer, byte: int) = buffer.redraw = true buffer.xend = buffer.cursorx - -proc setCursorX*(buffer: Buffer, x: int) = +proc setCursorX(buffer: Buffer, x: int) = if buffer.cursorx == x: return var b = buffer.currentCursorBytes() @@ -380,7 +349,7 @@ proc setCursorX*(buffer: Buffer, x: int) = buffer.redraw = true buffer.xend = buffer.cursorx -proc setCursorY*(buffer: Buffer, y: int) = +proc setCursorY(buffer: Buffer, y: int) = if buffer.cursory == y: return if y - buffer.fromy >= 0 and y - buffer.height < buffer.fromy: @@ -394,6 +363,18 @@ proc setCursorY*(buffer: Buffer, y: int) = buffer.redraw = true buffer.restoreCursorX() +proc setCursorXY*(buffer: Buffer, x, y: int) = + buffer.setCursorY(max(min(y, buffer.numLines - 1), 0)) + buffer.setCursorX(max(min(buffer.currentLineWidth(), x), 0)) + +proc setFromXY*(buffer: Buffer, x, y: int) = + buffer.fromy = max(min(y, buffer.maxfromy), 0) + buffer.fromx = max(min(x, buffer.maxfromx), 0) + +proc setCursorXBY(buffer: Buffer, x, y: int) = + buffer.setCursorY(y) + buffer.setCursorXB(x) + proc cursorDown*(buffer: Buffer) = if buffer.cursory < buffer.numLines - 1: buffer.setCursorY(buffer.cursory + 1) @@ -507,8 +488,7 @@ proc cursorNextLink*(buffer: Buffer) = let format = line.formats[i] let fl = format.nodes.getLink() if fl != nil and fl != link: - buffer.setCursorY(y) - buffer.setCursorXB(format.pos) + buffer.setCursorXBY(format.pos, y) return inc i @@ -548,8 +528,7 @@ proc cursorPrevLink*(buffer: Buffer) = ly = iy lx = format.pos dec i - buffer.setCursorY(ly) - buffer.setCursorXB(lx) + buffer.setCursorXBY(lx, ly) return dec i @@ -794,7 +773,8 @@ proc updateHover(buffer: Buffer) = elem.refreshStyle() let link = nodes.getLink() if link != nil: - buffer.hovertext = "(link)" + if link.tagType == TAG_A: + buffer.hovertext = HTMLAnchorElement(link).href else: buffer.hovertext = "" for node in buffer.prevnodes: @@ -857,7 +837,7 @@ let ua_stylesheet = newStringStream(css).parseStylesheet() #TODO refactor var ss_init = false var user_stylesheet: CSSStylesheet -proc renderDocument*(buffer: Buffer) = +proc renderDocument(buffer: Buffer) = buffer.clearText() if not ss_init: @@ -866,8 +846,6 @@ proc renderDocument*(buffer: Buffer) = buffer.document.applyStylesheets(ua_stylesheet, user_stylesheet) buffer.rootbox = buffer.document.alignBoxes(buffer.attrs) - if buffer.rootbox == nil: - return var stack: seq[CSSBox] stack.add(buffer.rootbox) while stack.len > 0: @@ -888,7 +866,7 @@ proc render*(buffer: Buffer) = else: buffer.renderDocument() -proc cursorBufferPos*(buffer: Buffer) = +proc cursorBufferPos(buffer: Buffer) = let x = max(buffer.cursorx - buffer.fromx, 0) let y = buffer.cursory - buffer.fromy print(HVP(y + 1, x + 1)) @@ -896,27 +874,33 @@ proc cursorBufferPos*(buffer: Buffer) = proc clearStatusMessage(buffer: Buffer) = buffer.statusmsg = newFixedGrid(buffer.width) -proc setStatusMessage*(buffer: Buffer, str: string) = +proc writeStatusMessage(buffer: Buffer, str: string, formatting: Formatting = Formatting()) = buffer.clearStatusMessage() - let text = str.toRunes() var i = 0 - var n = 0 - while i < text.len: - if text[i].width() == 0: - inc n - buffer.statusmsg[i - n].runes.add(text[i]) - inc i + for r in str.runes: + i += r.width() + if i >= buffer.statusmsg.len: + buffer.statusmsg[^1].runes.setLen(0) + buffer.statusmsg[^1].runes.add(Rune('$')) + break + buffer.statusmsg[i].runes.add(r) + buffer.statusmsg[i].formatting = formatting proc statusMsgForBuffer(buffer: Buffer) = var msg = $(buffer.cursory + 1) & "/" & $buffer.numLines & " (" & $buffer.atPercentOf() & "%) " & "<" & buffer.title & ">" if buffer.hovertext.len > 0: msg &= " " & buffer.hovertext - buffer.setStatusMessage(msg.ansiStyle(styleReverse).ansiReset()) + var formatting: Formatting + formatting.reverse_on + buffer.writeStatusMessage(msg, formatting) + +proc setStatusMessage*(buffer: Buffer, str: string) = + buffer.writeStatusMessage(str) + buffer.nostatus = true proc lineInfo*(buffer: Buffer) = buffer.setStatusMessage("line " & $(buffer.cursory + 1) & "/" & $buffer.numLines & " col " & $(buffer.cursorx + 1) & "/" & $buffer.currentLineWidth() & " cell width: " & $buffer.currentDisplayCell().width()) - buffer.nostatus = true proc displayBufferSwapOutput(buffer: Buffer) = print(buffer.generateSwapOutput()) @@ -925,15 +909,7 @@ proc displayBuffer(buffer: Buffer) = print(buffer.generateFullOutput()) proc displayStatusMessage*(buffer: Buffer) = - print(HVP(buffer.height + 1, 1)) - print(SGR()) print(buffer.generateStatusMessage()) - print(EL()) - -proc toggleSource*(buffer: Buffer) = - buffer.showsource = not buffer.showsource - buffer.reshape = true - buffer.redraw = true proc click*(buffer: Buffer): string = let link = buffer.getCursorLink() diff --git a/src/io/cell.nim b/src/io/cell.nim index f8b2b3cb..a4f56d61 100644 --- a/src/io/cell.nim +++ b/src/io/cell.nim @@ -14,6 +14,7 @@ type FLAG_UNDERLINE FLAG_STRIKE FLAG_OVERLINE + FLAG_REVERSE Formatting* = object fgcolor*: CellColor @@ -42,6 +43,7 @@ type func italic(formatting: Formatting): bool = FLAG_ITALIC in formatting.flags func bold(formatting: Formatting): bool = FLAG_BOLD in formatting.flags func underline(formatting: Formatting): bool = FLAG_UNDERLINE in formatting.flags +func reverse(formatting: Formatting): bool = FLAG_REVERSE in formatting.flags func strike(formatting: Formatting): bool = FLAG_STRIKE in formatting.flags func overline(formatting: Formatting): bool = FLAG_OVERLINE in formatting.flags @@ -54,28 +56,15 @@ proc bold_off*(formatting: var Formatting) = formatting.flags.excl(FLAG_BOLD) proc underline_on*(formatting: var Formatting) = formatting.flags.incl(FLAG_UNDERLINE) proc underline_off*(formatting: var Formatting) = formatting.flags.excl(FLAG_UNDERLINE) +proc reverse_on*(formatting: var Formatting) = formatting.flags.incl(FLAG_REVERSE) +proc reverse_off*(formatting: var Formatting) = formatting.flags.excl(FLAG_REVERSE) + proc strike_on*(formatting: var Formatting) = formatting.flags.incl(FLAG_STRIKE) proc strike_off*(formatting: var Formatting) = formatting.flags.excl(FLAG_STRIKE) proc overline_on*(formatting: var Formatting) = formatting.flags.incl(FLAG_OVERLINE) proc overline_off*(formatting: var Formatting) = formatting.flags.excl(FLAG_OVERLINE) -proc `bold=`*(formatting: var Formatting, b: bool) = - if b: formatting.flags.incl(FLAG_BOLD) - else: formatting.flags.excl(FLAG_BOLD) - -proc `underline=`*(formatting: var Formatting, b: bool) = - if b: formatting.flags.incl(FLAG_UNDERLINE) - else: formatting.flags.excl(FLAG_UNDERLINE) - -proc `strike=`*(formatting: var Formatting, b: bool) = - if b: formatting.flags.incl(FLAG_STRIKE) - else: formatting.flags.excl(FLAG_STRIKE) - -proc `overline=`*(formatting: var Formatting, b: bool) = - if b: formatting.flags.incl(FLAG_OVERLINE) - else: formatting.flags.excl(FLAG_OVERLINE) - #TODO ????? func `==`*(a: FixedCell, b: FixedCell): bool = return a.formatting == b.formatting and @@ -215,12 +204,16 @@ proc parseAnsiCode*(formatting: var Formatting, buf: string, fi: int): int = formatting.italic_on of 4: formatting.underline_on + of 7: + formatting.reverse_on of 9: formatting.strike_on of 22: formatting.bold_off of 23: formatting.italic_off + of 27: + formatting.reverse_off of 29: formatting.strike_off of 30..37: @@ -285,6 +278,8 @@ proc processFormatting*(formatting: var Formatting, cellf: Formatting): string = result &= SGR(23) if formatting.underline and not cellf.underline: result &= SGR(24) + if formatting.reverse and not cellf.reverse: + result &= SGR(27) if formatting.strike and not cellf.strike: result &= SGR(29) if formatting.overline and not cellf.overline: @@ -318,6 +313,8 @@ proc processFormatting*(formatting: var Formatting, cellf: Formatting): string = result &= SGR(3) if not formatting.underline and cellf.underline: result &= SGR(4) + if not formatting.reverse and cellf.reverse: + result &= SGR(7) if not formatting.strike and cellf.strike: result &= SGR(9) if not formatting.overline and cellf.overline: diff --git a/src/io/term.nim b/src/io/term.nim index a51b2a56..2e859d66 100644 --- a/src/io/term.nim +++ b/src/io/term.nim @@ -16,7 +16,7 @@ proc getTermAttributes*(): TermAttributes = when defined(posix): var win: IOctl_WinSize if ioctl(cint(getOsFileHandle(stdout)), TIOCGWINSZ, addr win) != -1: - result.width = int(win.ws_col) + result.width = int(win.ws_col) - 1 result.height = int(win.ws_row) result.width_px = int(win.ws_xpixel) result.height_px = int(win.ws_ypixel) @@ -24,7 +24,7 @@ proc getTermAttributes*(): TermAttributes = result.ppl = int(win.ws_ypixel) div int(win.ws_row) return #fail - result.width = terminalWidth() + result.width = terminalWidth() - 1 result.height = terminalHeight() if result.height == 0: result.height = 24 diff --git a/src/layout/box.nim b/src/layout/box.nim index adcb5a0a..711e5aff 100644 --- a/src/layout/box.nim +++ b/src/layout/box.nim @@ -18,6 +18,7 @@ type t*: BoxType x*: int y*: int + width*: int children*: seq[CSSBox] icontext*: InlineContext bcontext*: BlockContext @@ -27,7 +28,7 @@ type InlineContext* = ref object fromx*: int fromy*: int - conty*: bool + xhigh*: int whitespace*: bool ws_initial*: bool rows*: seq[CSSRowBox] diff --git a/src/layout/engine.nim b/src/layout/engine.nim index 7628416d..26b6ce02 100644 --- a/src/layout/engine.nim +++ b/src/layout/engine.nim @@ -57,12 +57,14 @@ proc flushRows(icontext: InlineContext) = icontext.rows.add(icontext.thisrow) icontext.thisrow.setLen(0) +func conty(icontext: InlineContext): bool = + icontext.thisrow.len > 0 + proc flushConty(box: CSSBox) = box.icontext.flushRows() box.icontext.fromx = box.x inc box.icontext.fromy inc box.bcontext.fromy - box.icontext.conty = false box.icontext.whitespace = true box.icontext.ws_initial = true @@ -134,6 +136,7 @@ func newInlineBox*(state: LayoutState, parent: CSSBox, vals: CSSSpecifiedValues) type InlineState = object icontext: InlineContext bcontext: BlockContext + ibox: CSSInlineBox rowbox: CSSRowBox word: seq[Rune] ww: int @@ -142,6 +145,8 @@ type InlineState = object cssvalues: CSSSpecifiedValues x: int +func maxwidth(state: InlineState): int = state.bcontext.width - state.x + proc newRowBox(state: var InlineState) = state.rowbox = CSSRowBox() state.rowbox.x = state.icontext.fromx @@ -166,22 +171,22 @@ proc inlineWrap(state: var InlineState) = if state.word.len == 0: state.icontext.whitespace = true state.icontext.ws_initial = true - state.icontext.conty = false else: if state.word[^1] == Rune(' '): state.icontext.whitespace = true state.icontext.ws_initial = false - state.icontext.conty = true state.newRowBox() proc addWord(state: var InlineState) = state.rowbox.str &= $state.word state.rowbox.width += state.ww + state.ibox.width += state.ww + state.ibox.width = min(state.maxwidth, state.ibox.width) state.word.setLen(0) state.ww = 0 proc wrapNormal(state: var InlineState, r: Rune) = - if state.icontext.fromx + state.rowbox.width + state.ww == state.bcontext.width and r == Rune(' '): + if state.icontext.fromx + state.rowbox.width + state.ww == state.maxwidth and r == Rune(' '): state.addWord() if state.word.len == 0: if r == Rune(' '): @@ -200,7 +205,7 @@ proc checkWrap(state: var InlineState, r: Rune) = case state.cssvalues{"word-break"} of WORD_BREAK_NORMAL: if state.icontext.fromx + state.rowbox.width > state.x and - state.icontext.fromx + state.rowbox.width + state.ww + r.width() > state.x + state.bcontext.width: + state.icontext.fromx + state.rowbox.width + state.ww + r.width() > state.maxwidth: state.wrapNormal(r) of WORD_BREAK_BREAK_ALL: if state.icontext.fromx + state.rowbox.width + state.ww + r.width() > state.x + state.bcontext.width: @@ -233,14 +238,13 @@ proc preWrap(state: var InlineState) = state.icontext.ws_initial = true state.skip = true -proc processInlineText(str: string, icontext: InlineContext, - bcontext: BlockContext, cssvalues: CSSSpecifiedValues, - x: int, nodes: seq[Node]) = +proc processInlineText(str: string, ibox: CSSInlineBox, nodes: seq[Node]) = var state: InlineState - state.icontext = icontext - state.bcontext = bcontext - state.cssvalues = cssvalues - state.x = x + state.ibox = ibox + state.icontext = ibox.icontext + state.bcontext = ibox.bcontext + state.cssvalues = ibox.cssvalues + state.x = ibox.x state.nodes = nodes var i = 0 @@ -300,13 +304,12 @@ proc processInlineText(str: string, icontext: InlineContext, if state.rowbox.str.len > 0: state.addRowBox() state.icontext.fromx += state.rowbox.width - state.icontext.conty = true state.bcontext.margin_todo = 0 state.bcontext.margin_done = 0 proc processInlineContext(ibox: CSSInlineBox, str: string, nodes: seq[Node]) = - processInlineText(str, ibox.icontext, ibox.bcontext, ibox.cssvalues, ibox.x, nodes) + processInlineText(str, ibox, nodes) proc processInlineBox(state: var LayoutState, parent: CSSBox, str: string): CSSInlineBox = if str.len == 0: @@ -347,15 +350,18 @@ proc add(state: var LayoutState, parent: CSSBox, box: CSSBlockBox) = parent.children.add(box) proc add(state: var LayoutState, parent: CSSBox, box: CSSInlineBox) = + parent.width = max(parent.width, box.width) parent.icontext.fromx += box.cssvalues{"margin-right"}.cells_w(state, parent.bcontext.width) parent.icontext.fromy = box.icontext.fromy parent.children.add(box) proc add(state: var LayoutState, parent: CSSBox, box: CSSInlineBlockBox) = - parent.icontext.fromx = max(box.icontext.fromx, box.bcontext.width) + parent.width = max(parent.width, box.width) + parent.icontext.fromx = max(box.icontext.fromx, box.x + box.width) parent.icontext.fromx += box.cssvalues{"margin-right"}.cells_w(state, parent.bcontext.width) - parent.icontext.conty = box.icontext.conty + parent.icontext.whitespace = box.icontext.whitespace + parent.icontext.ws_initial = box.icontext.ws_initial box.icontext.putRows() parent.icontext.thisrow.add(box.icontext.rows) diff --git a/src/types/url.nim b/src/types/url.nim new file mode 100644 index 00000000..8eec6090 --- /dev/null +++ b/src/types/url.nim @@ -0,0 +1,245 @@ +#See https://url.spec.whatwg.org/#url-parsing. +import strutils +import tables +import options +import unicode + +import utils/twtstr + +type + UrlState = enum + STATE_OVERRIDE, SCHEME_START_STATE, SCHEME_STATE, NO_SCHEME_STATE, + FILE_STATE, SPECIAL_RELATIVE_OR_AUTHORITY_STATE, + SPECIAL_AUTHORITY_SLASHES_STATE, PATH_OR_AUTHORITY_STATE, + OPAQUE_PATH_STATE, FRAGMENT_STATE, RELATIVE_STATE, + SPECIAL_AUTHORITY_IGNORE_SLASHES_STATE, AUTHORITY_STATE, PATH_STATE, + RELATIVE_SLASH_STATE, QUERY_STATE + + Blob* = object + + BlobUrlEntry* = object + obj: Blob #TODO + + UrlPath* = object + case opaque*: bool + of true: + s*: string + else: + ss*: seq[string] + + Url* = object + failure*: bool + isnull: bool + encoding: int #TODO + scheme: string + username: string + password: string + port: int + host: string + path: UrlPath + query: Option[string] + fragment: Option[string] + blob: Option[BlobUrlEntry] + +const NullUrl = Url(isnull: true) +const EmptyPath = UrlPath(opaque: true, s: "") + +const SpecialSchemes = { + "ftp": 21, + "file": -1, + "http": 80, + "https": 443, + "ws": 80, + "wss": 443, +}.toTable() + +proc shorten(url: var Url) = + assert not url.path.opaque + + if url.scheme == "file" and url.path.ss.len == 1 and url.path.ss[0][0] in Letters and url.path.ss[0][1] == ':': + return + if url.path.ss.len >= 0: + discard url.path.ss.pop() + +#TODO encoding +proc basicParseUrl*(input: string, base: Url = NullUrl, url: Url = Url(), override: bool = false): Url = + #TODO If input contains any leading or trailing C0 control or space, validation error. + #TODO If input contains any ASCII tab or newline, validation error. + let input = input.strip(true, false, {chr(0x00)..chr(0x1F), ' '}).strip(true, false, {'\t', '\n'}) + var buffer = "" + var atsignseen = false + var insidebrackets = false + var passwordtokenseen = false + var pointer = 0 + var state = SCHEME_START_STATE + if override: + state = STATE_OVERRIDE + var url = url + template c(): char = input[pointer] + template c(i: int): char = input[pointer + i] + template has(i: int): bool = (pointer + i < input.len) + template return_failure() = return Url(failure: true) + template includes_credentials(url: Url): bool = url.username != "" or url.password != "" + template default_port(url: Url): bool = url.scheme in SpecialSchemes and url.port == SpecialSchemes[url.scheme] + template start_over() = pointer = -1 + while pointer < input.len: + case state + of SCHEME_START_STATE: + if c.isAlphaAscii(): + buffer &= c.tolower() + state = SCHEME_STATE + elif not override: + state = NO_SCHEME_STATE + dec pointer + else: + #TODO validation error + return_failure + of SCHEME_STATE: + if c in Letters + {'+', '-', '.'}: + buffer &= c.tolower() + elif c == ':': + if override: + if url.scheme in SpecialSchemes and buffer notin SpecialSchemes: + return url + if url.scheme notin SpecialSchemes and buffer in SpecialSchemes: + return url + if (url.includes_credentials or url.port != -1) and buffer == "file": + return url + if url.scheme == "file" and url.host == "": + return url + url.scheme = buffer + if override: + if url.default_port: + url.port = -1 + return url + buffer = "" + if url.scheme == "file": + #TODO If remaining does not start with "//", validation error. + state = FILE_STATE + elif url.scheme in SpecialSchemes and not base.isnull and base.scheme == url.scheme: + state = SPECIAL_RELATIVE_OR_AUTHORITY_STATE + elif url.scheme in SpecialSchemes: + state = SPECIAL_AUTHORITY_SLASHES_STATE + elif has(1) and c(1) == '/': + state = PATH_OR_AUTHORITY_STATE + else: + url.path = EmptyPath + state = OPAQUE_PATH_STATE + elif not override: + buffer = "" + state = NO_SCHEME_STATE + start_over + else: + #TODO validation error + return_failure + of NO_SCHEME_STATE: + if base.isnull or base.path.opaque and c != '#': + #TODO validation error + return_failure + elif base.path.opaque and c == '#': + url.scheme = base.scheme + url.path = base.path + url.query = base.query + url.fragment = some("") + state = FRAGMENT_STATE + elif base.scheme != "file": + state = RELATIVE_STATE + dec pointer + else: + state = FILE_STATE + dec pointer + of SPECIAL_RELATIVE_OR_AUTHORITY_STATE: + if c == '/' and has(1) and c(1) == '/': + state = SPECIAL_AUTHORITY_IGNORE_SLASHES_STATE + inc pointer + else: + #TODO validation error + state = RELATIVE_STATE + dec pointer + of PATH_OR_AUTHORITY_STATE: + if c == '/': + state = AUTHORITY_STATE + else: + state = PATH_STATE + dec pointer + of RELATIVE_STATE: + assert base.scheme != "file" + url.scheme = base.scheme + if c == '/': + state = RELATIVE_SLASH_STATE + elif url.scheme in SpecialSchemes and c == '\\': + #TODO validation error + state = RELATIVE_SLASH_STATE + else: + url.username = base.username + url.password = base.password + url.host = base.host + url.port = base.port + url.path = base.path + url.query = base.query + if c == '?': + url.query = "".some + state = QUERY_STATE + elif c == '#': + url.fragment = "".some + state = FRAGMENT_STATE + else: + url.query = none(string) + url.shorten() + state = PATH_STATE + dec pointer + of RELATIVE_SLASH_STATE: + if url.scheme in SpecialSchemes and c in {'/', '\\'}: + #TODO if c is \ validation error + state = SPECIAL_AUTHORITY_IGNORE_SLASHES_STATE + elif c == '/': + state = AUTHORITY_STATE + else: + url.username = base.username + url.password = base.password + url.host = base.host + url.port = base.port + state = PATH_STATE + dec pointer + of SPECIAL_AUTHORITY_SLASHES_STATE: + if c == '/' and has(1) and c(1) == '/': + state = SPECIAL_AUTHORITY_IGNORE_SLASHES_STATE + inc pointer + else: + #TODO validation error + state = SPECIAL_AUTHORITY_IGNORE_SLASHES_STATE + dec pointer + of SPECIAL_AUTHORITY_IGNORE_SLASHES_STATE: + if c notin {'/', '\\'}: + state = AUTHORITY_STATE + dec pointer + else: + #TODO validation error + discard + of AUTHORITY_STATE: + if c == '@': + #TODO validation error + if atsignseen: + buffer = "%40" & buffer + atsignseen = true + var i = 0 + while i < buffer.len: + if c == ':' and not passwordtokenseen: + passwordtokenseen = true + inc i + continue + var r: Rune + fastRuneAt(buffer, i, r) + #TODO finish this mess + #encodedcodepoints = + + inc pointer + +proc parseURL(input: string, base: Url = NullUrl, url: Url = Url(), override: bool = false): Url = + var url = basicParseUrl(input, base, url, override) + if url.failure: + return url + if url.scheme != "blob": + return url + url.blob = some(BlobUrlEntry()) + return url diff --git a/src/utils/twtstr.nim b/src/utils/twtstr.nim index 01f3cfb4..e7260f0f 100644 --- a/src/utils/twtstr.nim +++ b/src/utils/twtstr.nim @@ -45,6 +45,9 @@ func isControlChar*(r: Rune): bool = of Rune(0x7F): return true else: return false +func isC0ControlOrSpace*(c: char): bool = + return c in {chr(0x00)..chr(0x1F), ' '} + func genControlCharMap*(): string = for c in low(char)..high(char): if c == '?': |