about summary refs log tree commit diff stats
path: root/src/render/rendertext.nim
blob: e91c1e10d4fbac1c3799f35df96829605910f120 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import streams
import unicode

import buffer/cell
import data/charset
import encoding/decoderstream
import utils/twtstr

type StreamRenderer* = object
  ansiparser: AnsiCodeParser
  format: Format
  af: bool
  decoder: DecoderStream
  newline: bool
  w: int

proc newStreamRenderer*(stream: Stream): StreamRenderer =
  result.format = newFormat()
  result.ansiparser.state = PARSE_DONE
  result.decoder = newDecoderStream(stream, CHARSET_UTF_8)

proc renderStream*(grid: var FlexibleGrid, renderer: var StreamRenderer, len: int) =
  if len == 0: return
  template add_format() =
    if renderer.af:
      renderer.af = false
      grid[grid.high].addFormat(renderer.w, renderer.format)

  if grid.len == 0: grid.addLine()
  var buf = newSeq[Rune](len * 4)
  let n = renderer.decoder.readData(addr buf[0], buf.len * sizeof(buf[0]))
  for i in 0 ..< n div sizeof(buf[0]):
    if renderer.newline:
      # avoid newline at end of stream
      grid.addLine()
      renderer.newline = false
      renderer.w = 0
    let r = buf[i]
    if r.isAscii():
      let c = cast[char](r)
      if renderer.ansiparser.state != PARSE_DONE:
        let cancel = renderer.ansiparser.parseAnsiCode(renderer.format, c)
        if not cancel:
          if renderer.ansiparser.state == PARSE_DONE:
            renderer.af = true
          continue
      case c
      of '\n':
        add_format
        renderer.newline = true
      of '\r': discard
      of '\e':
        renderer.ansiparser.reset()
        continue
      else:
        add_format
        grid[^1].str &= c
    else:
      add_format
      grid[^1].str &= r
    renderer.w += r.twidth(renderer.w)