mirror of
https://github.com/Floriansylvain/GoEvalCalc.git
synced 2026-08-19 11:43:25 +02:00
109 lines
2.5 KiB
Go
109 lines
2.5 KiB
Go
package main
|
|
|
|
import (
|
|
"fmt"
|
|
"math"
|
|
|
|
"github.com/expr-lang/expr"
|
|
"github.com/gdamore/tcell/v2"
|
|
"github.com/rivo/tview"
|
|
)
|
|
|
|
func main() {
|
|
app := tview.NewApplication()
|
|
|
|
env := map[string]any{
|
|
"abs": math.Abs,
|
|
"acos": math.Acos,
|
|
"asin": math.Asin,
|
|
"atan": math.Atan,
|
|
"atan2": math.Atan2,
|
|
"ceil": math.Ceil,
|
|
"cos": math.Cos,
|
|
"cosh": math.Cosh,
|
|
"exp": math.Exp,
|
|
"floor": math.Floor,
|
|
"log": math.Log,
|
|
"log10": math.Log10,
|
|
"max": math.Max,
|
|
"min": math.Min,
|
|
"mod": math.Mod,
|
|
"pow": math.Pow,
|
|
"round": math.Round,
|
|
"sin": math.Sin,
|
|
"sinh": math.Sinh,
|
|
"sqrt": math.Sqrt,
|
|
"tan": math.Tan,
|
|
"tanh": math.Tanh,
|
|
"pi": math.Pi,
|
|
"e": math.E,
|
|
}
|
|
|
|
title := tview.NewTextView()
|
|
title.SetText("🧮 [::b]Math Expression Evaluator[-]")
|
|
title.SetTextAlign(tview.AlignCenter)
|
|
title.SetDynamicColors(true)
|
|
title.SetBorder(true)
|
|
title.SetBorderColor(tcell.ColorLightBlue)
|
|
|
|
result := tview.NewTextView()
|
|
result.SetDynamicColors(true)
|
|
result.SetWrap(true)
|
|
result.SetChangedFunc(func() { app.Draw() })
|
|
result.SetBorder(true)
|
|
result.SetTitle("Result")
|
|
result.SetTitleAlign(tview.AlignLeft)
|
|
|
|
help := tview.NewTextView()
|
|
help.SetText("[yellow]Functions: sqrt, pow, abs, sin, cos, tan...\nConstants: pi, e")
|
|
help.SetDynamicColors(true)
|
|
help.SetWrap(true)
|
|
help.SetBorder(true)
|
|
help.SetTitle("Help")
|
|
help.SetTitleAlign(tview.AlignLeft)
|
|
|
|
input := tview.NewInputField()
|
|
input.SetLabel("Expression: ")
|
|
input.SetFieldWidth(60)
|
|
input.SetDoneFunc(func(key tcell.Key) {
|
|
if key == tcell.KeyEnter {
|
|
exprStr := input.GetText()
|
|
|
|
program, err := expr.Compile(exprStr, expr.Env(env))
|
|
if err != nil {
|
|
result.SetText(fmt.Sprintf("[red]Compile error: %v", err))
|
|
return
|
|
}
|
|
output, err := expr.Run(program, env)
|
|
if err != nil {
|
|
result.SetText(fmt.Sprintf("[red]Runtime error: %v", err))
|
|
return
|
|
}
|
|
result.SetText(fmt.Sprintf("[green]Result: %v", output))
|
|
}
|
|
})
|
|
input.SetBorder(true)
|
|
input.SetTitle("Input")
|
|
input.SetTitleAlign(tview.AlignLeft)
|
|
|
|
mainFlex := tview.NewFlex()
|
|
mainFlex.SetDirection(tview.FlexRow)
|
|
mainFlex.AddItem(title, 3, 1, false)
|
|
mainFlex.AddItem(input, 5, 0, true)
|
|
mainFlex.AddItem(result, 5, 0, false)
|
|
mainFlex.AddItem(help, 3, 1, false)
|
|
|
|
app.SetRoot(mainFlex, true)
|
|
app.SetInputCapture(func(event *tcell.EventKey) *tcell.EventKey {
|
|
if event.Key() == tcell.KeyEsc || event.Key() == tcell.KeyCtrlC {
|
|
app.Stop()
|
|
return nil
|
|
}
|
|
return event
|
|
})
|
|
|
|
if err := app.Run(); err != nil {
|
|
panic(err)
|
|
}
|
|
}
|