tui/utils.go
Timon Ringwald dfa00f5fe3 more views
2022-04-02 13:01:41 +02:00

90 lines
2.0 KiB
Go

package tui
import (
"strings"
"golang.org/x/text/width"
)
// WriteString writes a whole string to the buffer at position (x,y)
// no word wrap is applied at all. If the string does not fit, it will be truncated
func WriteString(b *ViewBuffer, str string, style Style, x, y int) (width int) {
dx := x
for _, r := range str {
if dx >= b.Width() {
return
}
b.Set(dx, y, Rune{r, style})
dx += runeWidth(r)
}
return dx - x
}
// WriteMultiLineString writes a multi-line string to the buffer at position (x,y)
// no word wrap is applied at all. If a line does not fit horizontally, it will be truncated
// All lines which do not fit vertically will be truncated as well
func WriteMultiLineString(b *ViewBuffer, str string, style Style, x, y int) (maxLineWidth, lineCount int) {
lines := strings.Split(str, "\n")
for dy, line := range lines {
if dy >= b.Height() {
return
}
lineWidth := WriteString(b, line, style, x, y+dy)
maxLineWidth = max(maxLineWidth, lineWidth)
}
return maxLineWidth, len(lines)
}
// MeasureString measures how much horizontal space str consumes when drawn to a buffer
func MeasureString(str string) (width int) {
dx := 0
for _, r := range str {
dx += runeWidth(r)
}
return dx
}
// MeasureString measures how much horizontal and vertical space str consumes when drawn to a buffer
func MeasureMultiLineString(str string) (maxLineWidth, lineCount int) {
lines := strings.Split(str, "\n")
for _, line := range lines {
lineWidth := MeasureString(line)
maxLineWidth = max(maxLineWidth, lineWidth)
}
return maxLineWidth, len(lines)
}
func runeWidth(r rune) int {
//fmt.Println(r, width.LookupRune(r).Kind())
switch width.LookupRune(r).Kind() {
case width.EastAsianFullwidth:
fallthrough
case width.EastAsianWide:
return 2
default:
return 1
}
}
func min(x, y int) int {
if x < y {
return x
}
return y
}
func max(x, y int) int {
if x > y {
return x
}
return y
}
func iff[T any](condition bool, trueValue, falseValue T) T {
if condition {
return trueValue
}
return falseValue
}