about summary refs log tree commit diff stats
path: root/src/io/buffer.nim
blob: 48bd64d37bcab7945d8ffa7ce69eb2e11e9ba2b5 (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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
import options
import streams
import terminal
import unicode

import css/cascade
import css/sheet
import html/dom
import html/tags
import html/parser
import io/term
import io/cell
import layout/box
import render/renderdocument
import render/rendertext
import types/url
import utils/twtstr

type
  Buffer* = ref object
    contenttype*: string
    title*: string
    lines*: FlexibleGrid
    display*: FixedGrid
    prevdisplay*: FixedGrid
    statusmsg*: FixedGrid
    hovertext*: string
    width*: int
    height*: int
    cursorx*: int
    cursory*: int
    xend*: int
    fromx*: int
    fromy*: int
    attrs*: TermAttributes
    document*: Document
    redraw*: bool
    reshape*: bool
    nostatus*: bool
    location*: Url
    ispipe*: bool
    istream*: Stream
    streamclosed*: bool
    source*: string
    rootbox*: CSSBox
    prevnodes*: seq[Node]
    sourcepair*: Buffer
    prev*: Buffer
    next* {.cursor.}: Buffer
    userstyle*: CSSStylesheet

proc newBuffer*(): Buffer =
  new(result)
  result.attrs = getTermAttributes()
  result.width = result.attrs.width
  result.height = result.attrs.height - 1

  result.display = newFixedGrid(result.width, result.height)
  result.prevdisplay = newFixedGrid(result.width, result.height)
  result.statusmsg = newFixedGrid(result.width)

func generateFullOutput(buffer: Buffer): string =
  var x = 0
  var w = 0
  var formatting = newFormatting()
  result &= HVP(1, 1)

  for cell in buffer.display:
    if x >= buffer.width:
      result &= EL()
      result &= '\n'
      x = 0
      w = 0

    result &= formatting.processFormatting(cell.formatting)
    result &= $cell.runes

    w += cell.width()
    inc x

  result &= EL()
  result &= '\n'

# 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 =
  var formatting = newFormatting()
  let curr = buffer.display
  let prev = buffer.prevdisplay
  var i = 0
  var x = 0
  var y = 0
  var line = ""
  var lr = false
  while i < curr.len:
    if x >= buffer.width:
      if lr:
        result &= HVP(y + 1, 1)
        result &= EL()
        result &= line
        lr = false
      x = 0
      inc y
      line = ""
    lr = lr or (curr[i] != prev[i])
    line &= formatting.processFormatting(curr[i].formatting)
    line &= $curr[i].runes
    inc i
    inc x
  if lr:
    result &= HVP(y + 1, 1)
    result &= EL()
    result &= line
    lr = false
  
  #TODO maybe fix this
  #var x = 0
  #var y = 0
  #var cx = -1
  #var cy = -1
  #var i = 0
  #var text = ""
  #while i < max:
  #  if x >= buffer.width:
  #    x = 0
  #    inc y

  #  if curr[i] != prev[i]:
  #    let currwidth = curr[i].runes.width()
  #    let prevwidth = prev[i].runes.width()
  #    if (curr[i].runes.len > 0 or currwidth < prevwidth) and (x != cx or y != cy):
  #      if text.len > 0:
  #        result &= text
  #        text = ""
  #      result &= HVP(y + 1, x + 1)
  #      cx = x
  #      cy = y

  #    text &= formatting.processFormatting(curr[i].formatting)

  #    text &= $curr[i].runes
  #    if currwidth < prevwidth:
  #      var j = 0
  #      while j < prevwidth - currwidth:
  #        text &= ' '
  #        inc j
  #    if text.len > 0:
  #      inc cx

  #  inc x
  #  inc i
  #if text.len > 0:
  #  result &= $text

func generateStatusMessage*(buffer: Buffer): string =
  var formatting = newFormatting()
  var w = 0
  for cell in buffer.statusmsg:
    result &= formatting.processFormatting(cell.formatting)
    result &= $cell.runes
    w += cell.width()
  if w < buffer.width:
    result &= EL()

func numLines*(buffer: Buffer): int = buffer.lines.len

func lastVisibleLine(buffer: Buffer): int = min(buffer.fromy + buffer.height, buffer.numLines)

func currentLineWidth(buffer: Buffer): int =
  return buffer.lines[buffer.cursory].width()

func maxfromy(buffer: Buffer): int = max(buffer.numLines - buffer.height, 0)

func maxfromx(buffer: Buffer): int = max(buffer.currentLineWidth() - buffer.width, 0)

func acursorx(buffer: Buffer): int =
  return max(0, buffer.cursorx - buffer.fromx)

func acursory(buffer: Buffer): int =
  return buffer.cursory - buffer.fromy

func cellOrigin(buffer: Buffer, x, y: int): int =
  let row = y * buffer.width
  var ox = x
  while buffer.display[row + ox].runes.len == 0 and ox > 0:
    dec ox
  return ox

func currentCellOrigin(buffer: Buffer): int =
  return buffer.cellOrigin(buffer.acursorx, buffer.acursory)

func currentDisplayCell(buffer: Buffer): FixedCell =
  let row = (buffer.cursory - buffer.fromy) * buffer.width
  return buffer.display[row + buffer.currentCellOrigin()]

func getLink(nodes: seq[Node]): Element =
  for node in nodes:
    if node.nodeType == ELEMENT_NODE:
      let elem = Element(node)
      if elem.tagType == TAG_A:
        return elem
  return nil

func getCursorLink(buffer: Buffer): Element =
  return buffer.currentDisplayCell().nodes.getLink()

func currentLine(buffer: Buffer): string =
  return buffer.lines[buffer.cursory].str

func currentCursorBytes(buffer: Buffer): int =
  let line = buffer.currentLine
  var w = 0
  var i = 0
  let cc = buffer.fromx + buffer.cursorx
  while i < line.len and w < cc:
    var r: Rune
    fastRuneAt(line, i, r)
    w += r.width()
  return i

func currentWidth(buffer: Buffer): int =
  let line = buffer.currentLine
  if line.len == 0: return 0
  var w = 0
  var i = 0
  let cc = buffer.fromx + buffer.cursorx
  var r: Rune
  fastRuneAt(line, i, r)
  while i < line.len and w < cc:
    fastRuneAt(line, i, r)
    w += r.width()
  return r.width()

func prevWidth(buffer: Buffer): int =
  let line = buffer.currentLine
  if line.len == 0: return 0
  var w = 0
  var i = 0
  let cc = buffer.fromx + buffer.cursorx
  var pr: Rune
  var r: Rune
  fastRuneAt(line, i, r)
  while i < line.len and w < cc:
    pr = r
    fastRuneAt(line, i, r)
    w += r.width()
  return pr.width()

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 =
  if buffer.lines.len == 0: return 100
  return (100 * (buffer.cursory + 1)) div buffer.numLines

func hasAnchor*(buffer: Buffer, anchor: string): bool =
  return buffer.document.getElementById(anchor) != nil

func getTitle(buffer: Buffer): string =
  if buffer.document != nil:
    let titles = buffer.document.getElementsByTag(TAG_TITLE)
    if titles.len > 0:
      for text in titles[0].textNodes:
        result &= text.data.strip().clearControls()
    return
  if buffer.ispipe:
    result = "*pipe*"
  else:
    result = $buffer.location

proc clearDisplay(buffer: Buffer) =
  buffer.prevdisplay = buffer.display
  buffer.display = newFixedGrid(buffer.width, buffer.height)

proc refreshDisplay(buffer: Buffer) =
  var r: Rune
  var y = 0
  buffer.clearDisplay()

  for line in buffer.lines[buffer.fromy..
                           buffer.lastVisibleLine - 1]:
    var w = 0
    var i = 0
    while w < buffer.fromx and i < line.str.len:
      fastRuneAt(line.str, i, r)
      w += r.width()

    let dls = y * buffer.width
    var k = 0
    var cf = line.findFormat(i)
    var nf = line.findNextFormat(i)
    if w > buffer.fromx:
      while k < w - buffer.fromx:
        buffer.display[dls + k].runes.add(Rune(' '))
        inc k

    while i < line.str.len:
      let j = i
      fastRuneAt(line.str, i, r)
      w += r.width()
      if w > buffer.fromx + buffer.width:
        break
      if nf.pos != -1 and nf.pos <= j:
        cf = nf
        nf = line.findNextFormat(j)
      buffer.display[dls + k].runes.add(r)
      if cf.pos != -1:
        buffer.display[dls + k].formatting = cf.formatting
        buffer.display[dls + k].nodes = cf.nodes
      let tk = k + r.width()
      while k < tk and k < buffer.width - 1:
        inc k

    inc y

proc setCursorXB(buffer: Buffer, byte: int) =
  var b = buffer.currentCursorBytes()
  var w = buffer.fromx + buffer.cursorx
  if b < byte:
    while b < byte:
      var r: Rune
      fastRuneAt(buffer.currentLine, b, r)
      w += r.width()
  else:
    while b > byte:
      let (r, o) = lastRune(buffer.currentLine, b)
      w -= r.width()
      b -= o

  let x = w
  if x - buffer.fromx >= 0 and x - buffer.width < buffer.fromx:
    buffer.cursorx = x
  else:
    if x > buffer.cursorx:
      buffer.fromx = max(x - buffer.width + 1, 0)
    elif x < buffer.cursorx:
      buffer.fromx = min(x, buffer.maxfromx)
    buffer.cursorx = x
    buffer.redraw = true
  buffer.xend = buffer.cursorx

proc setCursorX(buffer: Buffer, x: int, refresh = true, save = true) =
  if (not refresh) or (buffer.fromx <= x and x < buffer.fromx + buffer.width):
    buffer.cursorx = x
  else:
    if refresh and buffer.fromx > buffer.cursorx:
      buffer.fromx = max(buffer.currentLineWidth() - 1, 0)
      buffer.cursorx = buffer.fromx
    elif x > buffer.cursorx:
      buffer.fromx = max(x - buffer.width + 1, 0)
      buffer.cursorx = x
    elif x < buffer.cursorx:
      buffer.fromx = x
      buffer.cursorx = x
    buffer.redraw = true
  if save:
    buffer.xend = buffer.cursorx

proc restoreCursorX(buffer: Buffer) =
  buffer.setCursorX(max(min(buffer.currentLineWidth() - 1, buffer.xend), 0), false, false)

proc setCursorY(buffer: Buffer, y: int) =
  if buffer.cursory == y:
    return
  if y - buffer.fromy >= 0 and y - buffer.height < buffer.fromy:
    buffer.cursory = y
  else:
    if y > buffer.cursory:
      buffer.fromy = max(y - buffer.height + 1, 0)
    else:
      buffer.fromy = min(y, buffer.maxfromy)
    buffer.cursory = y
    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)

proc cursorUp*(buffer: Buffer) =
  if buffer.cursory > 0:
    buffer.setCursorY(buffer.cursory - 1)

proc cursorRight*(buffer: Buffer) =
  let cellwidth = buffer.currentWidth()
  if buffer.cursorx + cellwidth < buffer.currentLineWidth():
    buffer.setCursorX(buffer.cursorx + cellwidth)

proc cursorLeft*(buffer: Buffer) =
  buffer.setCursorX(max(buffer.cursorx - buffer.prevWidth(), 0))

proc cursorLineBegin*(buffer: Buffer) =
  buffer.setCursorX(0)

proc cursorLineEnd*(buffer: Buffer) =
  buffer.setCursorX(max(buffer.currentLineWidth() - 1, 0))

proc cursorNextWord*(buffer: Buffer) =
  var r: Rune
  var b = buffer.currentCursorBytes()
  var x = buffer.cursorx
  while b < buffer.currentLine.len:
    let pb = b
    fastRuneAt(buffer.currentLine, b, r)
    if r.breaksWord():
      b = pb
      break
    x += r.width()

  while b < buffer.currentLine.len:
    let pb = b
    fastRuneAt(buffer.currentLine, b, r)
    if not r.breaksWord():
      b = pb
      break
    x += r.width()

  if b < buffer.currentLine.len:
    buffer.setCursorX(x)
  else:
    if buffer.cursory < buffer.numLines - 1:
      buffer.cursorDown()
      buffer.cursorLineBegin()
    else:
      buffer.cursorLineEnd()

proc cursorPrevWord*(buffer: Buffer) =
  var b = buffer.currentCursorBytes()
  var x = buffer.cursorx
  if buffer.currentLine.len > 0:
    b = min(b, buffer.currentLine.len - 1)
    while b >= 0:
      let (r, o) = lastRune(buffer.currentLine, b)
      if r.breaksWord():
        break
      b -= o
      x -= r.width()

    while b >= 0:
      let (r, o) = lastRune(buffer.currentLine, b)
      if not r.breaksWord():
        break
      b -= o
      x -= r.width()
  else:
    b = -1

  if b >= 0:
    buffer.setCursorX(x)
  else:
    if buffer.cursory > 0:
      buffer.cursorUp()
      buffer.cursorLineEnd()
    else:
      buffer.cursorLineBegin()

proc cursorNextLink*(buffer: Buffer) =
  let line = buffer.lines[buffer.cursory]
  var i = line.findFormatN(buffer.currentCursorBytes()) - 1
  var link: Element = nil
  if i >= 0:
    link = line.formats[i].nodes.getLink()
  inc i

  while i < line.formats.len:
    let format = line.formats[i]
    let fl = format.nodes.getLink()
    if fl != nil and fl != link:
      buffer.setCursorXB(format.pos)
      return
    inc i

  for y in (buffer.cursory + 1)..(buffer.numLines - 1):
    let line = buffer.lines[y]
    i = 0
    while i < line.formats.len:
      let format = line.formats[i]
      let fl = format.nodes.getLink()
      if fl != nil and fl != link:
        buffer.setCursorXBY(format.pos, y)
        return
      inc i

proc cursorPrevLink*(buffer: Buffer) =
  let line = buffer.lines[buffer.cursory]
  var i = line.findFormatN(buffer.currentCursorBytes()) - 1
  var link: Element = nil
  if i >= 0:
    link = line.formats[i].nodes.getLink()
  dec i

  while i >= 0:
    let format = line.formats[i]
    let fl = format.nodes.getLink()
    if fl != nil and fl != link:
      buffer.setCursorXB(format.pos)
      return
    dec i

  for y in countdown(buffer.cursory - 1, 0):
    let line = buffer.lines[y]
    i = line.formats.len - 1
    while i >= 0:
      let format = line.formats[i]
      let fl = format.nodes.getLink()
      if fl != nil and fl != link:
        #go to beginning of link
        var ly = y #last y
        var lx = format.pos #last x
        for iy in countdown(ly - 1, 0):
          let line = buffer.lines[iy]
          i = line.formats.len - 1
          while i >= 0:
            let format = line.formats[i]
            let nl = format.nodes.getLink()
            if nl == fl:
              ly = iy
              lx = format.pos
            dec i
        buffer.setCursorXBY(lx, ly)
        return
      dec i

proc cursorFirstLine*(buffer: Buffer) =
  buffer.setCursorY(0)

proc cursorLastLine*(buffer: Buffer) =
  buffer.setCursorY(buffer.numLines - 1)

proc cursorTop*(buffer: Buffer) =
  buffer.setCursorY(buffer.fromy)

proc cursorMiddle*(buffer: Buffer) =
  buffer.setCursorY(min(buffer.fromy + (buffer.height - 2) div 2, buffer.numLines - 1))

proc cursorBottom*(buffer: Buffer) =
  buffer.setCursorY(min(buffer.fromy + buffer.height - 1, buffer.numLines - 1))

proc cursorLeftEdge*(buffer: Buffer) =
  buffer.setCursorX(buffer.fromx)

proc cursorVertMiddle*(buffer: Buffer) =
  buffer.setCursorX(min(buffer.fromx + (buffer.width - 2) div 2, buffer.currentLineWidth))

proc cursorRightEdge*(buffer: Buffer) =
  buffer.setCursorX(min(buffer.fromx + buffer.width - 1, buffer.currentLineWidth))

proc centerLine*(buffer: Buffer) =
  let ny = max(min(buffer.cursory - buffer.height div 2, buffer.numLines - buffer.height), 0)
  if ny != buffer.fromy:
    buffer.fromy = ny
    buffer.redraw = true

proc halfPageUp*(buffer: Buffer) =
  buffer.cursory = max(buffer.cursory - buffer.height div 2 + 1, 0)
  let nfy = max(0, buffer.fromy - buffer.height div 2 + 1)
  if nfy != buffer.fromy:
    buffer.fromy = nfy
    buffer.redraw = true
  buffer.restoreCursorX()

proc halfPageDown*(buffer: Buffer) =
  buffer.cursory = min(buffer.cursory + buffer.height div 2 - 1, buffer.numLines - 1)
  let nfy = min(max(buffer.numLines - buffer.height, 0), buffer.fromy + buffer.height div 2 - 1)
  if nfy != buffer.fromy:
    buffer.fromy = nfy
    buffer.redraw = true
  buffer.restoreCursorX()

proc pageUp*(buffer: Buffer) =
  buffer.cursory = max(buffer.cursory - buffer.height, 0)
  let nfy = max(0, buffer.fromy - buffer.height)
  if nfy != buffer.fromy:
    buffer.fromy = nfy
    buffer.redraw = true
  buffer.restoreCursorX()

proc pageDown*(buffer: Buffer) =
  buffer.cursory = min(buffer.cursory + buffer.height, buffer.numLines - 1)
  let nfy = min(buffer.fromy + buffer.height, max(buffer.numLines - buffer.height, 0))
  if nfy != buffer.fromy:
    buffer.fromy = nfy
    buffer.redraw = true
  buffer.restoreCursorX()

proc pageLeft*(buffer: Buffer) =
  buffer.cursorx = max(buffer.cursorx - buffer.width, 0)
  let nfx = max(0, buffer.fromx - buffer.width)
  if nfx != buffer.fromx:
    buffer.fromx = nfx
    buffer.redraw = true

proc pageRight*(buffer: Buffer) =
  buffer.cursorx = min(buffer.fromx, buffer.currentLineWidth())
  let nfx = min(max(buffer.maxScreenWidth() - buffer.width, 0), buffer.fromx + buffer.width)
  if nfx != buffer.fromx:
    buffer.fromx = nfx
    buffer.redraw = true

proc scrollDown*(buffer: Buffer) =
  if buffer.fromy + buffer.height < buffer.numLines:
    inc buffer.fromy
    if buffer.fromy > buffer.cursory:
      buffer.cursorDown()
    buffer.redraw = true
  else:
    buffer.cursorDown()

proc scrollUp*(buffer: Buffer) =
  if buffer.fromy > 0:
    dec buffer.fromy
    if buffer.fromy + buffer.height <= buffer.cursory:
      buffer.cursorUp()
    buffer.redraw = true
  else:
    buffer.cursorUp()

proc scrollRight*(buffer: Buffer) =
  if buffer.fromx + buffer.width < buffer.maxScreenWidth():
    inc buffer.fromx
    buffer.redraw = true

proc scrollLeft*(buffer: Buffer) =
  if buffer.fromx > 0:
    dec buffer.fromx
    if buffer.cursorx < buffer.fromx:
      buffer.setCursorX(max(buffer.currentLineWidth() - 1, 0))
    buffer.redraw = true

proc gotoAnchor*(buffer: Buffer) =
  let anchor = buffer.document.getElementById(buffer.location.anchor)
  if anchor == nil: return
  for y in 0..(buffer.numLines - 1):
    let line = buffer.lines[y]
    var i = 0
    while i < line.formats.len:
      let format = line.formats[i]
      if anchor in format.nodes:
        buffer.setCursorY(y)
        buffer.centerLine()
        buffer.setCursorXB(format.pos)
        return
      inc i

proc setLocation*(buffer: Buffer, location: Url) =
  buffer.location = location

proc gotoLocation*(buffer: Buffer, s: string) =
  discard parseUrl(s, buffer.location.some, buffer.location, true)

proc refreshTermAttrs*(buffer: Buffer): bool =
  let newAttrs = getTermAttributes()
  if newAttrs != buffer.attrs:
    buffer.attrs = newAttrs
    buffer.width = newAttrs.width
    buffer.height = newAttrs.height - 1
    return true
  return false

proc updateCursor(buffer: Buffer) =
  if buffer.fromy > buffer.lastVisibleLine - 1:
    buffer.fromy = 0
    buffer.cursory = buffer.lastVisibleLine - 1

  if buffer.lines.len == 0:
    buffer.cursory = 0

proc updateHover(buffer: Buffer) =
  let nodes = buffer.currentDisplayCell().nodes
  if nodes != buffer.prevnodes:
    for node in nodes:
      var elem: Element
      if node of Element:
        elem = Element(node)
      else:
        elem = node.parentElement
        assert elem != nil

      if not elem.hover and not (node in buffer.prevnodes):
        elem.hover = true
        buffer.reshape = true
        elem.refreshStyle()
    let link = nodes.getLink()
    if link != nil:
      if link.tagType == TAG_A:
        buffer.hovertext = parseUrl(HTMLAnchorElement(link).href, buffer.location.some).serialize()
    else:
      buffer.hovertext = ""
    for node in buffer.prevnodes:
      var elem: Element
      if node of Element:
        elem = Element(node)
      else:
        elem = node.parentElement
        assert elem != nil
      if elem.hover and not (node in nodes):
        elem.hover = false
        buffer.reshape = true
        elem.refreshStyle()
  buffer.prevnodes = nodes

proc load*(buffer: Buffer) =
  case buffer.contenttype
  of "text/html":
    if not buffer.streamclosed:
      #TODO not sure what to do with this.
      #Ideally we could just throw away the source data after parsing but then
      #source view won't work. Well we could still generate it... best would be a
      #config option like a) store source b) generate source
      buffer.source = buffer.istream.readAll()
      buffer.istream.close()
      buffer.streamclosed = true
    buffer.document = parseHtml(newStringStream(buffer.source))
  else:
    if not buffer.streamclosed:
      buffer.source = buffer.istream.readAll()
      buffer.istream.close()
      buffer.streamclosed = true
    buffer.lines = renderPlainText(buffer.source)

proc render*(buffer: Buffer) =
  case buffer.contenttype
  of "text/html":
    buffer.lines = renderDocument(buffer.document, buffer.attrs, buffer.userstyle)
  else: discard
  buffer.updateCursor()

proc cursorBufferPos(buffer: Buffer) =
  let x = buffer.acursorx
  let y = buffer.acursory
  print(HVP(y + 1, x + 1))

proc clearStatusMessage(buffer: Buffer) =
  buffer.statusmsg = newFixedGrid(buffer.width)

proc writeStatusMessage(buffer: Buffer, str: string, formatting: Formatting = Formatting()) =
  buffer.clearStatusMessage()
  var i = 0
  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
  var formatting: Formatting
  formatting.reverse = true
  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())

proc displayBufferSwapOutput(buffer: Buffer) =
  print(buffer.generateSwapOutput())

proc displayBuffer(buffer: Buffer) =
  print(buffer.generateFullOutput())

proc displayStatusMessage*(buffer: Buffer) =
  print(HVP(buffer.height + 1, 1))
  print(SGR())
  print(buffer.generateStatusMessage())
  print(SGR())

proc click*(buffer: Buffer): string =
  let link = buffer.getCursorLink()
  if link != nil:
    if link.tagType == TAG_A:
      return HTMLAnchorElement(link).href
  return ""

proc drawBuffer*(buffer: Buffer) =
  var formatting = newFormatting()
  for line in buffer.lines:
    if line.formats.len == 0:
      print(line.str & '\n')
    else:
      var x = 0
      for format in line.formats:
        print(line.str.substr(x, format.pos - 1))
        print(formatting.processFormatting(format.formatting))
        x = format.pos
      print(line.str.substr(x, line.str.len) & '\n')

proc refreshBuffer*(buffer: Buffer) =
  buffer.title = buffer.getTitle()
  stdout.hideCursor()

  if buffer.refreshTermAttrs():
    buffer.redraw = true
    buffer.reshape = true

  if buffer.redraw:
    buffer.refreshDisplay()
    buffer.displayBuffer()
    buffer.redraw = false

  buffer.updateHover()
  if buffer.reshape:
    buffer.render()
    buffer.reshape = false
    buffer.refreshDisplay()
    buffer.displayBufferSwapOutput()

  if not buffer.nostatus:
    buffer.statusMsgForBuffer()
  else:
    buffer.nostatus = false
  buffer.displayStatusMessage()
  buffer.cursorBufferPos()
  stdout.showCursor()