forked from kungfusheep/glyph
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuffer.go
More file actions
1352 lines (1199 loc) · 32.1 KB
/
buffer.go
File metadata and controls
1352 lines (1199 loc) · 32.1 KB
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
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package glyph
import (
"context"
"fmt"
"sync/atomic"
"unicode/utf8"
"github.com/mattn/go-runewidth"
)
// Buffer is a 2D grid of cells representing a drawable surface.
type Buffer struct {
cells []Cell
width int
height int
dirtyMaxY int // highest row written to (for partial clear)
// Row-level dirty tracking for efficient flush
dirtyRows []bool
allDirty bool // true after Clear() - all rows need checking
}
// emptyBufferCache is a pre-filled buffer of empty cells for fast clearing via copy()
var emptyBufferCache []Cell
// NewBuffer creates a new buffer with the given dimensions.
func NewBuffer(width, height int) *Buffer {
cells := make([]Cell, width*height)
empty := EmptyCell()
for i := range cells {
cells[i] = empty
}
return &Buffer{
cells: cells,
width: width,
height: height,
dirtyRows: make([]bool, height),
allDirty: true, // new buffer needs full flush
}
}
// Width returns the buffer width.
func (b *Buffer) Width() int {
return b.width
}
// Height returns the buffer height.
func (b *Buffer) Height() int {
return b.height
}
// ContentHeight returns the number of rows that have been written to.
func (b *Buffer) ContentHeight() int {
return b.dirtyMaxY + 1
}
// Size returns the buffer dimensions.
func (b *Buffer) Size() (width, height int) {
return b.width, b.height
}
// InBounds returns true if the given coordinates are within the buffer.
func (b *Buffer) InBounds(x, y int) bool {
return x >= 0 && x < b.width && y >= 0 && y < b.height
}
// index converts x,y coordinates to a slice index.
func (b *Buffer) index(x, y int) int {
return y*b.width + x
}
// Get returns the cell at the given coordinates.
// Returns an empty cell if out of bounds.
func (b *Buffer) Get(x, y int) Cell {
if !b.InBounds(x, y) {
return EmptyCell()
}
return b.cells[b.index(x, y)]
}
// Set sets the cell at the given coordinates.
// Does nothing if out of bounds.
// When drawing border characters, automatically merges with existing borders.
func (b *Buffer) Set(x, y int, c Cell) {
if !b.InBounds(x, y) {
return
}
idx := b.index(x, y)
existing := b.cells[idx]
// Merge border characters
if merged, ok := mergeBorders(existing.Rune, c.Rune); ok {
c.Rune = merged
}
b.cells[idx] = c
// Track dirty region
if y > b.dirtyMaxY {
b.dirtyMaxY = y
}
b.dirtyRows[y] = true
}
// SetFast sets a cell without border merging. Use for text/progress where
// you know the content isn't a border character.
func (b *Buffer) SetFast(x, y int, c Cell) {
if y < 0 || y >= b.height || x < 0 || x >= b.width {
return
}
b.cells[y*b.width+x] = c
if y > b.dirtyMaxY {
b.dirtyMaxY = y
}
b.dirtyRows[y] = true
}
// Partial block characters for sub-character progress bar precision (1/8 to 8/8)
var partialBlocks = [9]rune{' ', '▏', '▎', '▍', '▌', '▋', '▊', '▉', '█'}
// WriteProgressBar writes a progress bar directly to the buffer.
// Uses partial block characters for smooth sub-character precision.
// Background color fills the empty space.
// Writes all cells in a single pass.
func (b *Buffer) WriteProgressBar(x, y, width int, ratio float32, style Style) {
if y < 0 || y >= b.height {
return
}
if y > b.dirtyMaxY {
b.dirtyMaxY = y
}
b.dirtyRows[y] = true
// Calculate fill in eighths for sub-character precision
totalEighths := int(ratio * float32(width) * 8)
if totalEighths < 0 {
totalEighths = 0
}
maxEighths := width * 8
if totalEighths > maxEighths {
totalEighths = maxEighths
}
fullBlocks := totalEighths / 8
partialEighths := totalEighths % 8
base := y * b.width
end := x + width
if end > b.width {
end = b.width
}
if x < 0 {
x = 0
}
dst := b.cells[base+x : base+end]
// bulk fill the filled region
if fullBlocks > 0 {
filledCell := Cell{Rune: '█', Style: style}
n := fullBlocks
if n > len(dst) {
n = len(dst)
}
dst[0] = filledCell
for filled := 1; filled < n; filled *= 2 {
copy(dst[filled:n], dst[:filled])
}
dst = dst[n:]
}
// single partial block cell
if partialEighths > 0 && len(dst) > 0 {
emptyBG := Color{Mode: ColorRGB, R: 60, G: 60, B: 60}
dst[0] = Cell{Rune: partialBlocks[partialEighths], Style: Style{FG: style.FG, BG: emptyBG}}
dst = dst[1:]
}
// bulk fill the empty region
if len(dst) > 0 {
emptyBG := Color{Mode: ColorRGB, R: 60, G: 60, B: 60}
dst[0] = Cell{Rune: ' ', Style: Style{BG: emptyBG}}
for filled := 1; filled < len(dst); filled *= 2 {
copy(dst[filled:], dst[:filled])
}
}
}
// WriteStringFast writes a string without border merging.
// Writes directly to the cell slice without border merging.
func (b *Buffer) WriteStringFast(x, y int, s string, style Style, maxWidth int) {
if y < 0 || y >= b.height {
return
}
if y > b.dirtyMaxY {
b.dirtyMaxY = y
}
b.dirtyRows[y] = true
base := y * b.width
written := 0
for _, r := range s {
if written >= maxWidth || x >= b.width {
break
}
if x >= 0 {
b.cells[base+x] = Cell{Rune: r, Style: style}
}
x++
written++
}
}
// WriteSpans writes multiple styled text spans sequentially.
// Each span has its own style. Spans are written left to right.
// Handles double-width CJK characters correctly.
func (b *Buffer) WriteSpans(x, y int, spans []Span, maxWidth int) {
if y < 0 || y >= b.height {
return
}
if y > b.dirtyMaxY {
b.dirtyMaxY = y
}
b.dirtyRows[y] = true
base := y * b.width
written := 0
for _, span := range spans {
for _, r := range span.Text {
rw := runewidth.RuneWidth(r)
if rw == 0 {
rw = 1 // treat zero-width as 1 for positioning
}
if written+rw > maxWidth || x+rw > b.width {
return
}
if x >= 0 {
b.cells[base+x] = Cell{Rune: r, Style: span.Style}
// for double-width chars, fill second cell with placeholder
if rw == 2 && x+1 < b.width {
b.cells[base+x+1] = Cell{Rune: 0, Style: span.Style}
}
}
x += rw
written += rw
}
}
}
// WriteLeader writes "Label.....Value" format with fill characters.
// The label is left-aligned, value is right-aligned, fill chars in between.
func (b *Buffer) WriteLeader(x, y int, label, value string, width int, fill rune, style Style) {
if y < 0 || y >= b.height {
return
}
if y > b.dirtyMaxY {
b.dirtyMaxY = y
}
b.dirtyRows[y] = true
if fill == 0 {
fill = '.'
}
base := y * b.width
labelLen := utf8.RuneCountInString(label)
valueLen := utf8.RuneCountInString(value)
// Calculate fill length
fillLen := width - labelLen - valueLen
if fillLen < 1 {
fillLen = 1 // at least one fill char
}
pos := x
// Write label
for _, r := range label {
if pos >= b.width || pos-x >= width {
return
}
if pos >= 0 {
b.cells[base+pos] = Cell{Rune: r, Style: style}
}
pos++
}
// Write fill
for i := 0; i < fillLen && pos < b.width && pos-x < width; i++ {
if pos >= 0 {
b.cells[base+pos] = Cell{Rune: fill, Style: style}
}
pos++
}
// Write value
for _, r := range value {
if pos >= b.width || pos-x >= width {
return
}
if pos >= 0 {
b.cells[base+pos] = Cell{Rune: r, Style: style}
}
pos++
}
}
// sparklineChars maps values 0-7 to Unicode block characters.
var sparklineChars = []rune{'▁', '▂', '▃', '▄', '▅', '▆', '▇', '█'}
func sparklineWindow(dataLen, width int) (start, cols, offset int) {
if width <= 0 || dataLen <= 0 {
return 0, 0, 0
}
start = 0
if dataLen > width {
start = dataLen - width
}
cols = dataLen - start
if cols > width {
cols = width
}
offset = width - cols
return start, cols, offset
}
func sparklineRange(values []float64, start, cols int, min, max float64) (float64, float64) {
if min != 0 || max != 0 || cols <= 0 {
return min, max
}
window := values[start : start+cols]
min, max = window[0], window[0]
for _, v := range window[1:] {
if v < min {
min = v
}
if v > max {
max = v
}
}
return min, max
}
// WriteSparkline writes a sparkline chart using Unicode block characters.
func (b *Buffer) WriteSparkline(x, y int, values []float64, width int, min, max float64, style Style) {
if y < 0 || y >= b.height || len(values) == 0 || width <= 0 {
return
}
if y > b.dirtyMaxY {
b.dirtyMaxY = y
}
b.dirtyRows[y] = true
base := y * b.width
dataLen := len(values)
// render right-aligned: newest data at right edge, old data scrolls off left
start, cols, offset := sparklineWindow(dataLen, width)
min, max = sparklineRange(values, start, cols, min, max)
// Handle case where all values are the same
valRange := max - min
if valRange == 0 {
valRange = 1
}
for i := 0; i < width && x+i < b.width; i++ {
dataIdx := start + (i - offset)
if dataIdx < 0 || dataIdx >= dataLen {
if x+i >= 0 {
b.cells[base+x+i] = Cell{Rune: ' ', Style: style}
}
continue
}
// Normalize value to 0-7 range
normalized := (values[dataIdx] - min) / valRange
if normalized < 0 {
normalized = 0
} else if normalized > 1 {
normalized = 1
}
charIdx := int(normalized * 7.99) // 0-7
if charIdx > 7 {
charIdx = 7
}
if x+i >= 0 {
b.cells[base+x+i] = Cell{Rune: sparklineChars[charIdx], Style: style}
}
}
}
// WriteSparklineMulti writes a multi-row sparkline chart.
// total vertical resolution is height * 8 levels.
// renders bottom-up: full blocks for saturated rows, fractional block for the top cell, space above.
func (b *Buffer) WriteSparklineMulti(x, y int, values []float64, width, height int, min, max float64, style Style) {
if height <= 0 || width <= 0 || len(values) == 0 {
return
}
totalLevels := height * 8
dataLen := len(values)
// right-aligned: newest data at right edge, 1:1 mapping
startData, cols, colOffset := sparklineWindow(dataLen, width)
min, max = sparklineRange(values, startData, cols, min, max)
valRange := max - min
if valRange == 0 {
valRange = 1
}
for i := 0; i < width && x+i < b.width; i++ {
if x+i < 0 {
continue
}
dataIdx := startData + (i - colOffset)
if dataIdx < 0 || dataIdx >= dataLen {
for row := 0; row < height; row++ {
ry := y + height - 1 - row
if ry >= 0 && ry < b.height {
b.cells[ry*b.width+x+i] = Cell{Rune: ' ', Style: style}
}
}
continue
}
normalized := (values[dataIdx] - min) / valRange
if normalized < 0 {
normalized = 0
} else if normalized > 1 {
normalized = 1
}
// how many eighth-levels this value fills
filled := int(normalized * float64(totalLevels))
if filled > totalLevels {
filled = totalLevels
}
// render rows bottom-up
for row := 0; row < height; row++ {
ry := y + height - 1 - row // screen y: bottom row first
if ry < 0 || ry >= b.height {
continue
}
rowLevels := filled - row*8 // levels remaining for this row
var r rune
if rowLevels >= 8 {
r = '█'
} else if rowLevels > 0 {
r = sparklineChars[rowLevels]
} else {
r = ' '
}
b.cells[ry*b.width+x+i] = Cell{Rune: r, Style: style}
if ry > b.dirtyMaxY {
b.dirtyMaxY = ry
}
b.dirtyRows[ry] = true
}
}
}
// SetRune sets just the rune at the given coordinates, preserving style.
func (b *Buffer) SetRune(x, y int, r rune) {
if !b.InBounds(x, y) {
return
}
idx := b.index(x, y)
b.cells[idx].Rune = r
}
// SetStyle sets just the style at the given coordinates, preserving rune.
func (b *Buffer) SetStyle(x, y int, s Style) {
if !b.InBounds(x, y) {
return
}
idx := b.index(x, y)
b.cells[idx].Style = s
}
// Fill fills the entire buffer with the given cell.
func (b *Buffer) Fill(c Cell) {
for i := range b.cells {
b.cells[i] = c
}
}
// Clear clears the buffer to empty cells with default style.
// Uses copy() from a cached empty buffer.
func (b *Buffer) Clear() {
size := len(b.cells)
// Grow cache if needed (one-time cost)
if len(emptyBufferCache) < size {
emptyBufferCache = make([]Cell, size)
empty := EmptyCell()
for i := range emptyBufferCache {
emptyBufferCache[i] = empty
}
}
// Fast path: copy uses optimized memmove
copy(b.cells, emptyBufferCache[:size])
b.dirtyMaxY = 0
b.allDirty = true
// Clear individual row flags (allDirty takes precedence)
for i := range b.dirtyRows {
b.dirtyRows[i] = false
}
}
// RowDirty returns true if the given row has been modified since last ClearDirtyFlags.
// If allDirty is set (after Clear/Resize), all rows are considered dirty.
func (b *Buffer) RowDirty(y int) bool {
if b.allDirty {
return true
}
if y < 0 || y >= len(b.dirtyRows) {
return false
}
return b.dirtyRows[y]
}
// ClearDirtyFlags resets all row dirty flags after a flush.
// Call this after Screen.Flush() to start tracking changes for next frame.
func (b *Buffer) ClearDirtyFlags() {
b.allDirty = false
for i := range b.dirtyRows {
b.dirtyRows[i] = false
}
}
// MarkAllDirty forces all rows to be considered dirty.
// Useful after external modifications or for testing.
func (b *Buffer) MarkAllDirty() {
b.allDirty = true
}
// ResetDirtyMax resets the dirty tracking without clearing content.
// Use when you know the template will overwrite all cells.
func (b *Buffer) ResetDirtyMax() {
b.dirtyMaxY = -1
}
// ClearDirty clears only the rows that were written to since last clear.
// Useful when content doesn't fill the buffer.
func (b *Buffer) ClearDirty() {
if b.dirtyMaxY < 0 {
return
}
// Only clear rows 0..dirtyMaxY
size := (b.dirtyMaxY + 1) * b.width
if size > len(b.cells) {
size = len(b.cells)
}
// Ensure cache is big enough
if len(emptyBufferCache) < size {
emptyBufferCache = make([]Cell, len(b.cells))
empty := EmptyCell()
for i := range emptyBufferCache {
emptyBufferCache[i] = empty
}
}
copy(b.cells[:size], emptyBufferCache[:size])
// Mark cleared rows as dirty (content changed) and reset tracking
for y := 0; y <= b.dirtyMaxY && y < b.height; y++ {
b.dirtyRows[y] = true
}
b.dirtyMaxY = 0
}
// ClearLine clears a single line to empty cells.
func (b *Buffer) ClearLine(y int) {
if y < 0 || y >= b.height {
return
}
base := y * b.width
empty := EmptyCell()
for x := 0; x < b.width; x++ {
b.cells[base+x] = empty
}
b.dirtyRows[y] = true
}
// ClearLineWithStyle clears a single line with a styled space cell.
func (b *Buffer) ClearLineWithStyle(y int, style Style) {
if y < 0 || y >= b.height {
return
}
base := y * b.width
cell := Cell{Rune: ' ', Style: style}
for x := 0; x < b.width; x++ {
b.cells[base+x] = cell
}
b.dirtyRows[y] = true
}
// FillRect fills a rectangular region with the given cell.
// Uses direct slice writes (no border merge) for non-border cells,
// falls back to Set() only when the cell is a border character.
func (b *Buffer) FillRect(x, y, width, height int, c Cell) {
// fast path: non-border fills bypass Set() entirely
if c.Rune < boxDrawingMin || c.Rune > boxDrawingMax {
for dy := 0; dy < height; dy++ {
row := y + dy
if row < 0 || row >= b.height {
continue
}
if row > b.dirtyMaxY {
b.dirtyMaxY = row
}
b.dirtyRows[row] = true
base := row * b.width
for dx := 0; dx < width; dx++ {
col := x + dx
if col >= 0 && col < b.width {
b.cells[base+col] = c
}
}
}
return
}
for dy := 0; dy < height; dy++ {
for dx := 0; dx < width; dx++ {
b.Set(x+dx, y+dy, c)
}
}
}
// WriteString writes a string at the given coordinates with the given style.
// Returns the number of cells written.
func (b *Buffer) WriteString(x, y int, s string, style Style) int {
written := 0
for _, r := range s {
if !b.InBounds(x, y) {
break
}
b.Set(x, y, NewCell(r, style))
x++
written++
}
return written
}
// WriteStringClipped writes a string, stopping at maxWidth.
// Returns the number of cells written.
func (b *Buffer) WriteStringClipped(x, y int, s string, style Style, maxWidth int) int {
written := 0
for _, r := range s {
if written >= maxWidth || !b.InBounds(x, y) {
break
}
b.Set(x, y, NewCell(r, style))
x++
written++
}
return written
}
// WriteStringPadded writes a string and pads with spaces to fill width.
// This allows skipping Clear() when UI structure is stable.
func (b *Buffer) WriteStringPadded(x, y int, s string, style Style, width int) {
written := 0
for _, r := range s {
if written >= width || !b.InBounds(x, y) {
break
}
b.Set(x, y, NewCell(r, style))
x++
written++
}
// Pad with spaces
space := NewCell(' ', style)
for written < width && b.InBounds(x, y) {
b.Set(x, y, space)
x++
written++
}
}
// HLine draws a horizontal line of the given rune.
func (b *Buffer) HLine(x, y, length int, r rune, style Style) {
for i := 0; i < length; i++ {
b.Set(x+i, y, NewCell(r, style))
}
}
// VLine draws a vertical line of the given rune.
func (b *Buffer) VLine(x, y, length int, r rune, style Style) {
for i := 0; i < length; i++ {
b.Set(x, y+i, NewCell(r, style))
}
}
// Box drawing characters for borders.
const (
BoxHorizontal = '─'
BoxVertical = '│'
BoxTopLeft = '┌'
BoxTopRight = '┐'
BoxBottomLeft = '└'
BoxBottomRight = '┘'
BoxRoundedTopLeft = '╭'
BoxRoundedTopRight = '╮'
BoxRoundedBottomLeft = '╰'
BoxRoundedBottomRight = '╯'
BoxDoubleHorizontal = '═'
BoxDoubleVertical = '║'
BoxDoubleTopLeft = '╔'
BoxDoubleTopRight = '╗'
BoxDoubleBottomLeft = '╚'
BoxDoubleBottomRight = '╝'
)
// Box junction characters for merged borders
const (
BoxTeeDown = '┬' // ─ meets │ from below
BoxTeeUp = '┴' // ─ meets │ from above
BoxTeeRight = '├' // │ meets ─ from right
BoxTeeLeft = '┤' // │ meets ─ from left
BoxCross = '┼' // all four directions
)
// Box drawing range constants for fast rejection
const (
boxDrawingMin = 0x2500
boxDrawingMax = 0x257F
)
// borderEdgesArray provides O(1) lookup for border edge bits
// Index = rune - boxDrawingMin, value = edge bits (0 = not a border char)
// Using bits: 1=top, 2=right, 4=bottom, 8=left
var borderEdgesArray = [128]uint8{
0x00: 0b1010, // ─ BoxHorizontal (0x2500)
0x02: 0b0101, // │ BoxVertical (0x2502)
0x0C: 0b0110, // ┌ BoxTopLeft (0x250C)
0x10: 0b1100, // ┐ BoxTopRight (0x2510)
0x14: 0b0011, // └ BoxBottomLeft (0x2514)
0x18: 0b1001, // ┘ BoxBottomRight (0x2518)
0x1C: 0b0111, // ├ BoxTeeRight (0x251C)
0x24: 0b1101, // ┤ BoxTeeLeft (0x2524)
0x2C: 0b1110, // ┬ BoxTeeDown (0x252C)
0x34: 0b1011, // ┴ BoxTeeUp (0x2534)
0x3C: 0b1111, // ┼ BoxCross (0x253C)
0x6D: 0b0110, // ╭ BoxRoundedTopLeft (0x256D)
0x6E: 0b1100, // ╮ BoxRoundedTopRight (0x256E)
0x6F: 0b1001, // ╯ BoxRoundedBottomRight (0x256F)
0x70: 0b0011, // ╰ BoxRoundedBottomLeft (0x2570)
// single-direction stubs — allow merge to produce T/cross junctions
0x74: 0b1000, // ╴ left stub (0x2574): merges │+╴ → ┤, ─+╴ → ─
0x75: 0b0001, // ╵ up stub (0x2575): merges ─+╵ → ┴
0x76: 0b0010, // ╶ right stub (0x2576): merges │+╶ → ├, ─+╶ → ─
0x77: 0b0100, // ╷ down stub (0x2577): merges ─+╷ → ┬
}
// edgesToBorderArray provides O(1) lookup from edge bits to border rune
// Index = edge bits (0-15), value = border rune (0 = invalid)
var edgesToBorderArray = [16]rune{
0b0011: BoxBottomLeft,
0b0101: BoxVertical,
0b0110: BoxTopLeft,
0b0111: BoxTeeRight,
0b1001: BoxBottomRight,
0b1010: BoxHorizontal,
0b1011: BoxTeeUp,
0b1100: BoxTopRight,
0b1101: BoxTeeLeft,
0b1110: BoxTeeDown,
0b1111: BoxCross,
}
// mergeBorders combines two border characters into one.
// Returns the merged rune and true if both were border chars, otherwise false.
func mergeBorders(existing, new rune) (rune, bool) {
// Fast path: reject non-border characters immediately (99% of calls)
if existing < boxDrawingMin || existing > boxDrawingMax {
return new, false
}
if new < boxDrawingMin || new > boxDrawingMax {
return new, false
}
// Array lookup for edge bits
existingEdges := borderEdgesArray[existing-boxDrawingMin]
newEdges := borderEdgesArray[new-boxDrawingMin]
if existingEdges == 0 || newEdges == 0 {
return new, false
}
// Merge and lookup result
merged := existingEdges | newEdges
if result := edgesToBorderArray[merged]; result != 0 {
return result, true
}
return new, false
}
// BorderStyle defines the characters used for drawing borders.
type BorderStyle struct {
Horizontal rune
Vertical rune
TopLeft rune
TopRight rune
BottomLeft rune
BottomRight rune
}
// Standard border styles.
var (
BorderSingle = BorderStyle{
Horizontal: BoxHorizontal,
Vertical: BoxVertical,
TopLeft: BoxTopLeft,
TopRight: BoxTopRight,
BottomLeft: BoxBottomLeft,
BottomRight: BoxBottomRight,
}
BorderRounded = BorderStyle{
Horizontal: BoxHorizontal,
Vertical: BoxVertical,
TopLeft: BoxRoundedTopLeft,
TopRight: BoxRoundedTopRight,
BottomLeft: BoxRoundedBottomLeft,
BottomRight: BoxRoundedBottomRight,
}
BorderDouble = BorderStyle{
Horizontal: BoxDoubleHorizontal,
Vertical: BoxDoubleVertical,
TopLeft: BoxDoubleTopLeft,
TopRight: BoxDoubleTopRight,
BottomLeft: BoxDoubleBottomLeft,
BottomRight: BoxDoubleBottomRight,
}
)
// DrawBorder draws a border around the given rectangle.
func (b *Buffer) DrawBorder(x, y, width, height int, border BorderStyle, style Style) {
if width < 2 || height < 2 {
return
}
// Corners
b.Set(x, y, NewCell(border.TopLeft, style))
b.Set(x+width-1, y, NewCell(border.TopRight, style))
b.Set(x, y+height-1, NewCell(border.BottomLeft, style))
b.Set(x+width-1, y+height-1, NewCell(border.BottomRight, style))
// Horizontal lines
for i := 1; i < width-1; i++ {
b.Set(x+i, y, NewCell(border.Horizontal, style))
b.Set(x+i, y+height-1, NewCell(border.Horizontal, style))
}
// Vertical lines
for i := 1; i < height-1; i++ {
b.Set(x, y+i, NewCell(border.Vertical, style))
b.Set(x+width-1, y+i, NewCell(border.Vertical, style))
}
}
// Region returns a view into a rectangular region of the buffer.
// The returned Region shares the underlying cells with the parent buffer.
type Region struct {
buf *Buffer
x, y int
width int
height int
}
// Region creates a view into a rectangular region of the buffer.
func (b *Buffer) Region(x, y, width, height int) *Region {
return &Region{
buf: b,
x: x,
y: y,
width: width,
height: height,
}
}
// Width returns the region width.
func (r *Region) Width() int {
return r.width
}
// Height returns the region height.
func (r *Region) Height() int {
return r.height
}
// Size returns the region dimensions.
func (r *Region) Size() (width, height int) {
return r.width, r.height
}
// InBounds returns true if the given coordinates are within the region.
func (r *Region) InBounds(x, y int) bool {
return x >= 0 && x < r.width && y >= 0 && y < r.height
}
// Get returns the cell at the given region-relative coordinates.
func (r *Region) Get(x, y int) Cell {
if !r.InBounds(x, y) {
return EmptyCell()
}
return r.buf.Get(r.x+x, r.y+y)
}
// Set sets the cell at the given region-relative coordinates.
func (r *Region) Set(x, y int, c Cell) {
if !r.InBounds(x, y) {
return
}
r.buf.Set(r.x+x, r.y+y, c)
}
// Fill fills the region with the given cell.
func (r *Region) Fill(c Cell) {
for y := 0; y < r.height; y++ {
for x := 0; x < r.width; x++ {
r.Set(x, y, c)
}
}
}
// Clear clears the region to empty cells.
func (r *Region) Clear() {
r.Fill(EmptyCell())
}
// WriteString writes a string at the given region-relative coordinates.
func (r *Region) WriteString(x, y int, s string, style Style) int {
written := 0
for _, ch := range s {
if !r.InBounds(x, y) {
break
}
r.Set(x, y, NewCell(ch, style))
x++
written++
}
return written
}
// DrawBorder draws a border around the entire region.
func (r *Region) DrawBorder(border BorderStyle, style Style) {
if r.width < 2 || r.height < 2 {
return
}
// Corners
r.Set(0, 0, NewCell(border.TopLeft, style))
r.Set(r.width-1, 0, NewCell(border.TopRight, style))
r.Set(0, r.height-1, NewCell(border.BottomLeft, style))
r.Set(r.width-1, r.height-1, NewCell(border.BottomRight, style))
// Horizontal lines
for i := 1; i < r.width-1; i++ {
r.Set(i, 0, NewCell(border.Horizontal, style))
r.Set(i, r.height-1, NewCell(border.Horizontal, style))
}
// Vertical lines
for i := 1; i < r.height-1; i++ {
r.Set(0, i, NewCell(border.Vertical, style))
r.Set(r.width-1, i, NewCell(border.Vertical, style))
}
}
// GetLine returns the content of a single line as a string (trimmed).
func (b *Buffer) GetLine(y int) string {
if y < 0 || y >= b.height {
return ""
}
var line []byte
lastNonSpace := -1
for x := 0; x < b.width; x++ {
c := b.Get(x, y)
r := c.Rune
if r == 0 {
r = ' '
}
line = append(line, string(r)...)
if r != ' ' {
lastNonSpace = len(line)
}
}
if lastNonSpace >= 0 {