aboutsummaryrefslogtreecommitdiffstats
path: root/internal/render/render.go
blob: cf1dc60646151c9259a68aef75bcd185c91eb692 (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
// Copyright 2026 Rose Hogenson <r@roseh.moe>
//
// This file is part of ccp.
//
// Ccp is free software: you can redistribute it and/or modify it under the
// terms of the GNU General Public License as published by the Free Software
// Foundation, either version 3 of the License, or (at your option) any later
// version.
//
// Ccp is distributed in the hope that it will be useful, but WITHOUT ANY
// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
// FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
// details.
//
// You should have received a copy of the GNU General Public License along with
// ccp. If not, see <https://www.gnu.org/licenses/>.

// Package render renders to the terminal using ANSI escape sequences.
package render

import (
	"bufio"
	"bytes"
	"fmt"
	"os"

	runewidth "github.com/mattn/go-runewidth"
)

// Renderer updates a terminal UI. Typical usage looks like
//
//	r := render.New()
//	// Game loop
//	for {
//	    // Update state
//
//	    r.Clear()
//	    fmt.Fprintf(r, "Render UI by writing to r using io.Writer")
//	    r.Flush()
//	}
type Renderer struct {
	w              bufio.Writer
	prevLines      int
	width          int
	partialLineLen int
}

// New creates a new Renderer
func New() *Renderer {
	r := &Renderer{}
	r.w.Reset(os.Stderr)
	return r
}

// Clear clears the screen before rendering a new frame.
func (r *Renderer) Clear(width int) {
	r.width = width
	if r.prevLines > 0 {
		fmt.Fprintf(&r.w, "\033[%dA", r.prevLines)
	}
	r.w.WriteString("\r")
	r.prevLines = 0
	r.partialLineLen = 0
}

func truncate(b []byte, width int) ([]byte, int) {
	str := string(b)
	currentWidth := 0
	for i := 0; i < len(b); {
		chunkBytes := bytes.Index(b[i:], []byte("\033["))
		if chunkBytes < 0 {
			chunkBytes = len(b) - i
		} else if chunkBytes == 0 {
			// An escape sequence usually starts with [, then has one or two numbers
			// separated by semicolon, and ends with some terminating character. To
			// try and munch the whole sequence, skip over any numbers and
			// semicolon here.
			for i += 2; i < len(b)-1 && ('0' <= b[i] && b[i] <= '9' || b[i] == ';'); i++ {
			}
			// Skip the terminating character.
			i++
			continue
		}
		chunkWidth := runewidth.StringWidth(str[i : i+chunkBytes])
		if currentWidth+chunkWidth <= width {
			i += chunkBytes
			currentWidth += chunkWidth
			continue
		}
		lastChunk := runewidth.Truncate(str[i:i+chunkBytes], width-currentWidth, "")
		return b[:i+len(lastChunk)], width
	}
	return b, currentWidth
}

// Write implements io.Writer.
func (r *Renderer) Write(buf []byte) (int, error) {
	totalBytes := 0
	for len(buf) > 0 {
		i := bytes.IndexByte(buf, '\n')
		if i < 0 {
			line, lineWidth := truncate(buf, r.width-r.partialLineLen)
			r.partialLineLen += lineWidth
			if n, err := r.w.Write(line); err != nil {
				return totalBytes + n, err
			}
			totalBytes += len(buf)
			return totalBytes, nil
		}
		line, _ := truncate(buf[:i], r.width)
		buf = buf[i+1:]
		if n, err := r.w.Write(line); err != nil {
			return totalBytes + n, err
		}
		totalBytes += i
		if _, err := r.w.WriteString("\033[K\n"); err != nil {
			return totalBytes, err
		}
		totalBytes++
		r.prevLines++
		r.partialLineLen = 0
	}
	return totalBytes, nil
}

// Flush flushes the internal buffer to stdout. Flush should be called at the
// end of every frame.
func (r *Renderer) Flush() {
	r.w.WriteString("\033[J")
	r.w.Flush()
}