From c45883174aa26f9032f2c35867149971bf019525 Mon Sep 17 00:00:00 2001 From: Sam Anthony Date: Sat, 29 Jul 2023 16:37:16 -0230 Subject: limit width of window --- calc.go | 11 ++++------- ui.go | 29 +++++++++++++++++++++-------- 2 files changed, 25 insertions(+), 15 deletions(-) diff --git a/calc.go b/calc.go index 4eab368..e6897fe 100644 --- a/calc.go +++ b/calc.go @@ -1,9 +1,6 @@ package main -import ( - "strconv" - "strings" -) +import "strconv" type AngleMode bool @@ -36,7 +33,7 @@ func (c *Calculator) swap() { c.stack.push(f) } if st != nil { - c.buf = strings.TrimSpace(printNum(*st)) + c.buf = printNum(*st) } else { c.buf = "" } @@ -46,9 +43,9 @@ func (c *Calculator) swap() { // stack, if any. func (c *Calculator) negate() { if con := parseConstant(c.buf); con != nil { - c.buf = strings.TrimSpace(printNum(-*con)) + c.buf = printNum(-*con) } else if f, err := strconv.ParseFloat(c.buf, 64); err == nil { - c.buf = strings.TrimSpace(printNum(-f)) + c.buf = printNum(-f) } else if len(c.buf) == 0 && len(c.stack) > 0 { c.stack[len(c.stack)-1] = -c.stack[len(c.stack)-1] } diff --git a/ui.go b/ui.go index af4d101..46f748e 100644 --- a/ui.go +++ b/ui.go @@ -20,6 +20,9 @@ const ( // sigDigs is the number of significant digits when printing a number. const sigDigs = 17 +// maxWidth is the maximum width that the window will grow to. +const maxWidth = 32 + type UI struct { calc Calculator width int // Width of the window measured in characters. @@ -77,22 +80,24 @@ func (ui UI) Update(msg tea.Msg) (tea.Model, tea.Cmd) { func (ui UI) View() string { s := padding(ui) + width := min(ui.width, maxWidth) + // Angle mode. - s += fmt.Sprintf("%*s\n", ui.width-1, ui.calc.anglem) + s += fmt.Sprintf("%*s\n", width-1, ui.calc.anglem) // Stack. - top := boxTop(ui.width) - bottom := boxBottom(ui.width) + top := boxTop(width) + bottom := boxBottom(width) s += top + "\n" for _, f := range ui.calc.stack { - s += fmt.Sprintf("%[1]c%*s%[1]c\n", boxVertical, ui.width-2, printNum(f)) + s += fmt.Sprintf("%[1]c%[2]*.[2]*s%[1]c\n", boxVertical, width-2, printNum(f)) } s += bottom + "\n" // Buffer. - s += boxTop(ui.width) + "\n" - s += fmt.Sprintf("%[1]c%*s%[1]c\n", boxVertical, ui.width-2, ui.calc.buf) - s += boxBottom(ui.width) + s += top + "\n" + s += fmt.Sprintf("%[1]c>%[2]*.[2]*s%[1]c\n", boxVertical, width-3, ui.calc.buf) + s += bottom return s } @@ -114,7 +119,7 @@ func padding(ui UI) string { } func printNum(v float64) string { - return fmt.Sprintf(" %.*g", sigDigs, v) + return fmt.Sprintf("%.*g", sigDigs, v) } // boxTop returns the top of a UTF-8 box, 'width' characters wide (including @@ -153,3 +158,11 @@ func fill(s []rune, c rune) { s[i] = c } } + +// min returns the lesser of x or y. +func min(x, y int) int { + if x < y { + return x + } + return y +} -- cgit v1.2.3